cook-ssg 2.2.2 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/package.json +1 -1
- package/scripts/build.js +6 -0
- package/scripts/plugins/apply-base-path.js +201 -0
- package/scripts/utils/config/config.js +9 -0
- package/scripts/utils/util/util.js +8 -1
package/README.md
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
A static site build system with templating, bundling, and optimization features.
|
|
4
4
|
|
|
5
|
-
**
|
|
5
|
+
**Docs:** https://profpowell.github.io/cook/
|
|
6
6
|
**License:** MIT
|
|
7
|
-
**Node.js:** >=
|
|
7
|
+
**Node.js:** >=20.9.0
|
|
8
8
|
|
|
9
9
|
[Getting Started](#getting-started) | [View/Run the site code](#viewrun-the-site-code) | [Environment Flags](#environment-flags) | [Build Process](#build-process) | [NPM Run Scripts](#npm-run-scripts)
|
|
10
10
|
|
|
@@ -159,7 +159,8 @@ The build process performs the following steps, in this order:
|
|
|
159
159
|
10. **Creates `sitemap.xml`** - When `sitemap.url` is set, written to the site root (`/dist`, or `/dist/<siteRoot>`); fragments excluded
|
|
160
160
|
11. **Creates bundled files** - `.css` and `.js` bundles are written
|
|
161
161
|
12. **Fingerprints assets** - Opt-in content-hash filenames with HTML and JS-import rewriting (`fingerprint` config)
|
|
162
|
-
13. **
|
|
162
|
+
13. **Applies `basePath`** - When set, prefixes root-relative URLs in built HTML for sub-path hosting (production only)
|
|
163
|
+
14. **Runs custom-user `after` plugins** - Runs once after file processing
|
|
163
164
|
|
|
164
165
|
A page that fails during the loop is reported (with its path) and skipped; the rest of the site still builds, a failure summary prints at the end, and the process exits non-zero so CI catches it.
|
|
165
166
|
|
|
@@ -199,6 +200,13 @@ export default {
|
|
|
199
200
|
// so active links, the sitemap and formats use /docs/, not /pages/docs/.
|
|
200
201
|
siteRoot: '',
|
|
201
202
|
|
|
203
|
+
// URL path the site is served under (default: '' = domain root).
|
|
204
|
+
// For a GitHub Pages project site at https://user.github.io/repo/ set
|
|
205
|
+
// '/repo': links stay written as '/docs/' and production builds output
|
|
206
|
+
// '/repo/docs/'. `cook dev` ignores it. Include the base path in
|
|
207
|
+
// absolute URLs you set yourself (sitemap.url, data.siteUrl).
|
|
208
|
+
basePath: '',
|
|
209
|
+
|
|
202
210
|
// Sitemap: set url to enable (default: '' = no sitemap.xml)
|
|
203
211
|
sitemap: {
|
|
204
212
|
url: 'https://www.yoursite.com',
|
package/package.json
CHANGED
package/scripts/build.js
CHANGED
|
@@ -10,6 +10,7 @@ import Util, { runFileLoop, updatePage } from './utils/util/util.js';
|
|
|
10
10
|
|
|
11
11
|
// PLUGINS
|
|
12
12
|
// -----------------------------
|
|
13
|
+
import applyBasePath from './plugins/apply-base-path.js';
|
|
13
14
|
import autoComponents from './plugins/auto-components.js';
|
|
14
15
|
import { bundleAdd, bundleBuild } from './plugins/bundle.js';
|
|
15
16
|
import copySrc from './plugins/copy-src.js';
|
|
@@ -224,6 +225,11 @@ class Build {
|
|
|
224
225
|
// user-defined `after` plugins so they see fingerprinted output.
|
|
225
226
|
await fingerprintAssets();
|
|
226
227
|
|
|
228
|
+
// PLUGIN: Prefix root-relative URLs in built HTML with `basePath`
|
|
229
|
+
// (sub-path hosting, e.g. GitHub Pages project sites). Runs after every
|
|
230
|
+
// built-in post-loop plugin so they all work with plain root paths.
|
|
231
|
+
await applyBasePath();
|
|
232
|
+
|
|
227
233
|
// CUSTOM PLUGINS: Run custom user plugins after file loop
|
|
228
234
|
await customPlugins({store, data, plugins: plugins.after, log: 'After' });
|
|
229
235
|
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file apply-base-path.js
|
|
3
|
+
* @description Prefix root-relative URLs in built HTML with `basePath`.
|
|
4
|
+
*
|
|
5
|
+
* For sites served from a sub-path, e.g. a GitHub Pages project site at
|
|
6
|
+
* https://user.github.io/repo/. Authors keep writing root-relative URLs
|
|
7
|
+
* (`/docs/`, `/assets/css/site.css`) as if the site were at "/"; this
|
|
8
|
+
* post-pass rewrites them to `/repo/docs/`, `/repo/assets/css/site.css`.
|
|
9
|
+
*
|
|
10
|
+
* Runs once over the served root after every other built-in post-loop
|
|
11
|
+
* plugin (fragments, formats, sitemap, bundles, fingerprinting), so all of
|
|
12
|
+
* them keep working with plain root-relative paths. Skipped in
|
|
13
|
+
* development so `cook dev` still serves the site at "/".
|
|
14
|
+
*
|
|
15
|
+
* Rewritten:
|
|
16
|
+
* - href, src, action, formaction, poster, data (object) on any element
|
|
17
|
+
* - every candidate in srcset
|
|
18
|
+
* - url(/...) in style attributes and <style> blocks
|
|
19
|
+
* - keys and values of <script type="importmap"> imports and scopes
|
|
20
|
+
* Left alone:
|
|
21
|
+
* - relative, absolute (https:, mailto:, data:...) and protocol-relative (//) URLs
|
|
22
|
+
* - URLs already under basePath (the pass is idempotent)
|
|
23
|
+
* - text content (code samples showing href="/..." stay as written)
|
|
24
|
+
* - CSS/JS files, sitemap.xml, md/, api/ JSON and llms*.txt. Absolute
|
|
25
|
+
* URLs there come from `sitemap.url` / `data.siteUrl`, so include the
|
|
26
|
+
* base path in those values (https://user.github.io/repo).
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
// IMPORTS
|
|
30
|
+
// -----------------------------
|
|
31
|
+
import { promises as fs } from 'node:fs';
|
|
32
|
+
import Logger from '../utils/logger/logger.js';
|
|
33
|
+
import Util from '../utils/util/util.js';
|
|
34
|
+
import { siteRootDir } from '../utils/site-root/site-root.js';
|
|
35
|
+
|
|
36
|
+
// Config
|
|
37
|
+
import { basePath as basePathConfig, distPath, siteRoot } from '../utils/config/config.js';
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
// ============================================================================
|
|
41
|
+
// Pure helpers (exported for unit testing)
|
|
42
|
+
// ============================================================================
|
|
43
|
+
|
|
44
|
+
const URL_ATTRS = ['href', 'src', 'action', 'formaction', 'poster', 'data'];
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Normalize a basePath config value: '' | '/' | 'repo' | '/repo/' → '' | '/repo'
|
|
48
|
+
* @param {string} [basePath]
|
|
49
|
+
* @returns {string}
|
|
50
|
+
*/
|
|
51
|
+
export function normalizeBasePath(basePath) {
|
|
52
|
+
const trimmed = String(basePath || '').trim().replace(/^\/+|\/+$/g, '');
|
|
53
|
+
return trimmed ? `/${trimmed}` : '';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Prefix a single URL when it is root-relative and not already under basePath.
|
|
58
|
+
* @param {string} url
|
|
59
|
+
* @param {string} base - Normalized base ('/repo')
|
|
60
|
+
* @returns {string}
|
|
61
|
+
*/
|
|
62
|
+
export function prefixUrl(url, base) {
|
|
63
|
+
if (!base || typeof url !== 'string') return url;
|
|
64
|
+
// Root-relative only: "/x", not "//cdn", not "x", not "https://"
|
|
65
|
+
if (!url.startsWith('/') || url.startsWith('//')) return url;
|
|
66
|
+
// Already prefixed: "/repo", "/repo/", "/repo/x", "/repo?q", "/repo#h"
|
|
67
|
+
if (url.startsWith(base) && (url.length === base.length || /^[/?#]/.test(url[base.length]))) return url;
|
|
68
|
+
return `${base}${url}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Prefix every candidate URL in a srcset value.
|
|
73
|
+
* @param {string} srcset - e.g. "/a-320.webp 320w, /a-640.webp 640w"
|
|
74
|
+
* @param {string} base
|
|
75
|
+
* @returns {string}
|
|
76
|
+
*/
|
|
77
|
+
export function prefixSrcset(srcset, base) {
|
|
78
|
+
return srcset
|
|
79
|
+
.split(',')
|
|
80
|
+
.map(candidate => candidate.replace(/^(\s*)(\S+)/, (m, ws, url) => `${ws}${prefixUrl(url, base)}`))
|
|
81
|
+
.join(',');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Prefix root-relative url(...) references in CSS text.
|
|
86
|
+
* @param {string} css
|
|
87
|
+
* @param {string} base
|
|
88
|
+
* @returns {string}
|
|
89
|
+
*/
|
|
90
|
+
export function prefixCssUrls(css, base) {
|
|
91
|
+
return css.replace(/url\(\s*(['"]?)(\/[^'")\s]*)\1\s*\)/g,
|
|
92
|
+
(m, quote, url) => `url(${quote}${prefixUrl(url, base)}${quote})`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Prefix an import map's specifier keys and address values.
|
|
97
|
+
* @param {string} json - Import map JSON text
|
|
98
|
+
* @param {string} base
|
|
99
|
+
* @returns {string} Rewritten JSON, or the input unchanged if it does not parse
|
|
100
|
+
*/
|
|
101
|
+
export function prefixImportMap(json, base) {
|
|
102
|
+
let map;
|
|
103
|
+
try { map = JSON.parse(json); } catch { return json; }
|
|
104
|
+
const remap = (obj) => Object.fromEntries(
|
|
105
|
+
Object.entries(obj || {}).map(([k, v]) => [prefixUrl(k, base), prefixUrl(v, base)])
|
|
106
|
+
);
|
|
107
|
+
if (map.imports) map.imports = remap(map.imports);
|
|
108
|
+
if (map.scopes) {
|
|
109
|
+
map.scopes = Object.fromEntries(
|
|
110
|
+
Object.entries(map.scopes).map(([scope, entries]) => [prefixUrl(scope, base), remap(entries)])
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return JSON.stringify(map);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Rewrite root-relative URLs in an HTML document or fragment.
|
|
118
|
+
* @param {string} html
|
|
119
|
+
* @param {string} basePath - Raw or normalized base path
|
|
120
|
+
* @returns {{ html: string, rewrites: number }} Input returned untouched when nothing changed
|
|
121
|
+
*/
|
|
122
|
+
export function rewriteBasePath(html, basePath) {
|
|
123
|
+
const base = normalizeBasePath(basePath);
|
|
124
|
+
if (!base) return { html, rewrites: 0 };
|
|
125
|
+
|
|
126
|
+
const dom = Util.jsdom.dom({ src: html });
|
|
127
|
+
const document = dom.window.document;
|
|
128
|
+
let rewrites = 0;
|
|
129
|
+
|
|
130
|
+
const set = (el, attr, next) => {
|
|
131
|
+
if (next !== el.getAttribute(attr)) {
|
|
132
|
+
el.setAttribute(attr, next);
|
|
133
|
+
rewrites += 1;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
for (const attr of URL_ATTRS) {
|
|
138
|
+
document.querySelectorAll(`[${attr}]`).forEach(el => set(el, attr, prefixUrl(el.getAttribute(attr), base)));
|
|
139
|
+
}
|
|
140
|
+
document.querySelectorAll('[srcset]').forEach(el => set(el, 'srcset', prefixSrcset(el.getAttribute('srcset'), base)));
|
|
141
|
+
document.querySelectorAll('[style]').forEach(el => set(el, 'style', prefixCssUrls(el.getAttribute('style'), base)));
|
|
142
|
+
|
|
143
|
+
document.querySelectorAll('style').forEach(el => {
|
|
144
|
+
const next = prefixCssUrls(el.textContent, base);
|
|
145
|
+
if (next !== el.textContent) { el.textContent = next; rewrites += 1; }
|
|
146
|
+
});
|
|
147
|
+
document.querySelectorAll('script[type="importmap"]').forEach(el => {
|
|
148
|
+
const next = prefixImportMap(el.textContent, base);
|
|
149
|
+
if (next !== el.textContent) { el.textContent = next; rewrites += 1; }
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
if (rewrites === 0) return { html, rewrites: 0 };
|
|
153
|
+
return { html: Util.setSrc({ dom }), rewrites };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
// ============================================================================
|
|
158
|
+
// Plugin
|
|
159
|
+
// ============================================================================
|
|
160
|
+
|
|
161
|
+
class ApplyBasePath {
|
|
162
|
+
constructor(opts = {}) {
|
|
163
|
+
// Optional per-call overrides (used by tests and custom pipelines)
|
|
164
|
+
this.basePath = normalizeBasePath(opts.basePath ?? basePathConfig);
|
|
165
|
+
this.distPath = opts.distPath || distPath;
|
|
166
|
+
this.siteRoot = opts.siteRoot ?? siteRoot;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async init() {
|
|
170
|
+
if (!this.basePath) return;
|
|
171
|
+
// `cook dev` serves dist at "/": prefixed links would 404 locally
|
|
172
|
+
if (process.env.NODE_ENV === 'development') return;
|
|
173
|
+
|
|
174
|
+
Logger.persist.header(`\nApply basePath ${this.basePath}`);
|
|
175
|
+
|
|
176
|
+
const rootDir = siteRootDir(this.distPath, this.siteRoot);
|
|
177
|
+
const htmlFiles = (Util.getPaths(rootDir, rootDir, []) || []).filter(p => p.endsWith('.html'));
|
|
178
|
+
|
|
179
|
+
let files = 0;
|
|
180
|
+
let total = 0;
|
|
181
|
+
for (const htmlPath of htmlFiles) {
|
|
182
|
+
const original = await fs.readFile(htmlPath, 'utf-8');
|
|
183
|
+
const { html, rewrites } = rewriteBasePath(original, this.basePath);
|
|
184
|
+
if (rewrites > 0) {
|
|
185
|
+
await fs.writeFile(htmlPath, html, 'utf-8');
|
|
186
|
+
files += 1;
|
|
187
|
+
total += rewrites;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
Logger.persist.success(`Prefixed ${total} URL(s) in ${files} HTML file(s)`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
// EXPORT WRAPPER
|
|
197
|
+
// -----------------------------
|
|
198
|
+
export default async (opts) => {
|
|
199
|
+
const plugin = new ApplyBasePath(opts);
|
|
200
|
+
await plugin.init();
|
|
201
|
+
};
|
|
@@ -43,6 +43,14 @@ const defaultConfig = {
|
|
|
43
43
|
// `siteRoot: 'pages'`. Active links, the sitemap and the post-build page
|
|
44
44
|
// snapshot then use the URLs visitors actually see (/docs/, not /pages/docs/).
|
|
45
45
|
siteRoot: '',
|
|
46
|
+
// URL path the site is served under ('' = domain root). Set it for
|
|
47
|
+
// sub-path hosting such as a GitHub Pages project site
|
|
48
|
+
// (https://user.github.io/repo/ → `basePath: '/repo'`). Write links as
|
|
49
|
+
// usual ('/docs/'); production builds prefix root-relative URLs in the
|
|
50
|
+
// built HTML ('/repo/docs/'). `cook dev` ignores it and serves at "/".
|
|
51
|
+
// Include the base path in absolute URLs you configure yourself:
|
|
52
|
+
// `sitemap.url` and `data.siteUrl` ('https://user.github.io/repo').
|
|
53
|
+
basePath: '',
|
|
46
54
|
// The URL domain to use for the `sitemap.xml` entries.
|
|
47
55
|
// Set `sitemap.url` to enable: `sitemap.xml` is written to the site root
|
|
48
56
|
// (`distPath`, or `distPath/siteRoot`). Left empty, no sitemap is written.
|
|
@@ -297,6 +305,7 @@ export default config;
|
|
|
297
305
|
export const {
|
|
298
306
|
activeLink,
|
|
299
307
|
autoComponents,
|
|
308
|
+
basePath,
|
|
300
309
|
buildOnlyPaths,
|
|
301
310
|
bundle,
|
|
302
311
|
components,
|
|
@@ -571,9 +571,16 @@ function newDOM({src, options}) {
|
|
|
571
571
|
// We wrap it to provide a compatible interface for existing plugins
|
|
572
572
|
jsdom.parseCount += 1;
|
|
573
573
|
const parsed = parseHTML(src);
|
|
574
|
+
// linkedom always writes <!DOCTYPE html> (uppercase). Keep the doctype the
|
|
575
|
+
// author wrote (e.g. lowercase <!doctype html>, which HTML linters such as
|
|
576
|
+
// html-validate's doctype-style rule require) so output matches source.
|
|
577
|
+
const sourceDoctype = /^\s*(<!doctype\b[^>]*>)/i.exec(src)?.[1];
|
|
574
578
|
return {
|
|
575
579
|
window: { document: parsed.document },
|
|
576
|
-
serialize: () =>
|
|
580
|
+
serialize: () => {
|
|
581
|
+
const out = parsed.document.toString();
|
|
582
|
+
return sourceDoctype ? out.replace(/^<!doctype\b[^>]*>/i, sourceDoctype) : out;
|
|
583
|
+
},
|
|
577
584
|
_document: parsed.document,
|
|
578
585
|
};
|
|
579
586
|
}
|