diff options
Diffstat (limited to 'node_modules/@11ty/eleventy-plugin-bundle')
10 files changed, 1277 insertions, 0 deletions
diff --git a/node_modules/@11ty/eleventy-plugin-bundle/README.md b/node_modules/@11ty/eleventy-plugin-bundle/README.md new file mode 100644 index 0000000..a585831 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/README.md @@ -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 you’d 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, they’ll 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. + +Here’s 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 you’d 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 you’d 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. Here’s 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) +-->
\ No newline at end of file diff --git a/node_modules/@11ty/eleventy-plugin-bundle/eleventy.bundle.js b/node_modules/@11ty/eleventy-plugin-bundle/eleventy.bundle.js new file mode 100644 index 0000000..35f571c --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/eleventy.bundle.js @@ -0,0 +1,72 @@ +import bundleManagersPlugin from "./src/eleventy.bundleManagers.js"; +import pruneEmptyBundlesPlugin from "./src/eleventy.pruneEmptyBundles.js"; +import globalShortcodesAndTransforms from "./src/eleventy.shortcodes.js"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +function normalizeOptions(options = {}) { + options = Object.assign({ + // Plugin defaults + + // Extra bundles + // css, js, and html are guaranteed unless `bundles: false` + bundles: [], + toFileDirectory: "bundle", + // post-process + transforms: [], + hoistDuplicateBundlesFor: [], + bundleExportKey: "bundle", // use a `bundle` export in a 11ty.js template to populate bundles + + force: false, // force overwrite of existing getBundleManagers and addBundle configuration API methods + }, options); + + if(options.bundles !== false) { + options.bundles = Array.from(new Set(["css", "js", "html", ...(options.bundles || [])])); + } + + return options; +} + +function eleventyBundlePlugin(eleventyConfig, pluginOptions = {}) { + eleventyConfig.versionCheck(">=3.0.0"); + pluginOptions = normalizeOptions(pluginOptions); + + let alreadyAdded = "getBundleManagers" in eleventyConfig || "addBundle" in eleventyConfig; + if(!alreadyAdded || pluginOptions.force) { + if(alreadyAdded && pluginOptions.force) { + debug("Bundle plugin already added via `addPlugin`, add was forced via `force: true`"); + } + + bundleManagersPlugin(eleventyConfig, pluginOptions); + } + + // These can’t be unique (don’t skip re-add above), when the configuration file resets they need to be added again + pruneEmptyBundlesPlugin(eleventyConfig, pluginOptions); + globalShortcodesAndTransforms(eleventyConfig, pluginOptions); + + // Support subsequent calls like addPlugin(BundlePlugin, { bundles: [] }); + 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: "@11ty/eleventy-plugin-bundle" +}); + +export default eleventyBundlePlugin; +export { normalizeOptions }; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/package.json b/node_modules/@11ty/eleventy-plugin-bundle/package.json new file mode 100644 index 0000000..21c8405 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/package.json @@ -0,0 +1,62 @@ +{ + "name": "@11ty/eleventy-plugin-bundle", + "version": "3.0.7", + "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" + }, + "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" + ], + "watchMode": { + "ignoreChanges": [ + "**/_site/**", + ".cache" + ] + } + }, + "devDependencies": { + "@11ty/eleventy": "^3.0.0", + "ava": "^6.2.0", + "postcss": "^8.5.3", + "postcss-nested": "^7.0.2", + "sass": "^1.86.3" + }, + "dependencies": { + "@11ty/eleventy-utils": "^2.0.2", + "debug": "^4.4.0", + "posthtml-match-helper": "^2.0.3" + } +} diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/BundleFileOutput.js b/node_modules/@11ty/eleventy-plugin-bundle/src/BundleFileOutput.js new file mode 100644 index 0000000..332c5b7 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/BundleFileOutput.js @@ -0,0 +1,75 @@ +import fs from "node:fs"; +import path from "node:path"; +import debugUtil from "debug"; + +import { createHash } from "@11ty/eleventy-utils"; + +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; + } + + async getFilenameHash(content) { + if(hashCache[content]) { + return hashCache[content]; + } + + let base64hash = await createHash(content); + 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("/"); + } + + async 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 = await 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 }; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/CodeManager.js b/node_modules/@11ty/eleventy-plugin-bundle/src/CodeManager.js new file mode 100644 index 0000000..809c242 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/CodeManager.js @@ -0,0 +1,231 @@ +import { BundleFileOutput } from "./BundleFileOutput.js"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); +const DEBUG_LOG_TRUNCATION_SIZE = 200; + +class CodeManager { + // code is placed in this bucket by default + static DEFAULT_BUCKET_NAME = "default"; + + // code is hoisted to this bucket when necessary + static HOISTED_BUCKET_NAME = "default"; + + constructor(name) { + this.name = name; + this.trimOnAdd = true; + // TODO unindent on add + this.reset(); + this.transforms = []; + this.isHoisting = true; + this.fileExtension = undefined; + this.toFileDirectory = undefined; + this.bundleExportKey = "bundle"; + this.runsAfterHtmlTransformer = false; + this.pluckedSelector = undefined; + } + + setDelayed(isDelayed) { + this.runsAfterHtmlTransformer = Boolean(isDelayed); + } + + isDelayed() { + return this.runsAfterHtmlTransformer; + } + + // posthtml-match-selector friendly + setPluckedSelector(selector) { + this.pluckedSelector = selector; + } + + getPluckedSelector() { + return this.pluckedSelector; + } + + setFileExtension(ext) { + this.fileExtension = ext; + } + + setHoisting(enabled) { + this.isHoisting = !!enabled; + } + + setBundleDirectory(dir) { + this.toFileDirectory = dir; + } + + setBundleExportKey(key) { + this.bundleExportKey = key; + } + + getBundleExportKey() { + return this.bundleExportKey; + } + + reset() { + this.pages = {}; + } + + static normalizeBuckets(bucket) { + if(Array.isArray(bucket)) { + return bucket; + } else if(typeof bucket === "string") { + return bucket.split(","); + } + return [CodeManager.DEFAULT_BUCKET_NAME]; + } + + setTransforms(transforms) { + if(!Array.isArray(transforms)) { + throw new Error("Array expected to setTransforms"); + } + + this.transforms = transforms; + } + + _initBucket(pageUrl, bucket) { + if(!this.pages[pageUrl][bucket]) { + this.pages[pageUrl][bucket] = new Set(); + } + } + + addToPage(pageUrl, code = [], bucket) { + if(!Array.isArray(code) && code) { + code = [code]; + } + if(code.length === 0) { + return; + } + + if(!this.pages[pageUrl]) { + this.pages[pageUrl] = {}; + } + + let buckets = CodeManager.normalizeBuckets(bucket); + + let codeContent = code.map(entry => { + if(this.trimOnAdd) { + return entry.trim(); + } + return entry; + }); + + + for(let b of buckets) { + this._initBucket(pageUrl, b); + + for(let content of codeContent) { + if(content) { + if(!this.pages[pageUrl][b].has(content)) { + debug("Adding code to bundle %o for %o (bucket: %o, size: %o): %o", this.name, pageUrl, b, content.length, content.length > DEBUG_LOG_TRUNCATION_SIZE ? content.slice(0, DEBUG_LOG_TRUNCATION_SIZE) + "…" : content); + this.pages[pageUrl][b].add(content); + } + } + } + } + } + + async runTransforms(str, pageData, buckets) { + for (let callback of this.transforms) { + str = await callback.call( + { + page: pageData, + type: this.name, + buckets: buckets + }, + str + ); + } + + return str; + } + + getBucketsForPage(pageData) { + let pageUrl = pageData.url; + if(!this.pages[pageUrl]) { + return []; + } + return Object.keys(this.pages[pageUrl]); + } + + getRawForPage(pageData, buckets = undefined) { + let url = pageData.url; + if(!this.pages[url]) { + debug("No bundle code found for %o on %o, %O", this.name, url, this.pages); + return new Set(); + } + + buckets = CodeManager.normalizeBuckets(buckets); + + let set = new Set(); + let size = 0; + for(let b of buckets) { + if(!this.pages[url][b]) { + // Just continue, if you retrieve code from a bucket that doesn’t exist or has no code, it will return an empty set + continue; + } + + for(let entry of this.pages[url][b]) { + size += entry.length; + set.add(entry); + } + } + + debug("Retrieving %o for %o (buckets: %o, entries: %o, size: %o)", this.name, url, buckets, set.size, size); + return set; + } + + async getForPage(pageData, buckets = undefined) { + let set = this.getRawForPage(pageData, buckets); + let bundleContent = Array.from(set).join("\n"); + + // returns promise + return this.runTransforms(bundleContent, pageData, buckets); + } + + async writeBundle(pageData, buckets, options = {}) { + let url = pageData.url; + if(!this.pages[url]) { + debug("No bundle code found for %o on %o, %O", this.name, url, this.pages); + return ""; + } + + let { output, write } = options; + + buckets = CodeManager.normalizeBuckets(buckets); + + // TODO the bundle output URL might be useful in the transforms for sourcemaps + let content = await this.getForPage(pageData, buckets); + let writer = new BundleFileOutput(output, this.toFileDirectory); + writer.setFileExtension(this.fileExtension); + return writer.writeBundle(content, this.name, write); + } + + // Used when a bucket is output multiple times on a page and needs to be hoisted + hoistBucket(pageData, bucketName) { + let newTargetBucketName = CodeManager.HOISTED_BUCKET_NAME; + if(!this.isHoisting || bucketName === newTargetBucketName) { + return; + } + + let url = pageData.url; + if(!this.pages[url] || !this.pages[url][bucketName]) { + debug("No bundle code found for %o on %o, %O", this.name, url, this.pages); + return; + } + + debug("Code in bucket (%o) is being hoisted to a new bucket (%o)", bucketName, newTargetBucketName); + + this._initBucket(url, newTargetBucketName); + + for(let codeEntry of this.pages[url][bucketName]) { + this.pages[url][bucketName].delete(codeEntry); + this.pages[url][newTargetBucketName].add(codeEntry); + } + + // delete the bucket + delete this.pages[url][bucketName]; + } +} + +export { CodeManager }; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/OutOfOrderRender.js b/node_modules/@11ty/eleventy-plugin-bundle/src/OutOfOrderRender.js new file mode 100644 index 0000000..6cafa49 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/OutOfOrderRender.js @@ -0,0 +1,158 @@ +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +/* This class defers any `bundleGet` calls to a post-build transform step, + * to allow `getBundle` to be called before all of the `css` additions have been processed + */ +class OutOfOrderRender { + static SPLIT_REGEX = /(\/\*__EleventyBundle:[^:]*:[^:]*:[^:]*:EleventyBundle__\*\/)/; + static SEPARATOR = ":"; + + constructor(content) { + this.content = content; + this.managers = {}; + } + + // type if `get` (return string) or `file` (bundle writes to file, returns file url) + static getAssetKey(type, name, bucket) { + if(Array.isArray(bucket)) { + bucket = bucket.join(","); + } else if(typeof bucket === "string") { + } else { + bucket = ""; + } + return `/*__EleventyBundle:${type}:${name}:${bucket || "default"}:EleventyBundle__*/` + } + + static parseAssetKey(str) { + if(str.startsWith("/*__EleventyBundle:")) { + let [prefix, type, name, bucket, suffix] = str.split(OutOfOrderRender.SEPARATOR); + return { type, name, bucket }; + } + return false; + } + + setAssetManager(name, assetManager) { + this.managers[name] = assetManager; + } + + setOutputDirectory(dir) { + this.outputDirectory = dir; + } + + normalizeMatch(match) { + let ret = OutOfOrderRender.parseAssetKey(match) + return ret || match; + } + + findAll() { + let matches = this.content.split(OutOfOrderRender.SPLIT_REGEX); + let ret = []; + for(let match of matches) { + ret.push(this.normalizeMatch(match)); + } + return ret; + } + + setWriteToFileSystem(isWrite) { + this.writeToFileSystem = isWrite; + } + + getAllBucketsForPage(pageData) { + let availableBucketsForPage = new Set(); + for(let name in this.managers) { + for(let bucket of this.managers[name].getBucketsForPage(pageData)) { + availableBucketsForPage.add(`${name}::${bucket}`); + } + } + return availableBucketsForPage; + } + + getManager(name) { + if(!this.managers[name]) { + throw new Error(`No asset manager found for ${name}. Known names: ${Object.keys(this.managers)}`); + } + return this.managers[name]; + } + + async replaceAll(pageData, stage = 0) { + let matches = this.findAll(); + let availableBucketsForPage = this.getAllBucketsForPage(pageData); + let usedBucketsOnPage = new Set(); + let bucketsOutputStringCount = {}; + let bucketsFileCount = {}; + + for(let match of matches) { + if(typeof match === "string") { + continue; + } + + // type is `file` or `get` + let {type, name, bucket} = match; + let key = `${name}::${bucket}`; + if(!usedBucketsOnPage.has(key)) { + usedBucketsOnPage.add(key); + } + + if(type === "get") { + if(!bucketsOutputStringCount[key]) { + bucketsOutputStringCount[key] = 0; + } + bucketsOutputStringCount[key]++; + } else if(type === "file") { + if(!bucketsFileCount[key]) { + bucketsFileCount[key] = 0; + } + bucketsFileCount[key]++; + } + } + + // Hoist code in non-default buckets that are output multiple times + // Only hoist if 2+ `get` OR 1+ `get` and 1+ `file` + for(let bucketInfo in bucketsOutputStringCount) { + let stringOutputCount = bucketsOutputStringCount[bucketInfo]; + if(stringOutputCount > 1 || stringOutputCount === 1 && bucketsFileCount[bucketInfo] > 0) { + let [name, bucketName] = bucketInfo.split("::"); + this.getManager(name).hoistBucket(pageData, bucketName); + } + } + + let content = await Promise.all(matches.map(match => { + if(typeof match === "string") { + return match; + } + + let {type, name, bucket} = match; + let manager = this.getManager(name); + + // Quit early if in stage 0, run delayed replacements if in stage 1+ + if(typeof manager.isDelayed === "function" && manager.isDelayed() && stage === 0) { + return OutOfOrderRender.getAssetKey(type, name, bucket); + } + + if(type === "get") { + // returns promise + return manager.getForPage(pageData, bucket); + } else if(type === "file") { + // returns promise + return manager.writeBundle(pageData, bucket, { + output: this.outputDirectory, + write: this.writeToFileSystem, + }); + } + return ""; + })); + + for(let bucketInfo of availableBucketsForPage) { + if(!usedBucketsOnPage.has(bucketInfo)) { + let [name, bucketName] = bucketInfo.split("::"); + debug(`WARNING! \`${pageData.inputPath}\` has unbundled \`${name}\` assets (in the '${bucketName}' bucket) that were not written to or used on the page. You might want to add a call to \`getBundle('${name}', '${bucketName}')\` to your content! Learn more: https://github.com/11ty/eleventy-plugin-bundle#asset-bucketing`); + } + } + + return content.join(""); + } +} + +export { OutOfOrderRender }; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/bundlePlucker.js b/node_modules/@11ty/eleventy-plugin-bundle/src/bundlePlucker.js new file mode 100644 index 0000000..5dcad46 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/bundlePlucker.js @@ -0,0 +1,69 @@ +import debugUtil from "debug"; +import matchHelper from "posthtml-match-helper"; + +const debug = debugUtil("Eleventy:Bundle"); + +const ATTRS = { + ignore: "eleventy:ignore", + bucket: "eleventy:bucket", +}; + +const POSTHTML_PLUGIN_NAME = "11ty/eleventy/html-bundle-plucker"; + +function hasAttribute(node, name) { + return node?.attrs?.[name] !== undefined; +} + +function addHtmlPlucker(eleventyConfig, bundleManager) { + let matchSelector = bundleManager.getPluckedSelector(); + + if(!matchSelector) { + throw new Error("Internal error: missing plucked selector on bundle manager."); + } + + eleventyConfig.htmlTransformer.addPosthtmlPlugin( + "html", + function (context = {}) { + let pageUrl = context?.url; + if(!pageUrl) { + throw new Error("Internal error: missing `url` property from context."); + } + + return function (tree, ...args) { + tree.match(matchHelper(matchSelector), function (node) { + try { + // ignore + if(hasAttribute(node, ATTRS.ignore)) { + delete node.attrs[ATTRS.ignore]; + return node; + } + + if(Array.isArray(node?.content) && node.content.length > 0) { + // TODO make this better decoupled + if(node?.content.find(entry => entry.includes(`/*__EleventyBundle:`))) { + // preserve {% getBundle %} calls as-is + return node; + } + + let bucketName = node?.attrs?.[ATTRS.bucket]; + bundleManager.addToPage(pageUrl, [ ...node.content ], bucketName); + + return { attrs: [], content: [], tag: false }; + } + } catch(e) { + debug(`Bundle plucker: error adding content to bundle in HTML Assets: %o`, e); + return node; + } + + return node; + }); + }; + }, + { + // pluginOptions + name: POSTHTML_PLUGIN_NAME, + }, + ); +} + +export { addHtmlPlucker }; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.bundleManagers.js b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.bundleManagers.js new file mode 100644 index 0000000..8510abc --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.bundleManagers.js @@ -0,0 +1,85 @@ +import debugUtil from "debug"; +import { CodeManager } from "./CodeManager.js"; +import { addHtmlPlucker } from "./bundlePlucker.js" + +const debug = debugUtil("Eleventy:Bundle"); + +function eleventyBundleManagers(eleventyConfig, pluginOptions = {}) { + if(pluginOptions.force) { + // no errors + } else if(("getBundleManagers" in eleventyConfig || "addBundle" in eleventyConfig)) { + throw new Error("Duplicate addPlugin calls for @11ty/eleventy-plugin-bundle"); + } + + let managers = {}; + + function addBundle(name, bundleOptions = {}) { + if(name in managers) { + // note: shortcode must still be added + debug("Bundle exists %o, skipping.", name); + } else { + debug("Creating new bundle %o", name); + managers[name] = new CodeManager(name); + + if(bundleOptions.delayed !== undefined) { + managers[name].setDelayed(bundleOptions.delayed); + } + + if(bundleOptions.hoist !== undefined) { + managers[name].setHoisting(bundleOptions.hoist); + } + + if(bundleOptions.bundleHtmlContentFromSelector !== undefined) { + managers[name].setPluckedSelector(bundleOptions.bundleHtmlContentFromSelector); + managers[name].setDelayed(true); // must override `delayed` above + + addHtmlPlucker(eleventyConfig, managers[name]); + } + + if(bundleOptions.bundleExportKey !== undefined) { + managers[name].setBundleExportKey(bundleOptions.bundleExportKey); + } + + if(bundleOptions.outputFileExtension) { + managers[name].setFileExtension(bundleOptions.outputFileExtension); + } + + if(bundleOptions.toFileDirectory) { + managers[name].setBundleDirectory(bundleOptions.toFileDirectory); + } + + if(bundleOptions.transforms) { + managers[name].setTransforms(bundleOptions.transforms); + } + } + + // if undefined, defaults to `name` + if(bundleOptions.shortcodeName !== false) { + let shortcodeName = bundleOptions.shortcodeName || name; + + // e.g. `css` shortcode to add code to page bundle + // These shortcode names are not configurable on purpose (for wider plugin compatibility) + eleventyConfig.addPairedShortcode(shortcodeName, function addContent(content, bucket, explicitUrl) { + let url = explicitUrl || this.page?.url; + if(url) { // don’t add if a file doesn’t have an output URL + managers[name].addToPage(url, content, bucket); + } + return ""; + }); + } + }; + + eleventyConfig.addBundle = addBundle; + + eleventyConfig.getBundleManagers = function() { + return managers; + }; + + eleventyConfig.on("eleventy.before", async () => { + for(let key in managers) { + managers[key].reset(); + } + }); +}; + +export default eleventyBundleManagers; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.pruneEmptyBundles.js b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.pruneEmptyBundles.js new file mode 100644 index 0000000..3bcaa72 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.pruneEmptyBundles.js @@ -0,0 +1,105 @@ +import matchHelper from "posthtml-match-helper"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +const ATTRS = { + keep: "eleventy:keep" +}; + +const POSTHTML_PLUGIN_NAME = "11ty/eleventy-bundle/prune-empty"; + +function getTextNodeContent(node) { + if (!node.content) { + return ""; + } + + return node.content + .map((entry) => { + if (typeof entry === "string") { + return entry; + } + if (Array.isArray(entry.content)) { + return getTextNodeContent(entry); + } + return ""; + }) + .join(""); +} + +function eleventyPruneEmptyBundles(eleventyConfig, options = {}) { + // Right now script[src],link[rel="stylesheet"] nodes are removed if the final bundles are empty. + // `false` to disable + options.pruneEmptySelector = options.pruneEmptySelector ?? `style,script,link[rel="stylesheet"]`; + + // Subsequent call can remove a previously added `addPosthtmlPlugin` entry + // htmlTransformer.remove is v3.0.1-alpha.4+ + if(typeof eleventyConfig.htmlTransformer.remove === "function") { + eleventyConfig.htmlTransformer.remove("html", entry => { + if(entry.name === POSTHTML_PLUGIN_NAME) { + return true; + } + + // Temporary workaround for missing `name` property. + let fnStr = entry.fn.toString(); + return !entry.name && fnStr.startsWith("function (pluginOptions = {}) {") && fnStr.includes(`tree.match(matchHelper(options.pruneEmptySelector), function (node)`); + }); + } + + // `false` disables this plugin + if(options.pruneEmptySelector === false) { + return; + } + + if(!eleventyConfig.htmlTransformer || !eleventyConfig.htmlTransformer?.constructor?.SUPPORTS_PLUGINS_ENABLED_CALLBACK) { + debug("You will need to upgrade your version of Eleventy core to remove empty bundle tags automatically (v3 or newer)."); + return; + } + + eleventyConfig.htmlTransformer.addPosthtmlPlugin( + "html", + function bundlePruneEmptyPosthtmlPlugin(pluginOptions = {}) { + return function (tree) { + tree.match(matchHelper(options.pruneEmptySelector), function (node) { + if(node.attrs && node.attrs[ATTRS.keep] !== undefined) { + delete node.attrs[ATTRS.keep]; + return node; + } + + // <link rel="stylesheet" href=""> + if(node.tag === "link") { + if(node.attrs?.rel === "stylesheet" && (node.attrs?.href || "").trim().length === 0) { + return false; + } + } else { + let content = getTextNodeContent(node); + + if(!content) { + // <script></script> or <script src=""></script> + if(node.tag === "script" && (node.attrs?.src || "").trim().length === 0) { + return false; + } + + // <style></style> + if(node.tag === "style") { + return false; + } + } + } + + + return node; + }); + }; + }, + { + name: POSTHTML_PLUGIN_NAME, + // the `enabled` callback for plugins is available on v3.0.0-alpha.20+ and v3.0.0-beta.2+ + enabled: () => { + return Object.keys(eleventyConfig.getBundleManagers()).length > 0; + } + } + ); +} + +export default eleventyPruneEmptyBundles; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.shortcodes.js b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.shortcodes.js new file mode 100644 index 0000000..924731a --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.shortcodes.js @@ -0,0 +1,83 @@ +import { OutOfOrderRender } from "./OutOfOrderRender.js"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +export default function(eleventyConfig, pluginOptions = {}) { + let managers = eleventyConfig.getBundleManagers(); + let writeToFileSystem = true; + + function bundleTransform(content, stage = 0) { + // Only run if content is string + // Only run if managers are in play + if(typeof content !== "string" || Object.keys(managers).length === 0) { + return content; + } + + debug("Processing %o", this.page.url); + let render = new OutOfOrderRender(content); + for(let key in managers) { + render.setAssetManager(key, managers[key]); + } + + render.setOutputDirectory(eleventyConfig.directories.output); + render.setWriteToFileSystem(writeToFileSystem); + + return render.replaceAll(this.page, stage); + } + + eleventyConfig.on("eleventy.before", async ({ outputMode }) => { + if(Object.keys(managers).length === 0) { + return; + } + + if(outputMode !== "fs") { + writeToFileSystem = false; + debug("Skipping writing to the file system due to output mode: %o", outputMode); + } + }); + + // e.g. `getBundle` shortcode to get code in current page bundle + // bucket can be an array + // This shortcode name is not configurable on purpose (for wider plugin compatibility) + eleventyConfig.addShortcode("getBundle", function getContent(type, bucket, explicitUrl) { + if(!type || !(type in managers) || Object.keys(managers).length === 0) { + throw new Error(`Invalid bundle type: ${type}. Available options: ${Object.keys(managers)}`); + } + + return OutOfOrderRender.getAssetKey("get", type, bucket); + }); + + // write a bundle to the file system + // This shortcode name is not configurable on purpose (for wider plugin compatibility) + eleventyConfig.addShortcode("getBundleFileUrl", function(type, bucket, explicitUrl) { + if(!type || !(type in managers) || Object.keys(managers).length === 0) { + throw new Error(`Invalid bundle type: ${type}. Available options: ${Object.keys(managers)}`); + } + + return OutOfOrderRender.getAssetKey("file", type, bucket); + }); + + eleventyConfig.addTransform("@11ty/eleventy-bundle", function (content) { + let hasNonDelayedManagers = Boolean(Object.values(eleventyConfig.getBundleManagers()).find(manager => { + return typeof manager.isDelayed !== "function" || !manager.isDelayed(); + })); + if(hasNonDelayedManagers) { + return bundleTransform.call(this, content, 0); + } + return content; + }); + + eleventyConfig.addPlugin((eleventyConfig) => { + // Delayed bundles *MUST* not alter URLs + eleventyConfig.addTransform("@11ty/eleventy-bundle/delayed", function (content) { + let hasDelayedManagers = Boolean(Object.values(eleventyConfig.getBundleManagers()).find(manager => { + return typeof manager.isDelayed === "function" && manager.isDelayed(); + })); + if(hasDelayedManagers) { + return bundleTransform.call(this, content, 1); + } + return content; + }); + }); +}; |
