This commit is contained in:
nihil 2024-11-03 17:16:20 +01:00
commit fd6412d6f2
8090 changed files with 778406 additions and 0 deletions

13
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,13 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "build",
"group": "build",
"problemMatcher": [],
"label": "npm: build",
"detail": "run-s build:*"
}
]
}

58
_site/400/index.html Normal file
View File

@ -0,0 +1,58 @@
<!DOCTYPE html>
<html class="bg-gradient-to-t from-black to-purple-900 bg-fixed" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex, nofollow" />
<title>nihil's abode</title>
<meta name="description" content="nihil's humble abode on the interweb">
<link rel="stylesheet" href="/assets/css/tailwind.css">
<link rel="icon" type="image/x-icon" href="/assets/img/favicon.png">
<script src="/scripts/jquery-3.7.1.min.js"></script>
</head>
<body class="">
<script src="/scripts/oneko.js"></script>
<div class="flex flex-col min-h-screen items-center">
<header class="xl:h-4/10 flex justify-center items-center flex-col w-4/5 lg:2/3">
<h1 class="my-6 animate-text-shadow-pop">X_X</h1>
<nav class="flex flex-auto flex-col justify-center justify-items-center font-heading lg:text-3xl text-xl md:text-2xl w-4/5 flex-wrap h-2/10">
<div class="flex flex-row flex-wrap justify-items-center justify-center">
<a class="nav-link" href="/">home</a>
<a class="nav-link" href="/about/">about</a>
<a class="nav-link" href="/posts/">posts</a>
<a class="nav-link" href="/resources/">resources</a>
<a class="nav-link" href="/status/">status</a>
</div>
<hr class="hr-main">
</nav>
</header>
<main class="flex flex-col text-2xl font-body text-center mb-auto h-4/10 w-4/5 items-center justify-center tracking-wide">
<h2 class="mb-4 animate-text-shadow-pop">400 level oopsie! :c</h2>
<div class="flex flex-col justify-around items-center font-bold w-4/5 xl:w-2/3 text-pink-200">
whatever request you performed resulted in a client side error :c
</div>
</main>
<footer class="text-3xl text-pink-100 font-heading flex flex-col items-center justify-center h-2/10 mb-10 w-4/5 lg:w-2/3">
<hr class="hr-main">
<div class="text-center w-full">
Part of the REDACTED webring!
<br>
<br>
<div class="flex items-center justify-center">
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">← Bother the Doll</div>
</a>
<a class="transition-all duration-200" href="https://valhrafnaz.gay">
<div class="text-purple-300 hover:text-pink-600 w-max mx-20 hover:animate-bounce">nihil :3</div>
</a>
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">Bother the Doll →</div>
</a>
<div>
</div>
</footer>
</div>
</body>
</html>

58
_site/500/index.html Normal file
View File

@ -0,0 +1,58 @@
<!DOCTYPE html>
<html class="bg-gradient-to-t from-black to-purple-900 bg-fixed" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex, nofollow" />
<title>nihil's abode</title>
<meta name="description" content="nihil's humble abode on the interweb">
<link rel="stylesheet" href="/assets/css/tailwind.css">
<link rel="icon" type="image/x-icon" href="/assets/img/favicon.png">
<script src="/scripts/jquery-3.7.1.min.js"></script>
</head>
<body class="">
<script src="/scripts/oneko.js"></script>
<div class="flex flex-col min-h-screen items-center">
<header class="xl:h-4/10 flex justify-center items-center flex-col w-4/5 lg:2/3">
<h1 class="my-6 animate-text-shadow-pop">X_X</h1>
<nav class="flex flex-auto flex-col justify-center justify-items-center font-heading lg:text-3xl text-xl md:text-2xl w-4/5 flex-wrap h-2/10">
<div class="flex flex-row flex-wrap justify-items-center justify-center">
<a class="nav-link" href="/">home</a>
<a class="nav-link" href="/about/">about</a>
<a class="nav-link" href="/posts/">posts</a>
<a class="nav-link" href="/resources/">resources</a>
<a class="nav-link" href="/status/">status</a>
</div>
<hr class="hr-main">
</nav>
</header>
<main class="flex flex-col text-2xl font-body text-center mb-auto h-4/10 w-4/5 items-center justify-center tracking-wide">
<h2 class="mb-4 animate-text-shadow-pop">500 level oopsie! :c</h2>
<div class="flex flex-col justify-around items-center font-bold w-4/5 xl:w-2/3 text-pink-200">
whatever request you performed resulted in a server side error :c
</div>
</main>
<footer class="text-3xl text-pink-100 font-heading flex flex-col items-center justify-center h-2/10 mb-10 w-4/5 lg:w-2/3">
<hr class="hr-main">
<div class="text-center w-full">
Part of the REDACTED webring!
<br>
<br>
<div class="flex items-center justify-center">
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">← Bother the Doll</div>
</a>
<a class="transition-all duration-200" href="https://valhrafnaz.gay">
<div class="text-purple-300 hover:text-pink-600 w-max mx-20 hover:animate-bounce">nihil :3</div>
</a>
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">Bother the Doll →</div>
</a>
<div>
</div>
</footer>
</div>
</body>
</html>

60
_site/about/index.html Normal file
View File

@ -0,0 +1,60 @@
<!DOCTYPE html>
<html class="bg-gradient-to-t from-black to-purple-900 bg-fixed" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex, nofollow" />
<title>nihil's abode</title>
<meta name="description" content="nihil's humble abode on the interweb">
<link rel="stylesheet" href="/assets/css/tailwind.css">
<link rel="icon" type="image/x-icon" href="/assets/img/favicon.png">
<script src="/scripts/jquery-3.7.1.min.js"></script>
</head>
<body class="">
<script src="/scripts/oneko.js"></script>
<div class="flex flex-col min-h-screen items-center">
<header class="xl:h-4/10 flex justify-center items-center flex-col w-4/5 lg:2/3">
<h1 class="my-6 animate-text-shadow-pop">nihil&#39;s wretched abode :3</h1>
<nav class="flex flex-auto flex-col justify-center justify-items-center font-heading lg:text-3xl text-xl md:text-2xl w-4/5 flex-wrap h-2/10">
<div class="flex flex-row flex-wrap justify-items-center justify-center">
<a class="nav-link" href="/">home</a>
<a class="nav-link" href="/about/">about</a>
<a class="nav-link" href="/posts/">posts</a>
<a class="nav-link" href="/resources/">resources</a>
<a class="nav-link" href="/status/">status</a>
</div>
<hr class="hr-main">
</nav>
</header>
<main class="flex flex-col text-2xl font-body text-center mb-auto h-4/10 w-4/5 items-center justify-center tracking-wide">
<h2 class="mb-4 animate-text-shadow-pop">about me :3</h2>
<div class="flex flex-col justify-around items-center font-bold w-4/5 xl:w-2/3 text-pink-200">
<p>i am nihil and this is mine humble abode. i am a transfem (they/she/it) humanities phd student that also does a bunch of web shit in their free time.</p>
<p>i am also an ardent communist and anarchist, eventually this lil site will contain a reading list.</p>
<p>i am also on the regular sites as valhrafnaz.</p>
</div>
</main>
<footer class="text-3xl text-pink-100 font-heading flex flex-col items-center justify-center h-2/10 mb-10 w-4/5 lg:w-2/3">
<hr class="hr-main">
<div class="text-center w-full">
Part of the REDACTED webring!
<br>
<br>
<div class="flex items-center justify-center">
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">← Bother the Doll</div>
</a>
<a class="transition-all duration-200" href="https://valhrafnaz.gay">
<div class="text-purple-300 hover:text-pink-600 w-max mx-20 hover:animate-bounce">nihil :3</div>
</a>
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">Bother the Doll →</div>
</a>
<div>
</div>
</footer>
</div>
</body>
</html>

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

BIN
_site/assets/img/moth.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

View File

@ -0,0 +1,18 @@
<svg
viewBox="0 0 200 200"
xmlns='http://www.w3.org/2000/svg'>
<filter id='noiseFilter'>
<feTurbulence
type='fractalNoise'
baseFrequency='0.65'
numOctaves='3'
stitchTiles='stitch' />
</filter>
<rect
width='100%'
height='100%'
filter='url(#noiseFilter)' />
</svg>

After

Width:  |  Height:  |  Size: 323 B

BIN
_site/assets/img/oneko.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

BIN
_site/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

BIN
_site/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

99
_site/index.html Normal file
View File

@ -0,0 +1,99 @@
<!DOCTYPE html>
<html class="bg-gradient-to-t from-black to-purple-900 bg-fixed" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex, nofollow" />
<title>nihil's abode</title>
<meta name="description" content="nihil's humble abode on the interweb">
<link rel="stylesheet" href="/assets/css/tailwind.css">
<link rel="icon" type="image/x-icon" href="/assets/img/favicon.png">
<script src="/scripts/jquery-3.7.1.min.js"></script>
</head>
<body class="">
<script src="/scripts/oneko.js"></script>
<div class="flex flex-col min-h-screen items-center">
<header class="xl:h-4/10 flex justify-center items-center flex-col w-4/5 lg:2/3">
<h1 class="my-6 animate-text-shadow-pop">nihil&#39;s wretched abode :3</h1>
<nav class="flex flex-auto flex-col justify-center justify-items-center font-heading lg:text-3xl text-xl md:text-2xl w-4/5 flex-wrap h-2/10">
<div class="flex flex-row flex-wrap justify-items-center justify-center">
<a class="nav-link" href="/">home</a>
<a class="nav-link" href="/about/">about</a>
<a class="nav-link" href="/posts/">posts</a>
<a class="nav-link" href="/resources/">resources</a>
<a class="nav-link" href="/status/">status</a>
</div>
<hr class="hr-main">
</nav>
</header>
<main class="flex flex-col text-2xl font-body text-center mb-auto h-4/10 w-4/5 items-center justify-center tracking-wide">
<h2 class="mb-4 animate-text-shadow-pop">omg haii :3</h2>
<div class="flex flex-col justify-around items-center font-bold w-4/5 xl:w-2/3 text-pink-200">
<div class="flex justify-center">
<div class="mt-8 md text-center break-normal items-center justify-center justify-items-center">
<p>
welcome to my little horrible abode :3
<br>
here is a list of links to the services on this server, all of which are invite only, sorry >_<
</p>
</div>
</div>
<div class="flex justify-center w-4/5 lg:w-2/5">
<div class="group/link-btns grid grid-cols-2 grid-rows-3 lg:grid-cols-3 lg:grid-rows-2 gap-4 lg:gap-6 justify-items-center items-center my-16 lg:my-20 justify-self-center place-content-center center text-xl">
<a href="https://wiki.valhrafnaz.gay/">
<button type="button" class="btn-link">
wiki<br>:3
</button>
</a>
<a href="https://foundry.valhrafnaz.gay/">
<button type="button" class="btn-link">
VTT<br>:3
</button>
</a>
<a href="https://cloud.valhrafnaz.gay/">
<button type="button" class="btn-link">
cloud<br>:3
</button>
</a>
<a href="https://panel.valhrafnaz.gay/">
<button type="button" class="btn-link">
games<br>:3
</button>
</a>
<a href="https://git.valhrafnaz.gay/">
<button type="button" class="btn-link">
git<br>:3
</button>
</a>
<a href="https://mail.valhrafnaz.gay/">
<button type="button" class="btn-link">
mail<br>:3
</button>
</a>
</div>
</div>
</div>
</main>
<footer class="text-3xl text-pink-100 font-heading flex flex-col items-center justify-center h-2/10 mb-10 w-4/5 lg:w-2/3">
<hr class="hr-main">
<div class="text-center w-full">
Part of the REDACTED webring!
<br>
<br>
<div class="flex items-center justify-center">
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">← Bother the Doll</div>
</a>
<a class="transition-all duration-200" href="https://valhrafnaz.gay">
<div class="text-purple-300 hover:text-pink-600 w-max mx-20 hover:animate-bounce">nihil :3</div>
</a>
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">Bother the Doll →</div>
</a>
<div>
</div>
</footer>
</div>
</body>
</html>

77
_site/posts/index.html Normal file
View File

@ -0,0 +1,77 @@
<!DOCTYPE html>
<html class="bg-gradient-to-t from-black to-purple-900 bg-fixed" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex, nofollow" />
<title>nihil's abode</title>
<meta name="description" content="nihil's humble abode on the interweb">
<link rel="stylesheet" href="/assets/css/tailwind.css">
<link rel="icon" type="image/x-icon" href="/assets/img/favicon.png">
<script src="/scripts/jquery-3.7.1.min.js"></script>
</head>
<body class="">
<script src="/scripts/oneko.js"></script>
<div class="flex flex-col min-h-screen items-center">
<header class="xl:h-4/10 flex justify-center items-center flex-col w-4/5 lg:2/3">
<h1 class="my-6 animate-text-shadow-pop">nihil&#39;s wretched abode :3</h1>
<nav class="flex flex-auto flex-col justify-center justify-items-center font-heading lg:text-3xl text-xl md:text-2xl w-4/5 flex-wrap h-2/10">
<div class="flex flex-row flex-wrap justify-items-center justify-center">
<a class="nav-link" href="/">home</a>
<a class="nav-link" href="/about/">about</a>
<a class="nav-link" href="/posts/">posts</a>
<a class="nav-link" href="/resources/">resources</a>
<a class="nav-link" href="/status/">status</a>
</div>
<hr class="hr-main">
</nav>
</header>
<main class="flex flex-col text-2xl font-body text-center mb-auto h-4/10 w-4/5 items-center justify-center tracking-wide">
<h2 class="mb-4 animate-text-shadow-pop">Posts :3</h2>
<div class="flex flex-col justify-around items-center font-bold w-4/5 xl:w-2/3 text-pink-200">
<div class="flex flex-col items-center">
<div id="post-container" class="w-2/3 flex flex-col items-center">
<div class="post transition-all duration-300 hover:scale-110">
<a class="text-off-white hover:text-pink-500" href="/posts/post-1/">
<h2 class="text-2xl text-pink-300">first post hehe :3</h2>
<div class="text-justify text-base leading-snug"> this first post doesn't really contain much of substance, but in the future you can expect any sort of prose&hellip; </div>
<p class="text-sm text-purple-300"> Sun Nov 03 2024 </p>
</a>
</div>
</div>
<div class="inline-flex flex-row items-center mt-4">
<span class="mx-3" id="curr">1</span>
</div>
</div>
</div>
</main>
<footer class="text-3xl text-pink-100 font-heading flex flex-col items-center justify-center h-2/10 mb-10 w-4/5 lg:w-2/3">
<hr class="hr-main">
<div class="text-center w-full">
Part of the REDACTED webring!
<br>
<br>
<div class="flex items-center justify-center">
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">← Bother the Doll</div>
</a>
<a class="transition-all duration-200" href="https://valhrafnaz.gay">
<div class="text-purple-300 hover:text-pink-600 w-max mx-20 hover:animate-bounce">nihil :3</div>
</a>
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">Bother the Doll →</div>
</a>
<div>
</div>
</footer>
</div>
</body>
</html>

View File

@ -0,0 +1,80 @@
<!DOCTYPE html>
<html class="bg-gradient-to-t from-black to-purple-900 bg-fixed" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex, nofollow" />
<title>nihil's abode</title>
<meta name="description" content="nihil's humble abode on the interweb">
<link rel="stylesheet" href="/assets/css/tailwind.css">
<link rel="icon" type="image/x-icon" href="/assets/img/favicon.png">
<script src="/scripts/jquery-3.7.1.min.js"></script>
</head>
<body class="">
<script src="/scripts/oneko.js"></script>
<div class="flex flex-col min-h-screen items-center">
<header class="xl:h-4/10 flex justify-center items-center flex-col w-4/5 lg:2/3">
<h1 class="my-6 animate-text-shadow-pop">nihil&#39;s wretched abode :3</h1>
<nav class="flex flex-auto flex-col justify-center justify-items-center font-heading lg:text-3xl text-xl md:text-2xl w-4/5 flex-wrap h-2/10">
<div class="flex flex-row flex-wrap justify-items-center justify-center">
<a class="nav-link" href="/">home</a>
<a class="nav-link" href="/about/">about</a>
<a class="nav-link" href="/posts/">posts</a>
<a class="nav-link" href="/resources/">resources</a>
<a class="nav-link" href="/status/">status</a>
</div>
<hr class="hr-main">
</nav>
</header>
<main class="flex flex-col text-2xl font-body text-center mb-auto h-4/10 w-4/5 items-center justify-center tracking-wide">
<h2 class="mb-4 animate-text-shadow-pop">first post hehe :3</h2>
<div class="flex flex-col justify-around items-center font-bold w-4/5 xl:w-2/3 text-pink-200">
<div class="text-base text-purple-300 mb-5 inline-flex flex-col">
<span>Sun Nov 03 2024</span>
<span class="text-sm text-amber-200"><span id="time"></span> minutes read</span>
</div>
<article id="article" class="prose lg:prose-xl text-off-white text-justify">
<p>this first post doesn't really contain much of substance, but in the future you can expect any sort of prose i find interesting enough to post on here, probably about far-left politics, digital humanities, old norse, black metal, game analysis or whatever else bothers me that day :p</p>
<p>keeping a tradition i started on a long deleted blog years back, i leave you with some good music.</p>
<p>baiii :3</p>
<div class="flex justify-center">
<iframe width="720" height="480" src="https://www.youtube.com/embed/INgo0xmYBeg" title="Agalloch - The Mantle (Full Album)" frameborder="0" allow="clipboard-write; encrypted-media; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div>
</article>
<script defer>
function readingTime() {
const text = document.getElementById("article").innerText;
const wpm = 225;
const words = text.trim().split(/\s+/).length;
const time = Math.ceil(words / wpm);
document.getElementById("time").innerText = time;
}
readingTime();
</script>
</div>
</main>
<footer class="text-3xl text-pink-100 font-heading flex flex-col items-center justify-center h-2/10 mb-10 w-4/5 lg:w-2/3">
<hr class="hr-main">
<div class="text-center w-full">
Part of the REDACTED webring!
<br>
<br>
<div class="flex items-center justify-center">
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">← Bother the Doll</div>
</a>
<a class="transition-all duration-200" href="https://valhrafnaz.gay">
<div class="text-purple-300 hover:text-pink-600 w-max mx-20 hover:animate-bounce">nihil :3</div>
</a>
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">Bother the Doll →</div>
</a>
<div>
</div>
</footer>
</div>
</body>
</html>

View File

@ -0,0 +1,81 @@
<!DOCTYPE html>
<html class="bg-gradient-to-t from-black to-purple-900 bg-fixed" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex, nofollow" />
<title>nihil's abode</title>
<meta name="description" content="nihil's humble abode on the interweb">
<link rel="stylesheet" href="/assets/css/tailwind.css">
<link rel="icon" type="image/x-icon" href="/assets/img/favicon.png">
<script src="/scripts/jquery-3.7.1.min.js"></script>
</head>
<body class="">
<script src="/scripts/oneko.js"></script>
<div class="flex flex-col min-h-screen items-center">
<header class="xl:h-4/10 flex justify-center items-center flex-col w-4/5 lg:2/3">
<h1 class="my-6 animate-text-shadow-pop">nihil&#39;s wretched abode :3</h1>
<nav class="flex flex-auto flex-col justify-center justify-items-center font-heading lg:text-3xl text-xl md:text-2xl w-4/5 flex-wrap h-2/10">
<div class="flex flex-row flex-wrap justify-items-center justify-center">
<a class="nav-link" href="/">home</a>
<a class="nav-link" href="/about/">about</a>
<a class="nav-link" href="/posts/">posts</a>
<a class="nav-link" href="/resources/">resources</a>
<a class="nav-link" href="/status/">status</a>
</div>
<hr class="hr-main">
</nav>
</header>
<main class="flex flex-col text-2xl font-body text-center mb-auto h-4/10 w-4/5 items-center justify-center tracking-wide">
<h2 class="mb-4 animate-text-shadow-pop">important resources :3</h2>
<div class="flex flex-col justify-around items-center font-bold w-4/5 xl:w-2/3 text-pink-200">
<div id="prose" class="list-disc">
a list of sites i find important, feel free to let me know if i should add anything
<br>
<br>
<h3>diy hrt</h3>
<p>since i am transfem and currently relying on diy hrt this topic is near and dear to my heart
no hyperlinks to discourage automated nonsense <br>
<br></p>
<ul>
<li><a href="https://pastebin.com/Squ1vjYB">Pastebin with all important links as backup</a></li>
<li>diyhrt.market and hrtcafe.net for sourcing transfem diy products, market is much more up to date</li>
<li>transfemscience.org if you want to dive into the actual research behind recommandations (highly encouraged!)</li>
<li>r/TransDIY, currently at risk from outside actors</li>
<li>transharmreduction.org/hrt-testing for testing reports on diy estrogen<br>
<br></li>
</ul>
<h3>reading</h3>
<ul>
<li><a href="https://anarch.cc/library/">doe's library</a></li>
<li><a href="https://anarch.cc/library-resources/">doe's library resources</a></li>
<li><a href="https://archive.org/">archive.org</a></li>
<li><a href="https://theanarchistlibrary.org/special/index">the anarchist library</a></li>
<li><a href="https://marxists.org">marxists.org</a></li>
</ul>
</div>
</div>
</main>
<footer class="text-3xl text-pink-100 font-heading flex flex-col items-center justify-center h-2/10 mb-10 w-4/5 lg:w-2/3">
<hr class="hr-main">
<div class="text-center w-full">
Part of the REDACTED webring!
<br>
<br>
<div class="flex items-center justify-center">
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">← Bother the Doll</div>
</a>
<a class="transition-all duration-200" href="https://valhrafnaz.gay">
<div class="text-purple-300 hover:text-pink-600 w-max mx-20 hover:animate-bounce">nihil :3</div>
</a>
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">Bother the Doll →</div>
</a>
<div>
</div>
</footer>
</div>
</body>
</html>

2
_site/scripts/jquery-3.7.1.min.js vendored Normal file

File diff suppressed because one or more lines are too long

239
_site/scripts/oneko.js Normal file
View File

@ -0,0 +1,239 @@
// oneko.js: https://github.com/adryd325/oneko.js
(function oneko() {
const isReducedMotion =
window.matchMedia(`(prefers-reduced-motion: reduce)`) === true ||
window.matchMedia(`(prefers-reduced-motion: reduce)`).matches === true;
if (isReducedMotion) return;
const nekoEl = document.createElement("div");
let nekoPosX = 32;
let nekoPosY = 32;
let mousePosX = 0;
let mousePosY = 0;
let frameCount = 0;
let idleTime = 0;
let idleAnimation = null;
let idleAnimationFrame = 0;
const nekoSpeed = 10;
const spriteSets = {
idle: [[-3, -3]],
alert: [[-7, -3]],
scratchSelf: [
[-5, 0],
[-6, 0],
[-7, 0],
],
scratchWallN: [
[0, 0],
[0, -1],
],
scratchWallS: [
[-7, -1],
[-6, -2],
],
scratchWallE: [
[-2, -2],
[-2, -3],
],
scratchWallW: [
[-4, 0],
[-4, -1],
],
tired: [[-3, -2]],
sleeping: [
[-2, 0],
[-2, -1],
],
N: [
[-1, -2],
[-1, -3],
],
NE: [
[0, -2],
[0, -3],
],
E: [
[-3, 0],
[-3, -1],
],
SE: [
[-5, -1],
[-5, -2],
],
S: [
[-6, -3],
[-7, -2],
],
SW: [
[-5, -3],
[-6, -1],
],
W: [
[-4, -2],
[-4, -3],
],
NW: [
[-1, 0],
[-1, -1],
],
};
function init() {
nekoEl.id = "oneko";
nekoEl.ariaHidden = true;
nekoEl.style.width = "32px";
nekoEl.style.height = "32px";
nekoEl.style.position = "fixed";
nekoEl.style.pointerEvents = "none";
nekoEl.style.imageRendering = "pixelated";
nekoEl.style.left = `${nekoPosX - 16}px`;
nekoEl.style.top = `${nekoPosY - 16}px`;
nekoEl.style.zIndex = 2147483647;
let nekoFile = "/assets/img/oneko.gif"
const curScript = document.currentScript
if (curScript && curScript.dataset.cat) {
nekoFile = curScript.dataset.cat
}
nekoEl.style.backgroundImage = `url(${nekoFile})`;
document.body.appendChild(nekoEl);
document.addEventListener("mousemove", function (event) {
mousePosX = event.clientX;
mousePosY = event.clientY;
});
window.requestAnimationFrame(onAnimationFrame);
}
let lastFrameTimestamp;
function onAnimationFrame(timestamp) {
// Stops execution if the neko element is removed from DOM
if (!nekoEl.isConnected) {
return;
}
if (!lastFrameTimestamp) {
lastFrameTimestamp = timestamp;
}
if (timestamp - lastFrameTimestamp > 100) {
lastFrameTimestamp = timestamp
frame()
}
window.requestAnimationFrame(onAnimationFrame);
}
function setSprite(name, frame) {
const sprite = spriteSets[name][frame % spriteSets[name].length];
nekoEl.style.backgroundPosition = `${sprite[0] * 32}px ${sprite[1] * 32}px`;
}
function resetIdleAnimation() {
idleAnimation = null;
idleAnimationFrame = 0;
}
function idle() {
idleTime += 1;
// every ~ 20 seconds
if (
idleTime > 10 &&
Math.floor(Math.random() * 200) == 0 &&
idleAnimation == null
) {
let avalibleIdleAnimations = ["sleeping", "scratchSelf"];
if (nekoPosX < 32) {
avalibleIdleAnimations.push("scratchWallW");
}
if (nekoPosY < 32) {
avalibleIdleAnimations.push("scratchWallN");
}
if (nekoPosX > window.innerWidth - 32) {
avalibleIdleAnimations.push("scratchWallE");
}
if (nekoPosY > window.innerHeight - 32) {
avalibleIdleAnimations.push("scratchWallS");
}
idleAnimation =
avalibleIdleAnimations[
Math.floor(Math.random() * avalibleIdleAnimations.length)
];
}
switch (idleAnimation) {
case "sleeping":
if (idleAnimationFrame < 8) {
setSprite("tired", 0);
break;
}
setSprite("sleeping", Math.floor(idleAnimationFrame / 4));
if (idleAnimationFrame > 192) {
resetIdleAnimation();
}
break;
case "scratchWallN":
case "scratchWallS":
case "scratchWallE":
case "scratchWallW":
case "scratchSelf":
setSprite(idleAnimation, idleAnimationFrame);
if (idleAnimationFrame > 9) {
resetIdleAnimation();
}
break;
default:
setSprite("idle", 0);
return;
}
idleAnimationFrame += 1;
}
function frame() {
frameCount += 1;
const diffX = nekoPosX - mousePosX;
const diffY = nekoPosY - mousePosY;
const distance = Math.sqrt(diffX ** 2 + diffY ** 2);
if (distance < nekoSpeed || distance < 48) {
idle();
return;
}
idleAnimation = null;
idleAnimationFrame = 0;
if (idleTime > 1) {
setSprite("alert", 0);
// count down after being alerted before moving
idleTime = Math.min(idleTime, 7);
idleTime -= 1;
return;
}
let direction;
direction = diffY / distance > 0.5 ? "N" : "";
direction += diffY / distance < -0.5 ? "S" : "";
direction += diffX / distance > 0.5 ? "W" : "";
direction += diffX / distance < -0.5 ? "E" : "";
setSprite(direction, frameCount);
nekoPosX -= (diffX / distance) * nekoSpeed;
nekoPosY -= (diffY / distance) * nekoSpeed;
nekoPosX = Math.min(Math.max(16, nekoPosX), window.innerWidth - 16);
nekoPosY = Math.min(Math.max(16, nekoPosY), window.innerHeight - 16);
nekoEl.style.left = `${nekoPosX - 16}px`;
nekoEl.style.top = `${nekoPosY - 16}px`;
}
init();
})();

64
_site/status/index.html Normal file
View File

@ -0,0 +1,64 @@
<!DOCTYPE html>
<html class="bg-gradient-to-t from-black to-purple-900 bg-fixed" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex, nofollow" />
<title>nihil's abode</title>
<meta name="description" content="nihil's humble abode on the interweb">
<link rel="stylesheet" href="/assets/css/tailwind.css">
<link rel="icon" type="image/x-icon" href="/assets/img/favicon.png">
<script src="/scripts/jquery-3.7.1.min.js"></script>
</head>
<body class="">
<script src="/scripts/oneko.js"></script>
<div class="flex flex-col min-h-screen items-center">
<header class="xl:h-4/10 flex justify-center items-center flex-col w-4/5 lg:2/3">
<h1 class="my-6 animate-text-shadow-pop">nihil&#39;s wretched abode :3</h1>
<nav class="flex flex-auto flex-col justify-center justify-items-center font-heading lg:text-3xl text-xl md:text-2xl w-4/5 flex-wrap h-2/10">
<div class="flex flex-row flex-wrap justify-items-center justify-center">
<a class="nav-link" href="/">home</a>
<a class="nav-link" href="/about/">about</a>
<a class="nav-link" href="/posts/">posts</a>
<a class="nav-link" href="/resources/">resources</a>
<a class="nav-link" href="/status/">status</a>
</div>
<hr class="hr-main">
</nav>
</header>
<main class="flex flex-col text-2xl font-body text-center mb-auto h-4/10 w-4/5 items-center justify-center tracking-wide">
<h2 class="mb-4 animate-text-shadow-pop">Status :3</h2>
<div class="flex flex-col justify-around items-center font-bold w-4/5 xl:w-2/3 text-pink-200">
<div class="h-4/5 w-full">
<div id="embed-container">
<iframe id="responsive-frame" sandbox="allow-same-origin allow-scripts" referrerpolicy="origin-when-cross-origin" credentialless nofullscreen src="https://status.valhrafnaz.gay/status/main">
</div>
<div>
</div>
</main>
<footer class="text-3xl text-pink-100 font-heading flex flex-col items-center justify-center h-2/10 mb-10 w-4/5 lg:w-2/3">
<hr class="hr-main">
<div class="text-center w-full">
Part of the REDACTED webring!
<br>
<br>
<div class="flex items-center justify-center">
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">← Bother the Doll</div>
</a>
<a class="transition-all duration-200" href="https://valhrafnaz.gay">
<div class="text-purple-300 hover:text-pink-600 w-max mx-20 hover:animate-bounce">nihil :3</div>
</a>
<a class="transition-all duration-200" href="https://sleepydoll.gay">
<div class="text-purple-300 hover:text-pink-600 w-max hover:animate-bounce">Bother the Doll →</div>
</a>
<div>
</div>
</footer>
</div>
</body>
</html>

23
eleventy.config.cjs Normal file
View File

@ -0,0 +1,23 @@
module.exports = async function(eleventyConfig) {
// Input directory: src
// Output directory: _site
eleventyConfig.addWatchTarget("tailwind.config.js");
eleventyConfig.addWatchTarget(".src/**/*/*.css");
eleventyConfig.addFilter("truncatewords", function (str = "", limit = 30) {
return str.toString()
.trim()
.split(/\s+/g, limit)
.join(" ") + "&hellip;";
});
eleventyConfig.addPassthroughCopy("src/**/*/tailwind.css");
eleventyConfig.addPassthroughCopy("src/assets/img");
eleventyConfig.addPassthroughCopy("src/scripts/");
eleventyConfig.addPassthroughCopy("src/**/*.{png, jpeg, jpg, avif, gif}");
eleventyConfig.addPassthroughCopy("src/**/*.{ttf,otf,woff}");
};
module.exports.config = {
markdownTemplateEngine: "njk",
htmlTemplateEngine: 'njk',
};

1
node_modules/.bin/acorn generated vendored Symbolic link
View File

@ -0,0 +1 @@
../acorn/bin/acorn

1
node_modules/.bin/autoprefixer generated vendored Symbolic link
View File

@ -0,0 +1 @@
../autoprefixer/bin/autoprefixer

1
node_modules/.bin/browserslist generated vendored Symbolic link
View File

@ -0,0 +1 @@
../browserslist/cli.js

1
node_modules/.bin/cssesc generated vendored Symbolic link
View File

@ -0,0 +1 @@
../cssesc/bin/cssesc

1
node_modules/.bin/dev-ip generated vendored Symbolic link
View File

@ -0,0 +1 @@
../dev-ip/lib/dev-ip.js

1
node_modules/.bin/eleventy generated vendored Symbolic link
View File

@ -0,0 +1 @@
../@11ty/eleventy/cmd.cjs

1
node_modules/.bin/eleventy-dev-server generated vendored Symbolic link
View File

@ -0,0 +1 @@
../@11ty/eleventy-dev-server/cmd.js

1
node_modules/.bin/errno generated vendored Symbolic link
View File

@ -0,0 +1 @@
../errno/cli.js

1
node_modules/.bin/esparse generated vendored Symbolic link
View File

@ -0,0 +1 @@
../esprima/bin/esparse.js

1
node_modules/.bin/esvalidate generated vendored Symbolic link
View File

@ -0,0 +1 @@
../esprima/bin/esvalidate.js

1
node_modules/.bin/glob generated vendored Symbolic link
View File

@ -0,0 +1 @@
../glob/dist/esm/bin.mjs

1
node_modules/.bin/jiti generated vendored Symbolic link
View File

@ -0,0 +1 @@
../jiti/bin/jiti.js

1
node_modules/.bin/js-yaml generated vendored Symbolic link
View File

@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
node_modules/.bin/liquid generated vendored Symbolic link
View File

@ -0,0 +1 @@
../liquidjs/bin/liquid.js

1
node_modules/.bin/liquidjs generated vendored Symbolic link
View File

@ -0,0 +1 @@
../liquidjs/bin/liquid.js

1
node_modules/.bin/markdown-it generated vendored Symbolic link
View File

@ -0,0 +1 @@
../markdown-it/bin/markdown-it.mjs

1
node_modules/.bin/mime generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mime/cli.js

1
node_modules/.bin/mkdirp generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mkdirp/dist/cjs/src/bin.js

1
node_modules/.bin/nanoid generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nanoid/bin/nanoid.cjs

1
node_modules/.bin/node-which generated vendored Symbolic link
View File

@ -0,0 +1 @@
../which/bin/node-which

1
node_modules/.bin/npm-run-all generated vendored Symbolic link
View File

@ -0,0 +1 @@
../npm-run-all/bin/npm-run-all/index.js

1
node_modules/.bin/nunjucks-precompile generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nunjucks/bin/precompile

1
node_modules/.bin/pidtree generated vendored Symbolic link
View File

@ -0,0 +1 @@
../pidtree/bin/pidtree.js

1
node_modules/.bin/resolve generated vendored Symbolic link
View File

@ -0,0 +1 @@
../resolve/bin/resolve

1
node_modules/.bin/rimraf generated vendored Symbolic link
View File

@ -0,0 +1 @@
../rimraf/dist/esm/bin.mjs

1
node_modules/.bin/run-p generated vendored Symbolic link
View File

@ -0,0 +1 @@
../npm-run-all/bin/run-p/index.js

1
node_modules/.bin/run-s generated vendored Symbolic link
View File

@ -0,0 +1 @@
../npm-run-all/bin/run-s/index.js

1
node_modules/.bin/semver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../semver/bin/semver.js

1
node_modules/.bin/sucrase generated vendored Symbolic link
View File

@ -0,0 +1 @@
../sucrase/bin/sucrase

1
node_modules/.bin/sucrase-node generated vendored Symbolic link
View File

@ -0,0 +1 @@
../sucrase/bin/sucrase-node

1
node_modules/.bin/tailwind generated vendored Symbolic link
View File

@ -0,0 +1 @@
../tailwindcss/lib/cli.js

1
node_modules/.bin/tailwindcss generated vendored Symbolic link
View File

@ -0,0 +1 @@
../tailwindcss/lib/cli.js

1
node_modules/.bin/update-browserslist-db generated vendored Symbolic link
View File

@ -0,0 +1 @@
../update-browserslist-db/cli.js

1
node_modules/.bin/yaml generated vendored Symbolic link
View File

@ -0,0 +1 @@
../yaml/bin.mjs

4516
node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
on:
push:
branches-ignore:
- "gh-pages"
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: ["ubuntu-latest", "macos-latest", "windows-latest"]
node: ["16", "18", "20"]
name: Node.js ${{ matrix.node }} on ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Setup node
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node }}
- run: npm install
- run: npm test
env:
YARN_GPG: no

21
node_modules/@11ty/dependency-tree-esm/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Zach Leatherman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

40
node_modules/@11ty/dependency-tree-esm/README.md generated vendored Normal file
View File

@ -0,0 +1,40 @@
# `dependency-tree-esm`
Returns an unordered array of local paths to dependencies of a Node ES module JavaScript file.
* See also: [`dependency-tree`](https://github.com/11ty/eleventy-dependency-tree) for the CommonJS version.
This is used by Eleventy to find dependencies of a JavaScript file to watch for changes to re-run Eleventys build.
## Installation
```
npm install --save-dev @11ty/dependency-tree-esm
```
## Features
* Ignores bare specifiers (e.g. `import "my-package"`)
* Ignores Nodes built-ins (e.g. `import "path"`)
* Handles circular dependencies
* Returns an empty set if the file does not exist.
## Usage
```js
// my-file.js
// if my-local-dependency.js has dependencies, it will include those too
import "./my-local-dependency.js";
// ignored, is a built-in
import path from "path";
```
```js
const { find } = require("@11ty/dependency-tree-esm");
find("./my-file.js");
// returns ["./my-local-dependency.js"]
```

84
node_modules/@11ty/dependency-tree-esm/main.js generated vendored Normal file
View File

@ -0,0 +1,84 @@
const path = require("path");
const { existsSync } = require("fs");
const { readFile } = require("fs/promises");
const acorn = require("acorn");
const normalizePath = require("normalize-path");
const { TemplatePath } = require("@11ty/eleventy-utils");
// Is *not* a bare specifier (e.g. 'some-package')
// https://nodejs.org/dist/latest-v18.x/docs/api/esm.html#terminology
function isNonBareSpecifier(importSource) {
// Change \\ to / on Windows
let normalized = normalizePath(importSource);
// Relative specifier (e.g. './startup.js')
if(normalized.startsWith("./") || normalized.startsWith("../")) {
return true;
}
// Absolute specifier (e.g. 'file:///opt/nodejs/config.js')
if(normalized.startsWith("file:")) {
return true;
}
return false;
}
function normalizeFilePath(filePath) {
return TemplatePath.standardizeFilePath(path.relative(".", filePath));
}
function normalizeImportSourceToFilePath(filePath, source) {
let { dir } = path.parse(filePath);
let normalized = path.join(dir, source);
return normalizeFilePath(normalized);
}
async function findByContents(contents, filePath, alreadyParsedSet) {
// Should we use dependency-graph for these relationships?
let sources = new Set();
let ast = acorn.parse(contents, {sourceType: "module", ecmaVersion: "latest"});
for(let node of ast.body) {
if(node.type === "ImportDeclaration" && isNonBareSpecifier(node.source.value)) {
let normalized = normalizeImportSourceToFilePath(filePath, node.source.value);
if(sources.has(normalized) || normalized === filePath) {
continue;
}
sources.add(normalized);
}
}
// Recurse for nested deps
for(let source of sources) {
let s = await find(source, alreadyParsedSet);
for(let p of s) {
if(sources.has(p) || p === filePath) {
continue;
}
sources.add(p);
}
}
return Array.from(sources);
}
async function find(filePath, alreadyParsedSet = new Set()) {
// TODO add a cache here
// Unfortunately we need to read the entire file, imports need to be at the top level but they can be anywhere 🫠
let normalized = normalizeFilePath(filePath);
if(alreadyParsedSet.has(normalized) || !existsSync(filePath)) {
return [];
}
alreadyParsedSet.add(normalized);
let contents = await readFile(normalized, { encoding: 'utf8' });
let sources = await findByContents(contents, normalized, alreadyParsedSet);
return sources;
}
module.exports = {
find
};

View File

@ -0,0 +1,82 @@
# Dependency Graph Changelog
## 0.11.0 (March 5, 2021)
- Add `entryNodes` method that returns the nodes that nothing depends on - thanks [amcdnl](https://github.com/amcdnl)!
## 0.10.0 (January 9, 2021)
- Add `directDependenciesOf` and `directDependantsOf` methods for retrieving direct dependency information. (Fixes #40)
- Add aliases `dependentsOf` and `directDependentsOf`.
## 0.9.0 (February 10, 2020)
- Rewrite the topological sort DFS to be more efficient (and work!) on large graphs.
- No longer uses recursion to avoid stack overflows with large/deep graphs
- No longer is accidentally `O(N^2)` (thanks [willtennien](https://github.com/willtennien) for pointing this out!)
## 0.8.1 (December 3, 2019)
- Ensure all nodes are included in overallOrder when cycles are allowed. (Fixes #33)
## 0.8.0 (December 11, 2018)
- Add a `DepGraphCycleError` with cyclePath property - thanks [jhugman](https://github.com/jhugman)!
## 0.7.2 (August 30, 2018)
- Make constructor parameter optional in Typescript definition. (Fixes #26)
## 0.7.1 (June 5, 2018)
- Fix Typescript definition to include the new constructor arguments added in `0.7.0` - thanks [tbranyen](https://github.com/tbranyen)!
## 0.7.0 (January 17, 2018)
- Allow circular dependencies by passing in `{circular: true}` into the constructor - thanks [tbranyen](https://github.com/tbranyen)!
## 0.6.0 (October 22, 2017)
- Add a `size` method that will return the number of nodes in the graph.
- Add a `clone` method that will clone the graph. Any custom node data will only be shallow-copied. (Fixes #14)
## 0.5.2 (October 22, 2017)
- Add missing parameter in TypeScript definition. (Fixes #19)
## 0.5.1 (October 7, 2017)
- Now exposes Typescript type definition - thanks [vangorra](https://github.com/vangorra)!
## 0.5.0 (April 26, 2016)
- Add optional data parameter for the addNode method. (Fixes #12)
- Add methods getNodeData and setNodeData to manipulate the data associated with a node name. (Fixes #12)
- Change the hasNode method to be able to cope with falsy node data. (Fixes #12)
## 0.4.1 (Sept 3, 2015)
- Check all nodes for potential cycles when calculating overall order. (Fixes #8)
## 0.4.0 (Aug 1, 2015)
- Better error messages
- When a cycle is detected, the error message will now include the cycle in it. E.g `Dependency Cycle Found: a -> b -> c -> a` (Fixes #7)
- When calling `addDependency` if one of the nodes does not exist, the error will say which one it was (instead of saying that "one" of the two nodes did not exist and making you manually determine which one)
- Calling `overallOrder` on an empty graph will no longer throw an error about a dependency cycle. It will return an empty array.
## 0.3.0 (July 24, 2015)
- Fix issue where if you call `addNode` twice with the same name, it would clear all edges for that node. Now it will do nothing if a node with the specified name already exists. (Fixes #3)
## 0.2.1 (July 3, 2015)
- Fixed removeNode leaving references in outgoingEdges and reference to non-existent var edges - thanks [juhoha](https://github.com/juhoha)! (Fixes #2)
## 0.2.0 (May 1, 2015)
- Removed dependency on Underscore - thanks [myndzi](https://github.com/myndzi)! (Fixes #1)
## 0.1.0 (May 18, 2013)
- Initial Release - extracted out of asset-smasher

View File

@ -0,0 +1,19 @@
Copyright (C) 2013-2020 by Jim Riecken
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,78 @@
# Dependency Graph
Simple dependency graph
## Overview
This is a simple dependency graph useful for determining the order to do a list of things that depend on certain items being done before they are.
To use, `npm install dependency-graph` and then `require('dependency-graph').DepGraph`
## API
### DepGraph
Nodes in the graph are just simple strings with optional data associated with them.
- `addNode(name, data)` - add a node in the graph with optional data. If `data` is not given, `name` will be used as data
- `removeNode(name)` - remove a node from the graph
- `hasNode(name)` - check if a node exists in the graph
- `size()` - return the number of nodes in the graph
- `getNodeData(name)` - get the data associated with a node (will throw an `Error` if the node does not exist)
- `setNodeData(name, data)` - set the data for an existing node (will throw an `Error` if the node does not exist)
- `addDependency(from, to)` - add a dependency between two nodes (will throw an `Error` if one of the nodes does not exist)
- `removeDependency(from, to)` - remove a dependency between two nodes
- `clone()` - return a clone of the graph. Any data attached to the nodes will only be *shallow-copied*
- `dependenciesOf(name, leavesOnly)` - get an array containing the nodes that the specified node depends on (transitively). If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned in the array.
- `dependantsOf(name, leavesOnly)` (aliased as `dependentsOf`) - get an array containing the nodes that depend on the specified node (transitively). If `leavesOnly` is true, only nodes that do not have any dependants will be returned in the array.
- `directDependenciesOf(name)` - get an array containing the direct dependencies of the specified node
- `directDependantsOf(name)` (aliased as `directDependentsOf`) - get an array containing the nodes that directly depend on the specified node
- `overallOrder(leavesOnly)` - construct the overall processing order for the dependency graph. If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned.
- `entryNodes()` - array of nodes that have no dependants (i.e. nothing depends on them).
Dependency Cycles are detected when running `dependenciesOf`, `dependantsOf`, and `overallOrder` and if one is found, a `DepGraphCycleError` will be thrown that includes what the cycle was in the message as well as the `cyclePath` property: e.g. `Dependency Cycle Found: a -> b -> c -> a`. If you wish to silence this error, pass `circular: true` when instantiating `DepGraph` (more below).
## Examples
var DepGraph = require('dependency-graph').DepGraph;
var graph = new DepGraph();
graph.addNode('a');
graph.addNode('b');
graph.addNode('c');
graph.size() // 3
graph.addDependency('a', 'b');
graph.addDependency('b', 'c');
graph.dependenciesOf('a'); // ['c', 'b']
graph.dependenciesOf('b'); // ['c']
graph.dependantsOf('c'); // ['a', 'b']
graph.overallOrder(); // ['c', 'b', 'a']
graph.overallOrder(true); // ['c']
graph.entryNodes(); // ['a']
graph.addNode('d', 'data');
graph.getNodeData('d'); // 'data'
graph.setNodeData('d', 'newData');
graph.getNodeData('d'); // 'newData'
var circularGraph = new DepGraph({ circular: true });
circularGraph.addNode('a');
circularGraph.addNode('b');
circularGraph.addNode('c');
circularGraph.addNode('d');
circularGraph.addDependency('a', 'b');
circularGraph.addDependency('b', 'c'); // b depends on c
circularGraph.addDependency('c', 'a'); // c depends on a, which depends on b
circularGraph.addDependency('d', 'a');
circularGraph.dependenciesOf('b'); // ['a', 'c']
circularGraph.overallOrder(); // ['c', 'b', 'a', 'd']

View File

@ -0,0 +1,364 @@
/**
* A simple dependency graph
*/
/**
* Helper for creating a Topological Sort using Depth-First-Search on a set of edges.
*
* Detects cycles and throws an Error if one is detected (unless the "circular"
* parameter is "true" in which case it ignores them).
*
* @param edges The set of edges to DFS through
* @param leavesOnly Whether to only return "leaf" nodes (ones who have no edges)
* @param result An array in which the results will be populated
* @param circular A boolean to allow circular dependencies
*/
function createDFS(edges, leavesOnly, result, circular) {
var visited = {};
return function (start) {
if (visited[start]) {
return;
}
var inCurrentPath = {};
var currentPath = [];
var todo = []; // used as a stack
todo.push({ node: start, processed: false });
while (todo.length > 0) {
var current = todo[todo.length - 1]; // peek at the todo stack
var processed = current.processed;
var node = current.node;
if (!processed) {
// Haven't visited edges yet (visiting phase)
if (visited[node]) {
todo.pop();
continue;
} else if (inCurrentPath[node]) {
// It's not a DAG
if (circular) {
todo.pop();
// If we're tolerating cycles, don't revisit the node
continue;
}
currentPath.push(node);
throw new DepGraphCycleError(currentPath);
}
inCurrentPath[node] = true;
currentPath.push(node);
var nodeEdges = edges[node];
// (push edges onto the todo stack in reverse order to be order-compatible with the old DFS implementation)
for (var i = nodeEdges.length - 1; i >= 0; i--) {
todo.push({ node: nodeEdges[i], processed: false });
}
current.processed = true;
} else {
// Have visited edges (stack unrolling phase)
todo.pop();
currentPath.pop();
inCurrentPath[node] = false;
visited[node] = true;
if (!leavesOnly || edges[node].length === 0) {
result.push(node);
}
}
}
};
}
/**
* Simple Dependency Graph
*/
var DepGraph = (exports.DepGraph = function DepGraph(opts) {
this.nodes = {}; // Node -> Node/Data (treated like a Set)
this.outgoingEdges = {}; // Node -> [Dependency Node]
this.incomingEdges = {}; // Node -> [Dependant Node]
this.circular = opts && !!opts.circular; // Allows circular deps
});
DepGraph.prototype = {
/**
* The number of nodes in the graph.
*/
size: function () {
return Object.keys(this.nodes).length;
},
/**
* Add a node to the dependency graph. If a node already exists, this method will do nothing.
*/
addNode: function (node, data) {
if (!this.hasNode(node)) {
// Checking the arguments length allows the user to add a node with undefined data
if (arguments.length === 2) {
this.nodes[node] = data;
} else {
this.nodes[node] = node;
}
this.outgoingEdges[node] = [];
this.incomingEdges[node] = [];
}
},
/**
* Remove a node from the dependency graph. If a node does not exist, this method will do nothing.
*/
removeNode: function (node) {
if (this.hasNode(node)) {
delete this.nodes[node];
delete this.outgoingEdges[node];
delete this.incomingEdges[node];
[this.incomingEdges, this.outgoingEdges].forEach(function (edgeList) {
Object.keys(edgeList).forEach(function (key) {
var idx = edgeList[key].indexOf(node);
if (idx >= 0) {
edgeList[key].splice(idx, 1);
}
}, this);
});
}
},
/**
* Check if a node exists in the graph
*/
hasNode: function (node) {
return this.nodes.hasOwnProperty(node);
},
/**
* Get the data associated with a node name
*/
getNodeData: function (node) {
if (this.hasNode(node)) {
return this.nodes[node];
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Set the associated data for a given node name. If the node does not exist, this method will throw an error
*/
setNodeData: function (node, data) {
if (this.hasNode(node)) {
this.nodes[node] = data;
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Add a dependency between two nodes. If either of the nodes does not exist,
* an Error will be thrown.
*/
addDependency: function (from, to) {
if (!this.hasNode(from)) {
throw new Error("Node does not exist: " + from);
}
if (!this.hasNode(to)) {
throw new Error("Node does not exist: " + to);
}
if (this.outgoingEdges[from].indexOf(to) === -1) {
this.outgoingEdges[from].push(to);
}
if (this.incomingEdges[to].indexOf(from) === -1) {
this.incomingEdges[to].push(from);
}
return true;
},
/**
* Remove a dependency between two nodes.
*/
removeDependency: function (from, to) {
var idx;
if (this.hasNode(from)) {
idx = this.outgoingEdges[from].indexOf(to);
if (idx >= 0) {
this.outgoingEdges[from].splice(idx, 1);
}
}
if (this.hasNode(to)) {
idx = this.incomingEdges[to].indexOf(from);
if (idx >= 0) {
this.incomingEdges[to].splice(idx, 1);
}
}
},
/**
* Return a clone of the dependency graph. If any custom data is attached
* to the nodes, it will only be shallow copied.
*/
clone: function () {
var source = this;
var result = new DepGraph();
var keys = Object.keys(source.nodes);
keys.forEach(function (n) {
result.nodes[n] = source.nodes[n];
result.outgoingEdges[n] = source.outgoingEdges[n].slice(0);
result.incomingEdges[n] = source.incomingEdges[n].slice(0);
});
return result;
},
/**
* Get an array containing the direct dependencies of the specified node.
*
* Throws an Error if the specified node does not exist.
*/
directDependenciesOf: function (node) {
if (this.hasNode(node)) {
return this.outgoingEdges[node].slice(0);
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Get an array containing the nodes that directly depend on the specified node.
*
* Throws an Error if the specified node does not exist.
*/
directDependantsOf: function (node) {
if (this.hasNode(node)) {
return this.incomingEdges[node].slice(0);
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Get an array containing the nodes that the specified node depends on (transitively).
*
* Throws an Error if the graph has a cycle, or the specified node does not exist.
*
* If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned
* in the array.
*/
dependenciesOf: function (node, leavesOnly) {
if (this.hasNode(node)) {
var result = [];
var DFS = createDFS(
this.outgoingEdges,
leavesOnly,
result,
this.circular
);
DFS(node);
var idx = result.indexOf(node);
if (idx >= 0) {
result.splice(idx, 1);
}
return result;
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* get an array containing the nodes that depend on the specified node (transitively).
*
* Throws an Error if the graph has a cycle, or the specified node does not exist.
*
* If `leavesOnly` is true, only nodes that do not have any dependants will be returned in the array.
*/
dependantsOf: function (node, leavesOnly) {
if (this.hasNode(node)) {
var result = [];
var DFS = createDFS(
this.incomingEdges,
leavesOnly,
result,
this.circular
);
DFS(node);
var idx = result.indexOf(node);
if (idx >= 0) {
result.splice(idx, 1);
}
return result;
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Construct the overall processing order for the dependency graph.
*
* Throws an Error if the graph has a cycle.
*
* If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned.
*/
overallOrder: function (leavesOnly) {
var self = this;
var result = [];
var keys = Object.keys(this.nodes);
if (keys.length === 0) {
return result; // Empty graph
} else {
if (!this.circular) {
// Look for cycles - we run the DFS starting at all the nodes in case there
// are several disconnected subgraphs inside this dependency graph.
var CycleDFS = createDFS(this.outgoingEdges, false, [], this.circular);
keys.forEach(function (n) {
CycleDFS(n);
});
}
var DFS = createDFS(
this.outgoingEdges,
leavesOnly,
result,
this.circular
);
// Find all potential starting points (nodes with nothing depending on them) an
// run a DFS starting at these points to get the order
keys
.filter(function (node) {
return self.incomingEdges[node].length === 0;
})
.forEach(function (n) {
DFS(n);
});
// If we're allowing cycles - we need to run the DFS against any remaining
// nodes that did not end up in the initial result (as they are part of a
// subgraph that does not have a clear starting point)
if (this.circular) {
keys
.filter(function (node) {
return result.indexOf(node) === -1;
})
.forEach(function (n) {
DFS(n);
});
}
return result;
}
},
/**
* Get an array of nodes that have no dependants (i.e. nothing depends on them).
*/
entryNodes: function () {
var self = this;
return Object.keys(this.nodes).filter(function (node) {
return self.incomingEdges[node].length === 0;
});
}
};
// Create some aliases
DepGraph.prototype.directDependentsOf = DepGraph.prototype.directDependantsOf;
DepGraph.prototype.dependentsOf = DepGraph.prototype.dependantsOf;
/**
* Cycle error, including the path of the cycle.
*/
var DepGraphCycleError = (exports.DepGraphCycleError = function (cyclePath) {
var message = "Dependency Cycle Found: " + cyclePath.join(" -> ");
var instance = new Error(message);
instance.cyclePath = cyclePath;
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, DepGraphCycleError);
}
return instance;
});
DepGraphCycleError.prototype = Object.create(Error.prototype, {
constructor: {
value: Error,
enumerable: false,
writable: true,
configurable: true
}
});
Object.setPrototypeOf(DepGraphCycleError, Error);

View File

@ -0,0 +1,127 @@
declare module 'dependency-graph' {
export interface Options {
circular?: boolean;
}
export class DepGraph<T> {
/**
* Creates an instance of DepGraph with optional Options.
*/
constructor(opts?: Options);
/**
* The number of nodes in the graph.
*/
size(): number;
/**
* Add a node in the graph with optional data. If data is not given, name will be used as data.
* @param {string} name
* @param data
*/
addNode(name: string, data?: T): void;
/**
* Remove a node from the graph.
* @param {string} name
*/
removeNode(name: string): void;
/**
* Check if a node exists in the graph.
* @param {string} name
*/
hasNode(name: string): boolean;
/**
* Get the data associated with a node (will throw an Error if the node does not exist).
* @param {string} name
*/
getNodeData(name: string): T;
/**
* Set the data for an existing node (will throw an Error if the node does not exist).
* @param {string} name
* @param data
*/
setNodeData(name: string, data?: T): void;
/**
* Add a dependency between two nodes (will throw an Error if one of the nodes does not exist).
* @param {string} from
* @param {string} to
*/
addDependency(from: string, to: string): void;
/**
* Remove a dependency between two nodes.
* @param {string} from
* @param {string} to
*/
removeDependency(from: string, to: string): void;
/**
* Return a clone of the dependency graph (If any custom data is attached
* to the nodes, it will only be shallow copied).
*/
clone(): DepGraph<T>;
/**
* Get an array containing the direct dependency nodes of the specified node.
* @param name
*/
directDependenciesOf(name: string): string[];
/**
* Get an array containing the nodes that directly depend on the specified node.
* @param name
*/
directDependantsOf(name: string): string[];
/**
* Alias of `directDependantsOf`
*
* @see directDependantsOf
* @param {string} name
*/
directDependentsOf(name: string): string[];
/**
* Get an array containing the nodes that the specified node depends on (transitively). If leavesOnly is true, only nodes that do not depend on any other nodes will be returned in the array.
* @param {string} name
* @param {boolean} leavesOnly
*/
dependenciesOf(name: string, leavesOnly?: boolean): string[];
/**
* Get an array containing the nodes that depend on the specified node (transitively). If leavesOnly is true, only nodes that do not have any dependants will be returned in the array.
* @param {string} name
* @param {boolean} leavesOnly
*/
dependantsOf(name: string, leavesOnly?: boolean): string[];
/**
* Alias of `dependantsOf`
*
* @see dependantsOf
* @param name
* @param leavesOnly
*/
dependentsOf(name: string, leavesOnly?: boolean): string[];
/**
* Get an array of nodes that have no dependants (i.e. nothing depends on them).
*/
entryNodes(): string[];
/**
* Construct the overall processing order for the dependency graph. If leavesOnly is true, only nodes that do not depend on any other nodes will be returned.
* @param {boolean} leavesOnly
*/
overallOrder(leavesOnly?: boolean): string[];
}
export class DepGraphCycleError extends Error {
cyclePath: string[];
}
}

View File

@ -0,0 +1,31 @@
{
"name": "dependency-graph",
"description": "Simple dependency graph.",
"version": "0.11.0",
"author": "Jim Riecken <jriecken@gmail.com>",
"keywords": [
"dependency",
"graph"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git://github.com/jriecken/dependency-graph.git"
},
"bugs": {
"url": "http://github.com/jriecken/dependency-graph/issues"
},
"main": "./lib/dep_graph.js",
"scripts": {
"test": "jasmine specs/**/*.js"
},
"dependencies": {},
"optionalDependencies": {},
"devDependencies": {
"jasmine": "3.5.0"
},
"engines": {
"node": ">= 0.6.0"
},
"types": "./lib/index.d.ts"
}

View File

@ -0,0 +1,542 @@
var dep_graph = require("../lib/dep_graph");
var DepGraph = dep_graph.DepGraph;
describe("DepGraph", function () {
it("should be able to add/remove nodes", function () {
var graph = new DepGraph();
graph.addNode("Foo");
graph.addNode("Bar");
expect(graph.hasNode("Foo")).toBeTrue();
expect(graph.hasNode("Bar")).toBeTrue();
expect(graph.hasNode("NotThere")).toBeFalse();
graph.removeNode("Bar");
expect(graph.hasNode("Bar")).toBeFalse();
});
it("should calculate its size", function () {
var graph = new DepGraph();
expect(graph.size()).toBe(0);
graph.addNode("Foo");
graph.addNode("Bar");
expect(graph.size()).toBe(2);
graph.removeNode("Bar");
expect(graph.size()).toBe(1);
});
it("should treat the node data parameter as optional and use the node name as data if node data was not given", function () {
var graph = new DepGraph();
graph.addNode("Foo");
expect(graph.getNodeData("Foo")).toBe("Foo");
});
it("should be able to associate a node name with data on node add", function () {
var graph = new DepGraph();
graph.addNode("Foo", "data");
expect(graph.getNodeData("Foo")).toBe("data");
});
it("should be able to add undefined as node data", function () {
var graph = new DepGraph();
graph.addNode("Foo", undefined);
expect(graph.getNodeData("Foo")).toBeUndefined();
});
it("should return true when using hasNode with a node which has falsy data", function () {
var graph = new DepGraph();
var falsyData = ["", 0, null, undefined, false];
graph.addNode("Foo");
falsyData.forEach(function (data) {
graph.setNodeData("Foo", data);
expect(graph.hasNode("Foo")).toBeTrue();
// Just an extra check to make sure that the saved data is correct
expect(graph.getNodeData("Foo")).toBe(data);
});
});
it("should be able to set data after a node was added", function () {
var graph = new DepGraph();
graph.addNode("Foo", "data");
graph.setNodeData("Foo", "data2");
expect(graph.getNodeData("Foo")).toBe("data2");
});
it("should throw an error if we try to set data for a non-existing node", function () {
var graph = new DepGraph();
expect(function () {
graph.setNodeData("Foo", "data");
}).toThrow(new Error("Node does not exist: Foo"));
});
it("should throw an error if the node does not exists and we try to get data", function () {
var graph = new DepGraph();
expect(function () {
graph.getNodeData("Foo");
}).toThrow(new Error("Node does not exist: Foo"));
});
it("should do nothing if creating a node that already exists", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addDependency("a", "b");
graph.addNode("a");
expect(graph.dependenciesOf("a")).toEqual(["b"]);
});
it("should do nothing if removing a node that does not exist", function () {
var graph = new DepGraph();
graph.addNode("a");
expect(graph.hasNode("a")).toBeTrue();
graph.removeNode("a");
expect(graph.hasNode("Foo")).toBeFalse();
graph.removeNode("a");
expect(graph.hasNode("Foo")).toBeFalse();
});
it("should be able to add dependencies between nodes", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("a", "c");
expect(graph.dependenciesOf("a")).toEqual(["b", "c"]);
});
it("should find entry nodes", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("a", "c");
expect(graph.entryNodes()).toEqual(["a"]);
});
it("should throw an error if a node does not exist and a dependency is added", function () {
var graph = new DepGraph();
graph.addNode("a");
expect(function () {
graph.addDependency("a", "b");
}).toThrow(new Error("Node does not exist: b"));
});
it("should detect cycles", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("c", "a");
graph.addDependency("d", "a");
expect(function () {
graph.dependenciesOf("b");
}).toThrow(new dep_graph.DepGraphCycleError(["b", "c", "a", "b"]));
});
it("should allow cycles when configured", function () {
var graph = new DepGraph({ circular: true });
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("c", "a");
graph.addDependency("d", "a");
expect(graph.dependenciesOf("b")).toEqual(["a", "c"]);
expect(graph.overallOrder()).toEqual(["c", "b", "a", "d"]);
});
it(
"should include all nodes in overall order even from " +
"cycles in disconnected subgraphs when circular is true",
function () {
var graph = new DepGraph({ circular: true });
graph.addNode("2a");
graph.addNode("2b");
graph.addNode("2c");
graph.addDependency("2a", "2b");
graph.addDependency("2b", "2c");
graph.addDependency("2c", "2a");
graph.addNode("1a");
graph.addNode("1b");
graph.addNode("1c");
graph.addNode("1d");
graph.addNode("1e");
graph.addDependency("1a", "1b");
graph.addDependency("1a", "1c");
graph.addDependency("1b", "1c");
graph.addDependency("1c", "1d");
expect(graph.overallOrder()).toEqual([
"1d",
"1c",
"1b",
"1a",
"1e",
"2c",
"2b",
"2a"
]);
}
);
it("should detect cycles in overall order", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("c", "a");
graph.addDependency("d", "a");
expect(function () {
graph.overallOrder();
}).toThrow(new dep_graph.DepGraphCycleError(["a", "b", "c", "a"]));
});
it("should detect cycles in overall order when all nodes have dependants (incoming edges)", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("c", "a");
expect(function () {
graph.overallOrder();
}).toThrow(new dep_graph.DepGraphCycleError(["a", "b", "c", "a"]));
});
it(
"should detect cycles in overall order when there are several " +
"disconnected subgraphs (with one that does not have a cycle",
function () {
var graph = new DepGraph();
graph.addNode("a_1");
graph.addNode("a_2");
graph.addNode("b_1");
graph.addNode("b_2");
graph.addNode("b_3");
graph.addDependency("a_1", "a_2");
graph.addDependency("b_1", "b_2");
graph.addDependency("b_2", "b_3");
graph.addDependency("b_3", "b_1");
expect(function () {
graph.overallOrder();
}).toThrow(
new dep_graph.DepGraphCycleError(["b_1", "b_2", "b_3", "b_1"])
);
}
);
it("should retrieve dependencies and dependants in the correct order", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("d", "b");
expect(graph.dependenciesOf("a")).toEqual(["c", "b", "d"]);
expect(graph.dependenciesOf("b")).toEqual(["c"]);
expect(graph.dependenciesOf("c")).toEqual([]);
expect(graph.dependenciesOf("d")).toEqual(["c", "b"]);
expect(graph.dependantsOf("a")).toEqual([]);
expect(graph.dependantsOf("b")).toEqual(["a", "d"]);
expect(graph.dependantsOf("c")).toEqual(["a", "d", "b"]);
expect(graph.dependantsOf("d")).toEqual(["a"]);
// check the alias "dependentsOf"
expect(graph.dependentsOf("a")).toEqual([]);
expect(graph.dependentsOf("b")).toEqual(["a", "d"]);
expect(graph.dependentsOf("c")).toEqual(["a", "d", "b"]);
expect(graph.dependentsOf("d")).toEqual(["a"]);
});
it("should be able to retrieve direct dependencies/dependants", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("d", "b");
expect(graph.directDependenciesOf("a")).toEqual(["d", "b"]);
expect(graph.directDependenciesOf("b")).toEqual(["c"]);
expect(graph.directDependenciesOf("c")).toEqual([]);
expect(graph.directDependenciesOf("d")).toEqual(["b"]);
expect(graph.directDependantsOf("a")).toEqual([]);
expect(graph.directDependantsOf("b")).toEqual(["a", "d"]);
expect(graph.directDependantsOf("c")).toEqual(["b"]);
expect(graph.directDependantsOf("d")).toEqual(["a"]);
// check the alias "directDependentsOf"
expect(graph.directDependentsOf("a")).toEqual([]);
expect(graph.directDependentsOf("b")).toEqual(["a", "d"]);
expect(graph.directDependentsOf("c")).toEqual(["b"]);
expect(graph.directDependentsOf("d")).toEqual(["a"]);
});
it("should be able to resolve the overall order of things", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addNode("e");
graph.addDependency("a", "b");
graph.addDependency("a", "c");
graph.addDependency("b", "c");
graph.addDependency("c", "d");
expect(graph.overallOrder()).toEqual(["d", "c", "b", "a", "e"]);
});
it('should be able to only retrieve the "leaves" in the overall order', function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addNode("e");
graph.addDependency("a", "b");
graph.addDependency("a", "c");
graph.addDependency("b", "c");
graph.addDependency("c", "d");
expect(graph.overallOrder(true)).toEqual(["d", "e"]);
});
it("should be able to give the overall order for a graph with several disconnected subgraphs", function () {
var graph = new DepGraph();
graph.addNode("a_1");
graph.addNode("a_2");
graph.addNode("b_1");
graph.addNode("b_2");
graph.addNode("b_3");
graph.addDependency("a_1", "a_2");
graph.addDependency("b_1", "b_2");
graph.addDependency("b_2", "b_3");
expect(graph.overallOrder()).toEqual(["a_2", "a_1", "b_3", "b_2", "b_1"]);
});
it("should give an empty overall order for an empty graph", function () {
var graph = new DepGraph();
expect(graph.overallOrder()).toEqual([]);
});
it("should still work after nodes are removed", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
expect(graph.dependenciesOf("a")).toEqual(["c", "b"]);
graph.removeNode("c");
expect(graph.dependenciesOf("a")).toEqual(["b"]);
});
it("should clone an empty graph", function () {
var graph = new DepGraph();
expect(graph.size()).toEqual(0);
var cloned = graph.clone();
expect(cloned.size()).toEqual(0);
expect(graph === cloned).toBeFalse();
});
it("should clone a non-empty graph", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
var cloned = graph.clone();
expect(graph === cloned).toBeFalse();
expect(cloned.hasNode("a")).toBeTrue();
expect(cloned.hasNode("b")).toBeTrue();
expect(cloned.hasNode("c")).toBeTrue();
expect(cloned.dependenciesOf("a")).toEqual(["c", "b"]);
expect(cloned.dependantsOf("c")).toEqual(["a", "b"]);
// Changes to the original graph shouldn't affect the clone
graph.removeNode("c");
expect(graph.dependenciesOf("a")).toEqual(["b"]);
expect(cloned.dependenciesOf("a")).toEqual(["c", "b"]);
graph.addNode("d");
graph.addDependency("b", "d");
expect(graph.dependenciesOf("a")).toEqual(["d", "b"]);
expect(cloned.dependenciesOf("a")).toEqual(["c", "b"]);
});
it("should only be a shallow clone", function () {
var graph = new DepGraph();
var data = { a: 42 };
graph.addNode("a", data);
var cloned = graph.clone();
expect(graph === cloned).toBeFalse();
expect(graph.getNodeData("a") === cloned.getNodeData("a")).toBeTrue();
graph.getNodeData("a").a = 43;
expect(cloned.getNodeData("a").a).toBe(43);
cloned.setNodeData("a", { a: 42 });
expect(cloned.getNodeData("a").a).toBe(42);
expect(graph.getNodeData("a") === cloned.getNodeData("a")).toBeFalse();
});
});
describe("DepGraph Performance", function () {
it("should not exceed max call stack with a very deep graph", function () {
var g = new DepGraph();
var expected = [];
for (var i = 0; i < 100000; i++) {
var istr = i.toString();
g.addNode(istr);
expected.push(istr);
if (i > 0) {
g.addDependency(istr, (i - 1).toString());
}
}
var order = g.overallOrder();
expect(order).toEqual(expected);
});
it("should run an a reasonable amount of time for a very large graph", function () {
var randInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var g = new DepGraph();
var nodes = [];
// Create a graph with 100000 nodes in it with 10 random connections to
// lower numbered nodes
for (var i = 0; i < 100000; i++) {
nodes.push(i.toString());
g.addNode(i.toString());
for (var j = 0; j < 10; j++) {
var dep = randInt(0, i);
if (i !== dep) {
g.addDependency(i.toString(), dep.toString());
}
}
}
var start = new Date().getTime();
g.overallOrder();
var end = new Date().getTime();
expect(start - end).toBeLessThan(1000);
});
});
describe("DepGraphCycleError", function () {
var DepGraphCycleError = dep_graph.DepGraphCycleError;
it("should have a message", function () {
var err = new DepGraphCycleError(["a", "b", "c", "a"]);
expect(err.message).toEqual("Dependency Cycle Found: a -> b -> c -> a");
});
it("should be an instanceof DepGraphCycleError", function () {
var err = new DepGraphCycleError(["a", "b", "c", "a"]);
expect(err instanceof DepGraphCycleError).toBeTrue();
expect(err instanceof Error).toBeTrue();
});
it("should have a cyclePath", function () {
var cyclePath = ["a", "b", "c", "a"];
var err = new DepGraphCycleError(cyclePath);
expect(err.cyclePath).toEqual(cyclePath);
});
});

36
node_modules/@11ty/dependency-tree-esm/package.json generated vendored Normal file
View File

@ -0,0 +1,36 @@
{
"name": "@11ty/dependency-tree-esm",
"version": "1.0.0",
"description": "Finds all JavaScript ES Module dependencies from a filename.",
"main": "main.js",
"scripts": {
"test": "npx ava"
},
"repository": {
"type": "git",
"url": "git+https://github.com/11ty/eleventy-dependency-tree.git"
},
"author": {
"name": "Zach Leatherman",
"email": "zach@zachleat.com",
"url": "https://zachleat.com/"
},
"license": "MIT",
"dependencies": {
"@11ty/eleventy-utils": "^1.0.2",
"acorn": "^8.10.0",
"dependency-graph": "^0.11.0",
"normalize-path": "^3.0.0"
},
"devDependencies": {
"ava": "^5.3.1"
},
"ava": {
"files": [
"./test/*.js"
],
"ignoredByWatcher": [
"./test/stubs/**"
]
}
}

View File

@ -0,0 +1 @@
import "./circular-parent.js";

View File

@ -0,0 +1 @@
import "./circular-child.js";

View File

@ -0,0 +1,2 @@
import "./circular-self.js";
import "./empty.js";

View File

View File

@ -0,0 +1,2 @@
import fs from "fs";
import * as fdklsjf from "./imported-secondary.js";

View File

@ -0,0 +1,3 @@
import "fs";
export function hello() {}

View File

@ -0,0 +1,3 @@
import * as fdklsjf from "./imported-secondary.js";
export function hello() {}

View File

@ -0,0 +1 @@
import * as fdklsjf from "./nested.js";

View File

@ -0,0 +1,2 @@
import fs from "fs";
import * as fdklsjf from "./imported.js";

30
node_modules/@11ty/dependency-tree-esm/test/test.js generated vendored Normal file
View File

@ -0,0 +1,30 @@
const test = require("ava");
const { find } = require("../main.js");
test("Empty", async t => {
t.deepEqual(await find("./test/stubs/empty.js"), []);
});
test("Doesnt exist", async t => {
t.deepEqual(await find("./test/stubs/THIS_FILE_DOES_NOT_EXIST.js"), []);
});
test("Simple", async t => {
t.deepEqual(await find("./test/stubs/file.js"), ["./test/stubs/imported-secondary.js"]);
});
test("Nested two deep", async t => {
t.deepEqual(await find("./test/stubs/nested.js"), ["./test/stubs/imported.js", "./test/stubs/imported-secondary.js"]);
});
test("Nested three deep", async t => {
t.deepEqual(await find("./test/stubs/nested-grandchild.js"), ["./test/stubs/nested.js", "./test/stubs/imported.js", "./test/stubs/imported-secondary.js"]);
});
test("Circular", async t => {
t.deepEqual(await find("./test/stubs/circular-parent.js"), ["./test/stubs/circular-child.js"]);
});
test("Circular Self Reference", async t => {
t.deepEqual(await find("./test/stubs/circular-self.js"), ["./test/stubs/empty.js"]);
});

21
node_modules/@11ty/dependency-tree/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Zach Leatherman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

94
node_modules/@11ty/dependency-tree/README.md generated vendored Normal file
View File

@ -0,0 +1,94 @@
# `dependency-tree`
Returns an unordered array of local paths to dependencies of a CommonJS node JavaScript file (everything it or any of its dependencies `require`s).
* See also: [`dependency-tree-esm`](https://github.com/11ty/eleventy-dependency-tree-esm) for ES Modules.
Reduced feature (faster) alternative to the [`dependency-tree` package](https://www.npmjs.com/package/dependency-tree). This is used by Eleventy to find dependencies of a JavaScript file to watch for changes to re-run Eleventys build.
## Big Huge Caveat
⚠ A big caveat to this plugin is that it will require the file in order to build a dependency tree. So if your module has side effects and you dont want it to execute—do not use this!
## Installation
```
npm install --save-dev @11ty/dependency-tree
```
## Features
* Ignores `node_modules`
* Or, use `nodeModuleNames` to control whether or not `node_modules` package names are included (added in v2.0.1)
* Ignores Nodes built-ins (e.g. `path`)
* Handles circular dependencies (Node does this too)
## Usage
```js
// my-file.js
// if my-local-dependency.js has dependencies, it will include those too
const test = require("./my-local-dependency.js");
// ignored, is a built-in
const path = require("path");
```
```js
const DependencyTree = require("@11ty/dependency-tree");
DependencyTree("./my-file.js");
// returns ["./my-local-dependency.js"]
```
### `allowNotFound`
```js
const DependencyTree = require("@11ty/dependency-tree");
DependencyTree("./this-does-not-exist.js"); // throws an error
DependencyTree("./this-does-not-exist.js", { allowNotFound: true });
// returns []
```
### `nodeModuleNames`
(Added in v2.0.1) Controls whether or not node package names are included in the list of dependencies.
* `nodeModuleNames: "include"`: included alongside the local JS files.
* `nodeModuleNames: "exclude"` (default): node module package names are excluded.
* `nodeModuleNames: "only"`: only node module package names are returned.
```js
// my-file.js:
require("./my-local-dependency.js");
require("@11ty/eleventy");
```
```js
const DependencyTree = require("@11ty/dependency-tree");
DependencyTree("./my-file.js");
// returns ["./my-local-dependency.js"]
DependencyTree("./my-file.js", { nodeModuleNames: "exclude" });
// returns ["./my-local-dependency.js"]
DependencyTree("./my-file.js", { nodeModuleNames: "include" });
// returns ["./my-local-dependency.js", "@11ty/eleventy"]
DependencyTree("./my-file.js", { nodeModuleNames: "only" });
// returns ["@11ty/eleventy"]
```
#### (Deprecated) `nodeModuleNamesOnly`
(Added in v2.0.0) Changed to use `nodeModuleNames` option instead. Backwards compatibility is maintained automatically.
* `nodeModuleNamesOnly: false` is mapped to `nodeModuleNames: "exclude"`
* `nodeModuleNamesOnly: true` is mapped to `nodeModuleNames: "only"`
If both `nodeModuleNamesOnly` and `nodeModuleNames` are included in options, `nodeModuleNames` takes precedence.

132
node_modules/@11ty/dependency-tree/main.js generated vendored Normal file
View File

@ -0,0 +1,132 @@
const path = require("path");
const { TemplatePath } = require("@11ty/eleventy-utils");
function getAbsolutePath(filename) {
let normalizedFilename = path.normalize(filename); // removes dot slash
let hasDotSlash = filename.startsWith("./");
return hasDotSlash ? path.join(path.resolve("."), normalizedFilename) : normalizedFilename;
}
function getRelativePath(filename) {
let normalizedFilename = path.normalize(filename); // removes dot slash
let workingDirectory = path.resolve(".");
let result = "./" + (normalizedFilename.startsWith(workingDirectory) ? normalizedFilename.substr(workingDirectory.length + 1) : normalizedFilename);
return result;
}
function getNodeModuleName(filename) {
let foundNodeModules = false;
let moduleName = [];
let s = filename.split(path.sep);
for(let entry of s) {
if(entry === '.pnpm') {
foundNodeModules = false;
}
if(foundNodeModules) {
moduleName.push(entry);
if(!entry.startsWith("@")) {
return moduleName.join("/");
}
}
if(entry === "node_modules") {
foundNodeModules = true;
}
}
return false;
}
/* unordered */
function getDependenciesFor(filename, avoidCircular, optionsArg = {}) {
// backwards compatibility with `nodeModuleNamesOnly` boolean option
// Using `nodeModuleNames` property moving forward
if(("nodeModuleNamesOnly" in optionsArg) && !("nodeModuleNames" in optionsArg)) {
if(optionsArg.nodeModuleNamesOnly === true) {
optionsArg.nodeModuleNames = "only";
}
if(optionsArg.nodeModuleNamesOnly === false) {
optionsArg.nodeModuleNames = "exclude";
}
}
let options = Object.assign({
allowNotFound: false,
nodeModuleNames: "exclude", // also "include" or "only"
}, optionsArg);
let absoluteFilename = getAbsolutePath(filename)
try {
require(absoluteFilename);
} catch(e) {
if(e.code === "MODULE_NOT_FOUND" && options.allowNotFound) {
// do nothing
} else {
throw e;
}
}
let mod;
for(let entry in require.cache) {
if(entry === absoluteFilename) {
mod = require.cache[entry];
break;
}
}
let dependencies = new Set();
if(!mod) {
if(!options.allowNotFound) {
throw new Error(`Could not find ${filename} in @11ty/dependency-tree`);
}
} else {
let relativeFilename = getRelativePath(mod.filename);
if(!avoidCircular) {
avoidCircular = {};
} else if(options.nodeModuleNames !== "only") {
dependencies.add(relativeFilename);
}
avoidCircular[relativeFilename] = true;
if(mod.children) {
for(let child of mod.children) {
let relativeChildFilename = getRelativePath(child.filename);
let nodeModuleName = getNodeModuleName(child.filename);
if(options.nodeModuleNames !== "exclude" && nodeModuleName) {
dependencies.add(nodeModuleName);
}
// Add dependencies of this dependency (not top level node_modules)
if(nodeModuleName === false) {
if(!dependencies.has(relativeChildFilename) && // avoid infinite looping with circular deps
!avoidCircular[relativeChildFilename] ) {
for(let dependency of getDependenciesFor(relativeChildFilename, avoidCircular, options)) {
dependencies.add(dependency);
}
}
}
}
}
}
return dependencies;
}
function getCleanDependencyListFor(filename, options = {}) {
let deps = Array.from( getDependenciesFor(filename, null, options) );
return deps.map(filePath => {
if(filePath.startsWith("./")) {
return TemplatePath.standardizeFilePath(filePath);
}
return filePath; // node_module name
});
}
module.exports = getCleanDependencyListFor;
module.exports.getNodeModuleName = getNodeModuleName;

39
node_modules/@11ty/dependency-tree/package.json generated vendored Normal file
View File

@ -0,0 +1,39 @@
{
"name": "@11ty/dependency-tree",
"version": "3.0.1",
"description": "Finds all JavaScript CommmonJS require() dependencies from a filename.",
"main": "main.js",
"files": [
"main.js",
"!test",
"!test/**"
],
"scripts": {
"test": "npx ava"
},
"repository": {
"type": "git",
"url": "git+https://github.com/11ty/eleventy-dependency-tree.git"
},
"author": {
"name": "Zach Leatherman",
"email": "zach@zachleat.com",
"url": "https://zachleat.com/"
},
"license": "MIT",
"ava": {
"files": [
"./test/*.js"
],
"ignoredByWatcher": [
"./test/stubs/**"
]
},
"devDependencies": {
"@sindresorhus/is": "^4.6.0",
"ava": "^5.3.1"
},
"dependencies": {
"@11ty/eleventy-utils": "^1.0.2"
}
}

60
node_modules/@11ty/eleventy-dev-server/README.md generated vendored Normal file
View File

@ -0,0 +1,60 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.svg" width="200" height="200" alt="11ty Logo"></p>
# eleventy-dev-server 🕚⚡️🎈🐀
A minimal, modern, generic, hot-reloading local web server to help web developers.
## ➡ [Documentation](https://www.11ty.dev/docs/watch-serve/#eleventy-dev-server)
- Please star [Eleventy on GitHub](https://github.com/11ty/eleventy/)!
- Follow us on Twitter [@eleven_ty](https://twitter.com/eleven_ty)
- Support [11ty on Open Collective](https://opencollective.com/11ty)
- [11ty on npm](https://www.npmjs.com/org/11ty)
- [11ty on GitHub](https://github.com/11ty)
[![npm Version](https://img.shields.io/npm/v/@11ty/eleventy-dev-server.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy-dev-server)
## Installation
This is bundled with `@11ty/eleventy` (and you do not need to install it separately) in Eleventy v2.0.
## CLI
Eleventy Dev Server now also includes a CLI. The CLI is for **standalone** (non-Eleventy) use only: separate installation is unnecessary if youre using this server with `@11ty/eleventy`.
```sh
npm install -g @11ty/eleventy-dev-server
# Alternatively, install locally into your project
npm install @11ty/eleventy-dev-server
```
This package requires Node 18 or newer.
### CLI Usage
```sh
# Serve the current directory
npx @11ty/eleventy-dev-server
# Serve a different subdirectory (also aliased as --input)
npx @11ty/eleventy-dev-server --dir=_site
# Disable the `domdiff` feature
npx @11ty/eleventy-dev-server --domdiff=false
# Full command list in the Help
npx @11ty/eleventy-dev-server --help
```
## Tests
```
npm run test
```
- We use the [ava JavaScript test runner](https://github.com/avajs/ava) ([Assertions documentation](https://github.com/avajs/ava/blob/master/docs/03-assertions.md))
## Changelog
* `v2.0.0` bumps Node.js minimum to 18.

89
node_modules/@11ty/eleventy-dev-server/cli.js generated vendored Normal file
View File

@ -0,0 +1,89 @@
const pkg = require("./package.json");
const EleventyDevServer = require("./server.js");
const Logger = {
info: function(...args) {
console.log( "[11ty/eleventy-dev-server]", ...args );
},
error: function(...args) {
console.error( "[11ty/eleventy-dev-server]", ...args );
},
fatal: function(...args) {
Logger.error(...args);
process.exitCode = 1;
}
};
Logger.log = Logger.info;
class Cli {
static getVersion() {
return pkg.version;
}
static getHelp() {
return `Usage:
eleventy-dev-server
eleventy-dev-server --dir=_site
eleventy-dev-server --port=3000
Arguments:
--version
--dir=.
Directory to serve (default: \`.\`)
--input (alias for --dir)
--port=8080
Run the web server on this port (default: \`8080\`)
Will autoincrement if already in use.
--domdiff (enabled, default)
--domdiff=false (disabled)
Apply HTML changes without a full page reload.
--help`;
}
static getDefaultOptions() {
return {
port: "8080",
input: ".",
domDiff: true,
}
}
async serve(options = {}) {
this.options = Object.assign(Cli.getDefaultOptions(), options);
this.server = EleventyDevServer.getServer("eleventy-dev-server-cli", this.options.input, {
// TODO allow server configuration extensions
showVersion: true,
logger: Logger,
domDiff: this.options.domDiff,
// CLI watches all files in the folder by default
// this is different from Eleventy usage!
watch: [ this.options.input ],
});
this.server.serve(this.options.port);
// TODO? send any errors here to the server too
// with server.sendError({ error });
}
close() {
if(this.server) {
return this.server.close();
}
}
}
module.exports = {
Logger,
Cli
}

View File

@ -0,0 +1,294 @@
class Util {
static pad(num, digits = 2) {
let zeroes = new Array(digits + 1).join(0);
return `${zeroes}${num}`.slice(-1 * digits);
}
static log(message) {
Util.output("log", message);
}
static error(message, error) {
Util.output("error", message, error);
}
static output(type, ...messages) {
let now = new Date();
let date = `${Util.pad(now.getUTCHours())}:${Util.pad(
now.getUTCMinutes()
)}:${Util.pad(now.getUTCSeconds())}.${Util.pad(
now.getUTCMilliseconds(),
3
)}`;
console[type](`[11ty][${date} UTC]`, ...messages);
}
static capitalize(word) {
return word.substr(0, 1).toUpperCase() + word.substr(1);
}
static matchRootAttributes(htmlContent) {
// Workaround for morphdom bug with attributes on <html> https://github.com/11ty/eleventy-dev-server/issues/6
// Note also `childrenOnly: true` above
const parser = new DOMParser();
let parsed = parser.parseFromString(htmlContent, "text/html");
let parsedDoc = parsed.documentElement;
let newAttrs = parsedDoc.getAttributeNames();
let docEl = document.documentElement;
// Remove old
let removedAttrs = docEl.getAttributeNames().filter(name => !newAttrs.includes(name));
for(let attr of removedAttrs) {
docEl.removeAttribute(attr);
}
// Add new
for(let attr of newAttrs) {
docEl.setAttribute(attr, parsedDoc.getAttribute(attr));
}
}
static isEleventyLinkNodeMatch(from, to) {
// Issue #18 https://github.com/11ty/eleventy-dev-server/issues/18
// Dont update a <link> if the _11ty searchParam is the only thing thats different
if(from.tagName !== "LINK" || to.tagName !== "LINK") {
return false;
}
let oldWithoutHref = from.cloneNode();
let newWithoutHref = to.cloneNode();
oldWithoutHref.removeAttribute("href");
newWithoutHref.removeAttribute("href");
// if all other attributes besides href match
if(!oldWithoutHref.isEqualNode(newWithoutHref)) {
return false;
}
let oldUrl = new URL(from.href);
let newUrl = new URL(to.href);
// morphdom wants to force href="style.css?_11ty" => href="style.css"
let isErasing = oldUrl.searchParams.has("_11ty") && !newUrl.searchParams.has("_11ty");
if(!isErasing) {
// not a match if _11ty has a new value (not being erased)
return false;
}
oldUrl.searchParams.set("_11ty", "");
newUrl.searchParams.set("_11ty", "");
// is a match if erasing and the rest of the href matches too
return oldUrl.toString() === newUrl.toString();
}
// https://github.com/patrick-steele-idem/morphdom/issues/178#issuecomment-652562769
static runScript(source, target) {
let script = document.createElement('script');
// copy over the attributes
for(let attr of [...source.attributes]) {
script.setAttribute(attr.nodeName ,attr.nodeValue);
}
script.innerHTML = source.innerHTML;
(target || source).replaceWith(script);
}
}
class EleventyReload {
constructor() {
this.connectionMessageShown = false;
this.reconnectEventCallback = this.reconnect.bind(this);
}
init(options = {}) {
if (!("WebSocket" in window)) {
return;
}
let { protocol, host } = new URL(document.location.href);
// works with http (ws) and https (wss)
let websocketProtocol = protocol.replace("http", "ws");
let socket = new WebSocket(`${websocketProtocol}//${host}`);
socket.addEventListener("message", async (event) => {
try {
let data = JSON.parse(event.data);
// Util.log( JSON.stringify(data, null, 2) );
let { type } = data;
if (type === "eleventy.reload") {
await this.onreload(data);
} else if (type === "eleventy.msg") {
Util.log(`${data.message}`);
} else if (type === "eleventy.error") {
// Log Eleventy build errors
// Extra parsing for Node Error objects
let e = JSON.parse(data.error);
Util.error(`Build error: ${e.message}`, e);
} else if (type === "eleventy.status") {
// Full page reload on initial reconnect
if (data.status === "connected" && options.mode === "reconnect") {
window.location.reload();
}
if(data.status === "connected") {
// With multiple windows, only show one connection message
if(!this.isConnected) {
Util.log(Util.capitalize(data.status));
}
this.connectionMessageShown = true;
} else {
if(data.status === "disconnected") {
this.addReconnectListeners();
}
Util.log(Util.capitalize(data.status));
}
} else {
Util.log("Unknown event type", data);
}
} catch (e) {
Util.error(`Error parsing ${event.data}: ${e.message}`, e);
}
});
socket.addEventListener("open", () => {
// no reconnection when the connect is already open
this.removeReconnectListeners();
});
socket.addEventListener("close", () => {
this.connectionMessageShown = false;
this.addReconnectListeners();
});
}
reconnect() {
Util.log( "Reconnecting…" );
this.init({ mode: "reconnect" });
}
async onreload({ subtype, files, build }) {
if (subtype === "css") {
for (let link of document.querySelectorAll(`link[rel="stylesheet"]`)) {
if (link.href) {
let url = new URL(link.href);
url.searchParams.set("_11ty", Date.now());
link.href = url.toString();
}
}
Util.log(`CSS updated without page reload.`);
} else {
let morphed = false;
try {
if((build.templates || []).length > 0) {
// Important: using `./` in `./morphdom.js` allows the special `.11ty` folder to be changed upstream
const { default: morphdom } = await import(`./morphdom.js`);
// { url, inputPath, content }
for (let template of build.templates || []) {
if (template.url === document.location.pathname) {
// Importantly, if this does not match but is still relevant (layout/include/etc), a full reload happens below. This could be improved.
if ((files || []).includes(template.inputPath)) {
// Notable limitation: this wont re-run script elements or JavaScript page lifecycle events (load/DOMContentLoaded)
morphed = true;
morphdom(document.documentElement, template.content, {
childrenOnly: true,
onBeforeElUpdated: function (fromEl, toEl) {
if (fromEl.nodeName === "SCRIPT" && toEl.nodeName === "SCRIPT") {
if(toEl.innerHTML !== fromEl.innerHTML) {
Util.log(`JavaScript modified, reload initiated.`);
window.location.reload();
}
return false;
}
// Speed-up trick from morphdom docs
// https://dom.spec.whatwg.org/#concept-node-equals
if (fromEl.isEqualNode(toEl)) {
return false;
}
if(Util.isEleventyLinkNodeMatch(fromEl, toEl)) {
return false;
}
return true;
},
addChild: function(parent, child) {
// Declarative Shadow DOM https://github.com/11ty/eleventy-dev-server/issues/90
if(child.nodeName === "TEMPLATE" && child.hasAttribute("shadowrootmode")) {
let root = parent.shadowRoot;
if(root) {
// remove all shadow root children
while(root.firstChild) {
root.removeChild(root.firstChild);
}
}
for(let newChild of child.content.childNodes) {
root.appendChild(newChild);
}
} else {
parent.appendChild(child);
}
},
onNodeAdded: function (node) {
if (node.nodeName === 'SCRIPT') {
Util.log(`JavaScript added, reload initiated.`);
window.location.reload();
}
},
onElUpdated: function(node) {
// Re-attach custom elements
if(customElements.get(node.tagName.toLowerCase())) {
let placeholder = document.createElement("div");
node.replaceWith(placeholder);
requestAnimationFrame(() => {
placeholder.replaceWith(node);
placeholder = undefined;
});
}
}
});
Util.matchRootAttributes(template.content);
Util.log(`HTML delta applied without page reload.`);
}
break;
}
}
}
} catch(e) {
Util.error( "Morphdom error", e );
}
if (!morphed) {
Util.log(`Page reload initiated.`);
window.location.reload();
}
}
}
addReconnectListeners() {
this.removeReconnectListeners();
window.addEventListener("focus", this.reconnectEventCallback);
window.addEventListener("visibilitychange", this.reconnectEventCallback);
}
removeReconnectListeners() {
window.removeEventListener("focus", this.reconnectEventCallback);
window.removeEventListener("visibilitychange", this.reconnectEventCallback);
}
}
let reloader = new EleventyReload();
reloader.init();

77
node_modules/@11ty/eleventy-dev-server/cmd.js generated vendored Executable file
View File

@ -0,0 +1,77 @@
#!/usr/bin/env node
const pkg = require("./package.json");
// Node check
require("please-upgrade-node")(pkg, {
message: function (requiredVersion) {
return (
"eleventy-dev-server requires Node " +
requiredVersion +
". You will need to upgrade Node!"
);
},
});
const { Logger, Cli } = require("./cli.js");
const debug = require("debug")("Eleventy:DevServer");
try {
const defaults = Cli.getDefaultOptions();
for(let key in defaults) {
if(key.toLowerCase() !== key) {
defaults[key.toLowerCase()] = defaults[key];
delete defaults[key];
}
}
const argv = require("minimist")(process.argv.slice(2), {
string: [
"dir",
"input", // alias for dir
"port",
],
boolean: [
"version",
"help",
"domdiff",
],
default: defaults,
unknown: function (unknownArgument) {
throw new Error(
`We dont know what '${unknownArgument}' is. Use --help to see the list of supported commands.`
);
},
});
debug("command: eleventy-dev-server %o", argv);
process.on("unhandledRejection", (error, promise) => {
Logger.fatal("Unhandled rejection in promise:", promise, error);
});
process.on("uncaughtException", (error) => {
Logger.fatal("Uncaught exception:", error);
});
if (argv.version) {
console.log(Cli.getVersion());
} else if (argv.help) {
console.log(Cli.getHelp());
} else {
let cli = new Cli();
cli.serve({
input: argv.dir || argv.input,
port: argv.port,
domDiff: argv.domdiff,
});
process.on("SIGINT", async () => {
await cli.close();
process.exitCode = 0;
});
}
} catch (e) {
Logger.fatal("Fatal Error:", e)
}

58
node_modules/@11ty/eleventy-dev-server/package.json generated vendored Normal file
View File

@ -0,0 +1,58 @@
{
"name": "@11ty/eleventy-dev-server",
"version": "2.0.4",
"description": "A minimal, modern, generic, hot-reloading local web server to help web developers.",
"main": "server.js",
"scripts": {
"test": "npx ava --verbose",
"sample": "node cmd.js --input=test/stubs"
},
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/11ty"
},
"bin": {
"eleventy-dev-server": "./cmd.js"
},
"keywords": [
"eleventy",
"server",
"cli"
],
"publishConfig": {
"access": "public"
},
"author": {
"name": "Zach Leatherman",
"email": "zachleatherman@gmail.com",
"url": "https://zachleat.com/"
},
"repository": {
"type": "git",
"url": "git://github.com/11ty/eleventy-dev-server.git"
},
"bugs": "https://github.com/11ty/eleventy-dev-server/issues",
"homepage": "https://github.com/11ty/eleventy-dev-server/",
"dependencies": {
"@11ty/eleventy-utils": "^1.0.3",
"chokidar": "^3.6.0",
"debug": "^4.3.7",
"dev-ip": "^1.0.1",
"finalhandler": "^1.3.0",
"mime": "^3.0.0",
"minimist": "^1.2.8",
"morphdom": "^2.7.4",
"please-upgrade-node": "^3.2.0",
"send": "^0.19.0",
"ssri": "^11.0.0",
"urlpattern-polyfill": "^10.0.0",
"ws": "^8.18.0"
},
"devDependencies": {
"ava": "^6.1.3"
}
}

950
node_modules/@11ty/eleventy-dev-server/server.js generated vendored Normal file
View File

@ -0,0 +1,950 @@
const path = require("node:path");
const fs = require("node:fs");
const finalhandler = require("finalhandler");
const WebSocket = require("ws");
const { WebSocketServer } = WebSocket;
const mime = require("mime");
const ssri = require("ssri");
const send = require("send");
const devip = require("dev-ip");
const chokidar = require("chokidar");
const { TemplatePath, isPlainObject } = require("@11ty/eleventy-utils");
const debug = require("debug")("Eleventy:DevServer");
const pkg = require("./package.json");
const wrapResponse = require("./server/wrapResponse.js");
if (!globalThis.URLPattern) {
require("urlpattern-polyfill");
}
const DEFAULT_OPTIONS = {
port: 8080,
liveReload: true, // Enable live reload at all
showAllHosts: false, // IP address based hosts (other than localhost)
injectedScriptsFolder: ".11ty", // Change the name of the special folder used for injected scripts
portReassignmentRetryCount: 10, // number of times to increment the port if in use
https: {}, // `key` and `cert`, required for http/2 and https
domDiff: true, // Use morphdom to apply DOM diffing delta updates to HTML
showVersion: false, // Whether or not to show the server version on the command line.
encoding: "utf-8", // Default file encoding
pathPrefix: "/", // May be overridden by Eleventy, adds a virtual base directory to your project
watch: [], // Globs to pass to separate dev server chokidar for watching
aliases: {}, // Aliasing feature
indexFileName: "index.html", // Allow custom index file name
useCache: false, // Use a cache for file contents
headers: {}, // Set default response headers
messageOnStart: ({ hosts, startupTime, version, options }) => {
let hostsStr = " started";
if(Array.isArray(hosts) && hosts.length > 0) {
// TODO what happens when the cert doesnt cover non-localhost hosts?
hostsStr = ` at ${hosts.join(" or ")}`;
}
return `Server${hostsStr}${options.showVersion ? ` (v${version})` : ""}`;
},
onRequest: {}, // Maps URLPatterns to dynamic callback functions that run on a request from a client.
// Example:
// "/foo/:name": function({ url, pattern, patternGroups }) {
// return {
// headers: {
// "Content-Type": "text/html",
// },
// body: `${url} ${JSON.stringify(patternGroups)}`
// }
// }
// Logger (fancier one is injected by Eleventy)
logger: {
info: console.log,
log: console.log,
error: console.error,
}
}
class EleventyDevServer {
static getServer(...args) {
return new EleventyDevServer(...args);
}
constructor(name, dir, options = {}) {
debug("Creating new Dev Server instance.")
this.name = name;
this.normalizeOptions(options);
this.fileCache = {};
// Directory to serve
if(!dir) {
throw new Error("Missing `dir` to serve.");
}
this.dir = dir;
this.logger = this.options.logger;
if(this.options.watch.length > 0) {
this.getWatcher();
}
}
normalizeOptions(options = {}) {
this.options = Object.assign({}, DEFAULT_OPTIONS, options);
// better names for options https://github.com/11ty/eleventy-dev-server/issues/41
if(options.folder !== undefined) {
this.options.injectedScriptsFolder = options.folder;
delete this.options.folder;
}
if(options.domdiff !== undefined) {
this.options.domDiff = options.domdiff;
delete this.options.domdiff;
}
if(options.enabled !== undefined) {
this.options.liveReload = options.enabled;
delete this.options.enabled;
}
this.options.pathPrefix = this.cleanupPathPrefix(this.options.pathPrefix);
}
get watcher() {
if(!this._watcher) {
debug("Watching %O", this.options.watch);
// TODO if using Eleventy and `watch` option includes output folder (_site) this will trigger two update events!
this._watcher = chokidar.watch(this.options.watch, {
// TODO allow chokidar configuration extensions (or re-use the ones in Eleventy)
ignored: ["**/node_modules/**", ".git"],
ignoreInitial: true,
// same values as Eleventy
awaitWriteFinish: {
stabilityThreshold: 150,
pollInterval: 25,
},
});
this._watcher.on("change", (path) => {
this.logger.log( `File changed: ${path} (skips build)` );
this.reloadFiles([path]);
});
this._watcher.on("add", (path) => {
this.logger.log( `File added: ${path} (skips build)` );
this.reloadFiles([path]);
});
}
return this._watcher;
}
getWatcher() {
return this.watcher;
}
watchFiles(files) {
if(Array.isArray(files)) {
files = files.map(entry => TemplatePath.stripLeadingDotSlash(entry));
debug("Also watching %O", files);
this.watcher.add(files);
}
}
cleanupPathPrefix(pathPrefix) {
if(!pathPrefix || pathPrefix === "/") {
return "/";
}
if(!pathPrefix.startsWith("/")) {
pathPrefix = `/${pathPrefix}`
}
if(!pathPrefix.endsWith("/")) {
pathPrefix = `${pathPrefix}/`;
}
return pathPrefix;
}
// Allowed list of files that can be served from outside `dir`
setAliases(aliases) {
if(aliases) {
this.passthroughAliases = aliases;
debug( "Setting aliases (emulated passthrough copy) %O", aliases );
}
}
matchPassthroughAlias(url) {
let aliases = Object.assign({}, this.options.aliases, this.passthroughAliases);
for(let targetUrl in aliases) {
if(!targetUrl) {
continue;
}
let file = aliases[targetUrl];
if(url.startsWith(targetUrl)) {
let inputDirectoryPath = file + url.slice(targetUrl.length);
// e.g. addPassthroughCopy("img/") but <img src="/img/built/IdthKOzqFA-350.png">
// generated by the image plugin (written to the output folder)
// If they do not exist in the input directory, this will fallback to the output directory.
if(fs.existsSync(inputDirectoryPath)) {
return inputDirectoryPath;
}
}
}
return false;
}
isFileInDirectory(dir, file) {
let absoluteDir = TemplatePath.absolutePath(dir);
let absoluteFile = TemplatePath.absolutePath(file);
return absoluteFile.startsWith(absoluteDir);
}
getOutputDirFilePath(filepath, filename = "") {
let computedPath;
if(filename === ".html") {
// avoid trailing slash for filepath/.html requests
let prefix = path.join(this.dir, filepath);
if(prefix.endsWith(path.sep)) {
prefix = prefix.substring(0, prefix.length - path.sep.length);
}
computedPath = prefix + filename;
} else {
computedPath = path.join(this.dir, filepath, filename);
}
computedPath = decodeURIComponent(computedPath);
if(!filename) { // is a direct URL request (not an implicit .html or index.html add)
let alias = this.matchPassthroughAlias(filepath);
if(alias) {
if(!this.isFileInDirectory(path.resolve("."), alias)) {
throw new Error("Invalid path");
}
return alias;
}
}
// Check that the file is in the output path (error if folks try use `..` in the filepath)
if(!this.isFileInDirectory(this.dir, computedPath)) {
throw new Error("Invalid path");
}
return computedPath;
}
isOutputFilePathExists(rawPath) {
return fs.existsSync(rawPath) && !TemplatePath.isDirectorySync(rawPath);
}
/* Use conventions documented here https://www.zachleat.com/web/trailing-slash/
* resource.html exists:
* /resource matches
* /resource/ redirects to /resource
* resource/index.html exists:
* /resource redirects to /resource/
* /resource/ matches
* both resource.html and resource/index.html exists:
* /resource matches /resource.html
* /resource/ matches /resource/index.html
*/
mapUrlToFilePath(url) {
// Note: `localhost` is not important here, any host would work
let u = new URL(url, "http://localhost/");
url = u.pathname;
// Remove PathPrefix from start of URL
if (this.options.pathPrefix !== "/") {
// Requests to root should redirect to new pathPrefix
if(url === "/") {
return {
statusCode: 302,
url: this.options.pathPrefix,
}
}
// Requests to anything outside of root should fail with 404
if (!url.startsWith(this.options.pathPrefix)) {
return {
statusCode: 404,
};
}
url = url.slice(this.options.pathPrefix.length - 1);
}
let rawPath = this.getOutputDirFilePath(url);
if (this.isOutputFilePathExists(rawPath)) {
return {
statusCode: 200,
filepath: rawPath,
};
}
let indexHtmlPath = this.getOutputDirFilePath(url, this.options.indexFileName);
let indexHtmlExists = fs.existsSync(indexHtmlPath);
let htmlPath = this.getOutputDirFilePath(url, ".html");
let htmlExists = fs.existsSync(htmlPath);
// /resource/ => /resource/index.html
if (indexHtmlExists && url.endsWith("/")) {
return {
statusCode: 200,
filepath: indexHtmlPath,
};
}
// /resource => resource.html
if (htmlExists && !url.endsWith("/")) {
return {
statusCode: 200,
filepath: htmlPath,
};
}
// /resource => redirect to /resource/
if (indexHtmlExists && !url.endsWith("/")) {
return {
statusCode: 301,
url: u.pathname + "/",
};
}
// /resource/ => redirect to /resource
if (htmlExists && url.endsWith("/")) {
return {
statusCode: 301,
url: u.pathname.substring(0, u.pathname.length - 1),
};
}
return {
statusCode: 404,
};
}
_getFileContents(localpath, rootDir) {
if(this.options.useCache && this.fileCache[localpath]) {
return this.fileCache[localpath];
}
let filepath;
let searchLocations = [];
if(rootDir) {
searchLocations.push(TemplatePath.absolutePath(rootDir, localpath));
}
// fallbacks for file:../ installations
searchLocations.push(TemplatePath.absolutePath(__dirname, localpath));
searchLocations.push(TemplatePath.absolutePath(__dirname, "../../../", localpath));
for(let loc of searchLocations) {
if(fs.existsSync(loc)) {
filepath = loc;
break;
}
}
let contents = fs.readFileSync(filepath, {
encoding: this.options.encoding,
});
if(this.options.useCache) {
this.fileCache[localpath] = contents;
}
return contents;
}
augmentContentWithNotifier(content, inlineContents = false, options = {}) {
let { integrityHash, scriptContents } = options;
if(!scriptContents) {
scriptContents = this._getFileContents("./client/reload-client.js");
}
if(!integrityHash) {
integrityHash = ssri.fromData(scriptContents);
}
// This isnt super necessary because its a local file, but its included anyway
let script = `<script type="module" integrity="${integrityHash}"${inlineContents ? `>${scriptContents}` : ` src="/${this.options.injectedScriptsFolder}/reload-client.js">`}</script>`;
if (content.includes("</head>")) {
return content.replace("</head>", `${script}</head>`);
}
// If the HTML document contains an importmap, insert the module script after the importmap element
let importMapRegEx = /<script type=\\?importmap\\?[^>]*>(\n|.)*?<\/script>/gmi;
let importMapMatch = content.match(importMapRegEx)?.[0];
if (importMapMatch) {
return content.replace(importMapMatch, `${importMapMatch}${script}`);
}
// <title> is the only *required* element in an HTML document
if (content.includes("</title>")) {
return content.replace("</title>", `</title>${script}`);
}
// If youve reached this section, your HTML is invalid!
// We want to be super forgiving here, because folks might be in-progress editing the document!
if (content.includes("</body>")) {
return content.replace("</body>", `${script}</body>`);
}
if (content.includes("</html>")) {
return content.replace("</html>", `${script}</html>`);
}
if (content.includes("<!doctype html>")) {
return content.replace("<!doctype html>", `<!doctype html>${script}`);
}
// Notably, works without content at all!!
return (content || "") + script;
}
getFileContentType(filepath, res) {
let contentType = res.getHeader("Content-Type");
// Content-Type might be already set via middleware
if (contentType) {
return contentType;
}
let mimeType = mime.getType(filepath);
if (!mimeType) {
return;
}
contentType = mimeType;
// We only want to append charset if the header is not already set
if (contentType === "text/html") {
contentType = `text/html; charset=${this.options.encoding}`;
}
return contentType;
}
renderFile(filepath, res) {
let contents = fs.readFileSync(filepath);
let contentType = this.getFileContentType(filepath, res);
for(const [key, value] of Object.entries(this.options.headers)){
res.setHeader(key, value);
}
if (!contentType) {
return res.end(contents);
}
res.setHeader("Content-Type", contentType);
if (contentType.startsWith("text/html")) {
// the string is important here, wrapResponse expects strings internally for HTML content (for now)
return res.end(contents.toString());
}
return res.end(contents);
}
async eleventyDevServerMiddleware(req, res, next) {
for(let urlPatternString in this.options.onRequest) {
let fn = this.options.onRequest[urlPatternString];
let fullPath = this.getServerPath(urlPatternString);
let p = new URLPattern({ pathname: fullPath });
// request url should already include pathprefix.
let fullUrl = this.getServerUrlRaw("localhost", req.url);
let match = p.exec(fullUrl);
let u = new URL(fullUrl);
if(match) {
let result = await fn({
url: u,
pattern: p,
patternGroups: match?.pathname?.groups || {},
});
if(!result && result !== "") {
continue;
}
if(typeof result === "string") {
return res.end(result);
}
if(isPlainObject(result)) {
if(typeof result.status === "number") {
res.statusCode = result.status;
}
if(isPlainObject(result.headers)) {
for(let name in result.headers) {
res.setHeader(name, result.headers[name]);
}
}
return res.end(result.body || "");
}
throw new Error(`Invalid return type from \`onRequest\` pattern for ${urlPatternString}: expected string or object.`);
}
}
if(req.url === `/${this.options.injectedScriptsFolder}/reload-client.js`) {
if(this.options.liveReload) {
res.setHeader("Content-Type", mime.getType("js"));
return res.end(this._getFileContents("./client/reload-client.js"));
}
} else if(req.url === `/${this.options.injectedScriptsFolder}/morphdom.js`) {
if(this.options.domDiff) {
res.setHeader("Content-Type", mime.getType("js"));
return res.end(this._getFileContents("./node_modules/morphdom/dist/morphdom-esm.js", path.resolve(".")));
}
}
next();
}
// This runs at the end of the middleware chain
eleventyProjectMiddleware(req, res) {
// Known issue with `finalhandler` and HTTP/2:
// UnsupportedWarning: Status message is not supported by HTTP/2 (RFC7540 8.1.2.4)
// https://github.com/pillarjs/finalhandler/pull/34
let lastNext = finalhandler(req, res, {
onerror: (e) => {
if (e.statusCode === 404) {
let localPath = TemplatePath.stripLeadingSubPath(
e.path,
TemplatePath.absolutePath(this.dir)
);
this.logger.error(
`HTTP ${e.statusCode}: Template not found in output directory (${this.dir}): ${localPath}`
);
} else {
this.logger.error(`HTTP ${e.statusCode}: ${e.message}`);
}
},
});
// middleware (maybe a serverless request) already set a body upstream, skip this part
if(!res._shouldForceEnd) {
let match = this.mapUrlToFilePath(req.url);
debug( req.url, match );
if (match) {
// Content-Range request, probably Safari trying to stream video
if (req.headers.range) {
return send(req, match.filepath).pipe(res);
}
if (match.statusCode === 200 && match.filepath) {
return this.renderFile(match.filepath, res);
}
// Redirects, usually for trailing slash to .html stuff
if (match.url) {
res.statusCode = match.statusCode;
res.setHeader("Location", match.url);
return res.end();
}
let raw404Path = this.getOutputDirFilePath("404.html");
if(match.statusCode === 404 && this.isOutputFilePathExists(raw404Path)) {
res.statusCode = match.statusCode;
res.isCustomErrorPage = true;
return this.renderFile(raw404Path, res);
}
}
}
if(res.body && !res.bodyUsed) {
if(res._shouldForceEnd) {
res.end();
} else {
let err = new Error("A response was never written to the stream. Are you missing a server middleware with `res.end()`?");
err.statusCode = 500;
lastNext(err);
return;
}
}
lastNext();
}
async onRequestHandler (req, res) {
res = wrapResponse(res, content => {
// check to see if this is a client fetch and not a navigation
let isXHR = req.headers["sec-fetch-mode"] && req.headers["sec-fetch-mode"] != "navigate";
if(this.options.liveReload !== false && !isXHR) {
let scriptContents = this._getFileContents("./client/reload-client.js");
let integrityHash = ssri.fromData(scriptContents);
// Bare (not-custom) finalhandler error pages have a Content-Security-Policy `default-src 'none'` that
// prevents the client script from executing, so we override it
if(res.statusCode !== 200 && !res.isCustomErrorPage) {
res.setHeader("Content-Security-Policy", `script-src '${integrityHash}'`);
}
return this.augmentContentWithNotifier(content, res.statusCode !== 200, {
scriptContents,
integrityHash
});
}
return content;
});
let middlewares = this.options.middleware || [];
middlewares = middlewares.slice();
// TODO because this runs at the very end of the middleware chain,
// if we move the static stuff up in the order we could use middleware to modify
// the static content in middleware!
middlewares.push(this.eleventyProjectMiddleware);
middlewares.reverse();
// Runs very first in the middleware chain
middlewares.push(this.eleventyDevServerMiddleware);
let bound = [];
let next;
for(let ware of middlewares) {
let fn;
if(next) {
fn = ware.bind(this, req, res, next);
} else {
fn = ware.bind(this, req, res);
}
bound.push(fn);
next = fn;
}
bound.reverse();
let [first] = bound;
await first();
}
getHosts() {
let hosts = new Set();
if(this.options.showAllHosts) {
for(let host of devip()) {
hosts.add(this.getServerUrl(host));
}
}
hosts.add(this.getServerUrl("localhost"));
return Array.from(hosts);
}
get server() {
if (this._server) {
return this._server;
}
this.start = Date.now();
// Check for secure server requirements, otherwise use HTTP
let { key, cert } = this.options.https;
if(key && cert) {
const { createSecureServer } = require("http2");
let options = {
allowHTTP1: true,
// Credentials
key: fs.readFileSync(key),
cert: fs.readFileSync(cert),
};
this._server = createSecureServer(options, this.onRequestHandler.bind(this));
this._serverProtocol = "https:";
} else {
const { createServer } = require("http");
this._server = createServer(this.onRequestHandler.bind(this));
this._serverProtocol = "http:";
}
this.portRetryCount = 0;
this._server.on("error", (err) => {
if (err.code == "EADDRINUSE") {
if (this.portRetryCount < this.options.portReassignmentRetryCount) {
this.portRetryCount++;
debug(
"Server already using port %o, trying the next port %o. Retry number %o of %o",
err.port,
err.port + 1,
this.portRetryCount,
this.options.portReassignmentRetryCount
);
this._serverListen(err.port + 1);
} else {
throw new Error(
`Tried ${this.options.portReassignmentRetryCount} different ports but they were all in use. You can a different starter port using --port on the command line.`
);
}
} else {
this._serverErrorHandler(err);
}
});
this._server.on("listening", (e) => {
this.setupReloadNotifier();
let logMessageCallback = typeof this.options.messageOnStart === "function" ? this.options.messageOnStart : () => false;
let hosts = this.getHosts();
let message = logMessageCallback({
hosts,
localhostUrl: this.getServerUrl("localhost"),
options: this.options,
version: pkg.version,
startupTime: Date.now() - this.start,
});
if(message) {
this.logger.info(message);
}
});
return this._server;
}
_serverListen(port) {
this.server.listen({
port,
});
}
getServerPath(pathname) {
// duplicate slashes
if(this.options.pathPrefix.endsWith("/") && pathname.startsWith("/")) {
pathname = pathname.slice(1);
}
return `${this.options.pathPrefix}${pathname}`;
}
getServerUrlRaw(host, pathname = "", isRaw = true) {
if(!this._server || !this._serverProtocol) {
throw new Error("Access to `serverUrl` property not yet available.");
}
let { port } = this._server.address();
return `${this._serverProtocol}//${host}:${port}${isRaw ? pathname : this.getServerPath(pathname)}`;
}
getServerUrl(host, pathname = "") {
return this.getServerUrlRaw(host, pathname, false);
}
async getPort() {
return new Promise(resolve => {
this.server.on("listening", (e) => {
let { port } = this._server.address();
resolve(port);
});
})
}
serve(port) {
this.getWatcher();
this._serverListen(port);
}
_serverErrorHandler(err) {
if (err.code == "EADDRINUSE") {
this.logger.error(`Server error: Port in use ${err.port}`);
} else {
this.logger.error(`Server error: ${err.message}`);
}
}
// Websocket Notifications
setupReloadNotifier() {
let updateServer = new WebSocketServer({
// includes the port
server: this.server,
});
updateServer.on("connection", (ws) => {
this.sendUpdateNotification({
type: "eleventy.status",
status: "connected",
});
});
updateServer.on("error", (err) => {
this._serverErrorHandler(err);
});
this.updateServer = updateServer;
}
// Broadcasts to all open browser windows
sendUpdateNotification(obj) {
if(!this.updateServer?.clients) {
return;
}
for(let client of this.updateServer.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(obj));
}
}
}
// Helper for promisifying close methods with callbacks, like http.Server or ws.WebSocketServer.
_closeServer(server) {
return new Promise((resolve, reject) => {
server.close(err => {
if (err) {
reject(err);
}
resolve();
});
});
}
async close() {
// Prevent multiple invocations.
if (this?._isClosing) {
return;
}
this._isClosing = true;
// TODO would be awesome to set a delayed redirect when port changed to redirect to new _server_
this.sendUpdateNotification({
type: "eleventy.status",
status: "disconnected",
});
if(this.updateServer) {
// Close all existing WS connections.
this.updateServer?.clients.forEach(socket => socket.close());
await this._closeServer(this.updateServer);
}
if(this._server?.listening) {
await this._closeServer(this.server);
}
if(this._watcher) {
await this._watcher.close();
delete this._watcher;
}
delete this._isClosing;
}
sendError({ error }) {
this.sendUpdateNotification({
type: "eleventy.error",
// Thanks https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
error: JSON.stringify(error, Object.getOwnPropertyNames(error)),
});
}
// reverse of mapUrlToFilePath
// /resource/ <= /resource/index.html
// /resource <= resource.html
getUrlsFromFilePath(path) {
if(this.dir === ".") {
path = `/${path}`
} else {
path = path.slice(this.dir.length);
}
let urls = [];
urls.push(path);
if(path.endsWith(`/${this.options.indexFileName}`)) {
urls.push(path.slice(0, -1 * this.options.indexFileName.length));
} else if(path.endsWith(".html")) {
urls.push(path.slice(0, -1 * ".html".length));
}
return urls;
}
// [{ url, inputPath, content }]
getBuildTemplatesFromFilePath(path) {
// We can skip this for non-html files, dom-diffing will not apply
if(!path.endsWith(".html")) {
return [];
}
let urls = this.getUrlsFromFilePath(path);
let obj = {
inputPath: path,
content: fs.readFileSync(path, "utf8"),
}
return urls.map(url => {
return Object.assign({ url }, obj);
});
}
reloadFiles(files, useDomDiffingForHtml = true) {
if(!Array.isArray(files)) {
throw new Error("reloadFiles method requires an array of file paths.");
}
let subtype;
if(!files.some((entry) => !entry.endsWith(".css"))) {
// all css changes
subtype = "css";
}
let templates = [];
if(useDomDiffingForHtml && this.options.domDiff) {
for(let filePath of files) {
if(!filePath.endsWith(".html")) {
continue;
}
for(let templateEntry of this.getBuildTemplatesFromFilePath(filePath)) {
templates.push(templateEntry);
}
}
}
this.reload({
files,
subtype,
build: {
templates
}
});
}
reload(event) {
let { subtype, files, build } = event;
if (build?.templates) {
build.templates = build.templates
.filter(entry => {
if(!this.options.domDiff) {
// Dont include any files if the dom diffing option is disabled
return false;
}
// Filter to only include watched templates that were updated
return (files || []).includes(entry.inputPath);
});
}
this.sendUpdateNotification({
type: "eleventy.reload",
subtype,
files,
build,
});
}
}
module.exports = EleventyDevServer;

View File

@ -0,0 +1,129 @@
function getContentType(headers) {
if(!headers) {
return;
}
for(let key in headers) {
if(key.toLowerCase() === "content-type") {
return headers[key];
}
}
}
// Inspired by `resp-modifier` https://github.com/shakyShane/resp-modifier/blob/4a000203c9db630bcfc3b6bb8ea2abc090ae0139/index.js
function wrapResponse(resp, transformHtml) {
resp._wrappedOriginalWrite = resp.write;
resp._wrappedOriginalWriteHead = resp.writeHead;
resp._wrappedOriginalEnd = resp.end;
resp._wrappedHeaders = [];
resp._wrappedTransformHtml = transformHtml;
resp._hasEnded = false;
resp._shouldForceEnd = false;
// Compatibility with web standards Response()
Object.defineProperty(resp, "body", {
// Returns write cache
get: function() {
if(typeof this._writeCache === "string") {
return this._writeCache;
}
},
// Usage:
// res.body = ""; // overwrite existing content
// res.body += ""; // append to existing content, can also res.write("") to append
set: function(data) {
if(typeof data === "string") {
this._writeCache = data;
}
}
});
// Compatibility with web standards Response()
Object.defineProperty(resp, "bodyUsed", {
get: function() {
return this._hasEnded;
}
})
// Original signature writeHead(statusCode[, statusMessage][, headers])
resp.writeHead = function(statusCode, ...args) {
let headers = args[args.length - 1];
// statusMessage is a string
if(typeof headers !== "string") {
this._contentType = getContentType(headers);
}
if((this._contentType || "").startsWith("text/html")) {
this._wrappedHeaders.push([statusCode, ...args]);
} else {
return this._wrappedOriginalWriteHead(statusCode, ...args);
}
return this;
}
// data can be a String or Buffer
resp.write = function(data, ...args) {
if(typeof data === "string") {
if(!this._writeCache) {
this._writeCache = "";
}
// TODO encoding and callback args
this._writeCache += data;
} else {
// Buffers
return this._wrappedOriginalWrite(data, ...args);
}
return this;
}
// data can be a String or Buffer
resp.end = function(data, encoding, callback) {
resp._hasEnded = true;
if(typeof this._writeCache === "string" || typeof data === "string") {
// Strings
if(!this._writeCache) {
this._writeCache = "";
}
if(typeof data === "string") {
this._writeCache += data;
}
let result = this._writeCache;
// Only transform HTML
// Note the “setHeader versus writeHead” note on https://nodejs.org/api/http.html#responsewriteheadstatuscode-statusmessage-headers
let contentType = this._contentType || getContentType(this.getHeaders());
if(contentType && contentType.startsWith("text/html")) {
if(this._wrappedTransformHtml && typeof this._wrappedTransformHtml === "function") {
result = this._wrappedTransformHtml(result);
this.setHeader("Content-Length", Buffer.byteLength(result));
}
}
for(let headers of this._wrappedHeaders) {
this._wrappedOriginalWriteHead(...headers);
}
this._writeCache = [];
this._wrappedOriginalWrite(result, encoding)
return this._wrappedOriginalEnd(callback);
} else {
// Buffers
for(let headers of this._wrappedHeaders) {
this._wrappedOriginalWriteHead(...headers);
}
if(data) {
this._wrappedOriginalWrite(data, encoding);
}
return this._wrappedOriginalEnd(callback);
}
}
return resp;
}
module.exports = wrapResponse;

337
node_modules/@11ty/eleventy-plugin-bundle/README.md generated vendored Normal file
View File

@ -0,0 +1,337 @@
# eleventy-plugin-bundle
Little bundles of code, little bundles of joy.
Create minimal per-page or app-level bundles of CSS, JavaScript, or HTML to be included in your Eleventy project.
Makes it easy to implement Critical CSS, in-use-only CSS/JS bundles, SVG icon libraries, or secondary HTML content to load via XHR.
## Why?
This project is a minimum-viable-bundler and asset pipeline in Eleventy. It does not perform any transpilation or code manipulation (by default). The code you put in is the code you get out (with configurable `transforms` if youd like to modify the code).
For more larger, more complex use cases you may want to use a more full featured bundler like Vite, Parcel, Webpack, rollup, esbuild, or others.
But do note that a full-featured bundler has a significant build performance cost, so take care to weigh the cost of using that style of bundler against whether or not this plugin has sufficient functionality for your use case—especially as the platform matures and we see diminishing returns on code transpilation (ES modules everywhere).
## Installation
No installation necessary. Starting with Eleventy `v3.0.0-alpha.10` and newer, this plugin is now bundled with Eleventy.
## Usage
By default, Bundle Plugin v2.0 does not include any default bundles. You must add these yourself via `eleventyConfig.addBundle`. One notable exception happens when using the WebC Eleventy Plugin, which adds `css`, `js`, and `html` bundles for you.
To create a bundle type, use `eleventyConfig.addBundle` in your Eleventy configuration file (default `.eleventy.js`):
```js
// .eleventy.js
export default function(eleventyConfig) {
eleventyConfig.addBundle("css");
};
```
This does two things:
1. Creates a new `css` shortcode for adding arbitrary code to this bundle
2. Adds `"css"` as an eligible type argument to the `getBundle` and `getBundleFileUrl` shortcodes.
### Full options list
```js
export default function(eleventyConfig) {
eleventyConfig.addBundle("css", {
// (Optional) Folder (relative to output directory) files will write to
toFileDirectory: "bundle",
// (Optional) File extension used for bundle file output, defaults to bundle name
outputFileExtension: "css",
// (Optional) Name of shortcode for use in templates, defaults to bundle name
shortcodeName: "css",
// shortcodeName: false, // disable this feature.
// (Optional) Modify bundle content
transforms: [],
// (Optional) If two identical code blocks exist in non-default buckets, theyll be hoisted to the first bucket in common.
hoist: true,
// (Optional) In 11ty.js templates, having a named export of `bundle` will populate your bundles.
bundleExportKey: "bundle",
// bundleExportKey: false, // disable this feature.
});
};
```
Read more about [`hoist` and duplicate bundle hoisting](https://github.com/11ty/eleventy-plugin-bundle/issues/5).
### Universal Shortcodes
The following Universal Shortcodes (available in `njk`, `liquid`, `hbs`, `11ty.js`, and `webc`) are provided by this plugin:
* `getBundle` to retrieve bundled code as a string.
* `getBundleFileUrl` to create a bundle file on disk and retrieve the URL to that file.
Heres a [real-world commit showing this in use on the `eleventy-base-blog` project](https://github.com/11ty/eleventy-base-blog/commit/c9595d8f42752fa72c66991c71f281ea960840c9?diff=split).
### Example: Add bundle code in a Markdown file in Eleventy
```md
# My Blog Post
This is some content, I am writing markup.
{% css %}
em { font-style: italic; }
{% endcss %}
## More Markdown
{% css %}
strong { font-weight: bold; }
{% endcss %}
```
Renders to:
```html
<h1>My Blog Post</h1>
<p>This is some content, I am writing markup.</p>
<h2>More Markdown</h2>
```
Note that the bundled code is excluded!
_There are a few [more examples below](#examples)!_
### Render bundle code
```html
<!-- Use this *anywhere*: a layout file, content template, etc -->
<style>{% getBundle "css" %}</style>
<!--
You can add more code to the bundle after calling
getBundle and it will be included.
-->
{% css %}* { color: orange; }{% endcss %}
```
### Write a bundle to a file
Writes the bundle content to a content-hashed file location in your output directory and returns the URL to the file for use like this:
```html
<link rel="stylesheet" href="{% getBundleFileUrl "css" %}">
```
Note that writing bundles to files will likely be slower for empty-cache first time visitors but better cached in the browser for repeat-views (and across multiple pages, too).
### Asset bucketing
```html
<!-- This goes into a `defer` bucket (the bucket can be any string value) -->
{% css "defer" %}em { font-style: italic; }{% endcss %}
```
```html
<!-- Pass the arbitrary `defer` bucket name as an additional argument -->
<style>{% getBundle "css", "defer" %}</style>
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}">
```
A `default` bucket is implied:
```html
<!-- These two statements are the same -->
{% css %}em { font-style: italic; }{% endcss %}
{% css "default" %}em { font-style: italic; }{% endcss %}
<!-- These two are the same too -->
<style>{% getBundle "css" %}</style>
<style>{% getBundle "css", "default" %}</style>
```
### Examples
#### Critical CSS
```js
// .eleventy.js
export default function(eleventyConfig) {
eleventyConfig.addBundle("css");
};
```
Use asset bucketing to divide CSS between the `default` bucket and a `defer` bucket, loaded asynchronously.
_(Note that some HTML boilerplate has been omitted from the sample below)_
```html
<!---->
<head>
<!-- Inlined critical styles -->
<style>{% getBundle "css" %}</style>
<!-- Deferred non-critical styles -->
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}" media="print" onload="this.media='all'">
<noscript>
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}">
</noscript>
</head>
<body>
<!-- This goes into a `default` bucket -->
{% css %}/* Inline in the head, great with @font-face! */{% endcss %}
<!-- This goes into a `defer` bucket (the bucket can be any string value) -->
{% css "defer" %}/* Load me later */{% endcss %}
</body>
<!---->
```
**Related**:
* Check out the [demo of Critical CSS using Eleventy Edge](https://demo-eleventy-edge.netlify.app/critical-css/) for a repeat view optimization without JavaScript.
* You may want to improve the above code with [`fetchpriority`](https://www.smashingmagazine.com/2022/04/boost-resource-loading-new-priority-hint-fetchpriority/) when [browser support improves](https://caniuse.com/mdn-html_elements_link_fetchpriority).
#### SVG Icon Library
Here an `svg` is bundle is created.
```js
// .eleventy.js
export default function(eleventyConfig) {
eleventyConfig.addBundle("svg");
};
```
```html
<svg width="0" height="0" aria-hidden="true" style="position: absolute;">
<defs>{% getBundle "svg" %}</defs>
</svg>
<!-- And anywhere on your page you can add icons to the set -->
{% svg %}
<g id="icon-close"><path d="…" /></g>
{% endsvg %}
And now you can use `icon-close` in as many SVG instances as youd like (without repeating the heftier SVG content).
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
```
#### React Helmet-style `<head>` additions
```js
// .eleventy.js
export default function(eleventyConfig) {
eleventyConfig.addBundle("html");
};
```
This might exist in an Eleventy layout file:
```html
<head>
{% getBundle "html", "head" %}
</head>
```
And then in your content you might want to page-specific `preconnect`:
```html
{% html "head" %}
<link href="https://v1.opengraph.11ty.dev" rel="preconnect" crossorigin>
{% endhtml %}
```
#### Bundle Sass with the Render Plugin
You can render template syntax inside of the `{% css %}` shortcode too, if youd like to do more advanced things using Eleventy template types.
This example assumes you have added the [Render plugin](https://www.11ty.dev/docs/plugins/render/) and the [`scss` custom template type](https://www.11ty.dev/docs/languages/custom/) to your Eleventy configuration file.
```html
{% css %}
{% renderTemplate "scss" %}
h1 { .test { color: red; } }
{% endrenderTemplate %}
{% endcss %}
```
Now the compiled Sass is available in your default bundle and will show up in `getBundle` and `getBundleFileUrl`.
#### Use with [WebC](https://www.11ty.dev/docs/languages/webc/)
Starting with `@11ty/eleventy-plugin-webc@0.9.0` (track at [issue #48](https://github.com/11ty/eleventy-plugin-webc/issues/48)) this plugin is used by default in the Eleventy WebC plugin. Specifically, [WebC Bundler Mode](https://www.11ty.dev/docs/languages/webc/#css-and-js-(bundler-mode)) now uses the bundle plugin under the hood.
To add CSS to a bundle in WebC, you would use a `<style>` element in a WebC page or component:
```html
<style>/* This is bundled. */</style>
<style webc:keep>/* Do not bundle me—leave as is */</style>
```
To add JS to a page bundle in WebC, you would use a `<script>` element in a WebC page or component:
```html
<script>/* This is bundled. */</script>
<script webc:keep>/* Do not bundle me—leave as is */</script>
```
* Existing calls via WebC helpers `getCss` or `getJs` (e.g. `<style @raw="getCss(page.url)">`) have been wired up to `getBundle` (for `"css"` and `"js"` respectively) automatically.
* For consistency, you may prefer using the bundle plugin method names everywhere: `<style @raw="getBundle('css')">` and `<script @raw="getBundle('js')">` both work fine.
* Outside of WebC, the Universal Filters `webcGetCss` and `webcGetJs` were removed in Eleventy `v3.0.0-alpha.10` in favor of the `getBundle` Universal Shortcode (`{% getBundle "css" %}` and `{% getBundle "js" %}` respectively).
#### Modify the bundle output
You can wire up your own async-friendly callbacks to transform the bundle output too. Heres a quick example of [`postcss` integration](https://github.com/postcss/postcss#js-api).
```js
const postcss = require("postcss");
const postcssNested = require("postcss-nested");
export default function(eleventyConfig) {
eleventyConfig.addBundle("css", {
transforms: [
async function(content) {
// this.type returns the bundle name.
// Same as Eleventy transforms, this.page is available here.
let result = await postcss([postcssNested]).process(content, { from: this.page.inputPath, to: null });
return result.css;
}
]
});
};
```
## Advanced
### Limitations
Bundles do not support nesting or recursion (yet?). If this will be useful to you, please file an issue!
<!--
Version Two:
* Think about Eleventy transform order, scenarios where this transform needs to run first.
* JavaScript API independent of eleventy
* Clean up the _site/bundle folder on exit?
* Example ideas:
* App bundle and page bundle
* can we make this work for syntax highlighting? or just defer to WebC for this?
{% css %}
<style>
em { font-style: italic; }
</style>
{% endcss %}
* a way to declare dependencies? or just defer to buckets here
* What if we want to add code duplicates? Adding `alert(1);` `alert(1);` to alert twice?
* sourcemaps (maybe via magic-string module or https://www.npmjs.com/package/concat-with-sourcemaps)
-->

View File

@ -0,0 +1,66 @@
import { createRequire } from "node:module";
import bundleManagersPlugin from "./src/eleventy.bundleManagers.js";
import pruneEmptyBundlesPlugin from "./src/eleventy.pruneEmptyBundles.js";
import shortcodesPlugin from "./src/eleventy.shortcodes.js";
import debugUtil from "debug";
const require = createRequire(import.meta.url);
const debug = debugUtil("Eleventy:Bundle");
const pkg = require("./package.json");
function normalizeOptions(options = {}) {
options = Object.assign({
// Plugin defaults
bundles: [], // extra bundles: css, js, and html are guaranteed unless `bundles: false`
toFileDirectory: "bundle",
// post-process
transforms: [],
hoistDuplicateBundlesFor: [],
bundleExportKey: "bundle", // use a `bundle` export in a 11ty.js template to populate bundles
}, options);
if(options.bundles !== false) {
options.bundles = Array.from(new Set(["css", "js", "html", ...(options.bundles || [])]));
}
return options;
}
function eleventyBundlePlugin(eleventyConfig, pluginOptions = {}) {
eleventyConfig.versionCheck(pkg["11ty"].compatibility);
pluginOptions = normalizeOptions(pluginOptions);
if(!("getBundleManagers" in eleventyConfig) && !("addBundle" in eleventyConfig)) {
bundleManagersPlugin(eleventyConfig, pluginOptions);
}
pruneEmptyBundlesPlugin(eleventyConfig, pluginOptions);
// should this be unique too?
shortcodesPlugin(eleventyConfig, pluginOptions);
if(Array.isArray(pluginOptions.bundles)) {
debug("Adding bundles via `addPlugin`: %o", pluginOptions.bundles)
pluginOptions.bundles.forEach(name => {
let isHoisting = Array.isArray(pluginOptions.hoistDuplicateBundlesFor) && pluginOptions.hoistDuplicateBundlesFor.includes(name);
eleventyConfig.addBundle(name, {
hoist: isHoisting,
outputFileExtension: name, // default as `name`
shortcodeName: name, // `false` will skip shortcode
transforms: pluginOptions.transforms,
toFileDirectory: pluginOptions.toFileDirectory,
bundleExportKey: pluginOptions.bundleExportKey, // `false` will skip bundle export
});
});
}
};
// This is used to find the package name for this plugin (used in eleventy-plugin-webc to prevent dupes)
Object.defineProperty(eleventyBundlePlugin, "eleventyPackage", {
value: pkg.name
});
export default eleventyBundlePlugin;
export { normalizeOptions };

62
node_modules/@11ty/eleventy-plugin-bundle/package.json generated vendored Normal file
View File

@ -0,0 +1,62 @@
{
"name": "@11ty/eleventy-plugin-bundle",
"version": "3.0.0",
"description": "Little bundles of code, little bundles of joy.",
"main": "eleventy.bundle.js",
"type": "module",
"scripts": {
"sample": "DEBUG=Eleventy:Bundle npx @11ty/eleventy --config=sample/sample-config.js --input=sample --serve",
"test": "npx ava"
},
"publishConfig": {
"access": "public"
},
"license": "MIT",
"engines": {
"node": ">=18"
},
"11ty": {
"compatibility": ">=3.0.0-alpha"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/11ty"
},
"keywords": [
"eleventy",
"eleventy-plugin"
],
"repository": {
"type": "git",
"url": "git://github.com/11ty/eleventy-plugin-bundle.git"
},
"bugs": "https://github.com/11ty/eleventy-plugin-bundle/issues",
"homepage": "https://www.11ty.dev/",
"author": {
"name": "Zach Leatherman",
"email": "zachleatherman@gmail.com",
"url": "https://zachleat.com/"
},
"ava": {
"failFast": true,
"files": [
"test/*.js",
"test/*.mjs"
],
"ignoredByWatcher": [
"**/_site/**",
".cache"
]
},
"devDependencies": {
"@11ty/eleventy": "3.0.0-alpha.20",
"ava": "^5.3.1",
"postcss": "^8.4.31",
"postcss-nested": "^6.0.1",
"sass": "^1.69.5"
},
"dependencies": {
"debug": "^4.3.4",
"posthtml-match-helper": "^2.0.2"
}
}

View File

@ -0,0 +1,76 @@
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import debugUtil from "debug";
const debug = debugUtil("Eleventy:Bundle");
const hashCache = {};
const directoryExistsCache = {};
const writingCache = new Set();
class BundleFileOutput {
constructor(outputDirectory, bundleDirectory) {
this.outputDirectory = outputDirectory;
this.bundleDirectory = bundleDirectory || "";
this.hashLength = 10;
this.fileExtension = undefined;
}
setFileExtension(ext) {
this.fileExtension = ext;
}
getFilenameHash(content) {
if(hashCache[content]) {
return hashCache[content];
}
let hash = createHash("sha256");
hash.update(content);
let base64hash = hash.digest('base64').replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
let filenameHash = base64hash.substring(0, this.hashLength);
hashCache[content] = filenameHash;
return filenameHash;
}
getFilename(filename, extension) {
return filename + (extension && !extension.startsWith(".") ? `.${extension}` : "");
}
modifyPathToUrl(dir, filename) {
return "/" + path.join(dir, filename).split(path.sep).join("/");
}
writeBundle(content, type, writeToFileSystem) {
// do not write a bundle, do not return a file name is content is empty
if(!content) {
return;
}
let dir = path.join(this.outputDirectory, this.bundleDirectory);
let filenameHash = this.getFilenameHash(content);
let filename = this.getFilename(filenameHash, this.fileExtension || type);
if(writeToFileSystem) {
let fullPath = path.join(dir, filename);
// no duplicate writes, this may be improved with a fs exists check, but it would only save the first write
if(!writingCache.has(fullPath)) {
writingCache.add(fullPath);
if(!directoryExistsCache[dir]) {
fs.mkdirSync(dir, { recursive: true });
directoryExistsCache[dir] = true;
}
debug("Writing bundle %o", fullPath);
fs.writeFileSync(fullPath, content);
}
}
return this.modifyPathToUrl(this.bundleDirectory, filename);
}
}
export { BundleFileOutput };

Some files were not shown because too many files have changed in this diff Show More