cook-ssg 2.1.3 → 2.2.1

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.
Files changed (36) hide show
  1. package/README.md +48 -20
  2. package/package.json +4 -9
  3. package/scripts/build.js +91 -26
  4. package/scripts/dev.js +46 -16
  5. package/scripts/plugins/apply-template.js +8 -17
  6. package/scripts/plugins/auto-components.js +2 -2
  7. package/scripts/plugins/bundle.js +6 -3
  8. package/scripts/plugins/copy-src.js +1 -1
  9. package/scripts/plugins/create-dir-from-file.js +4 -2
  10. package/scripts/plugins/create-dist.js +1 -2
  11. package/scripts/plugins/custom-plugins.js +1 -1
  12. package/scripts/plugins/declarative-shadow-dom.js +2 -2
  13. package/scripts/plugins/escape-code-blocks.js +22 -1
  14. package/scripts/plugins/fingerprint-assets.js +133 -13
  15. package/scripts/plugins/generate-formats.js +49 -39
  16. package/scripts/plugins/generate-fragments.js +24 -14
  17. package/scripts/plugins/generate-sitemap-xml.js +38 -15
  18. package/scripts/plugins/minify-src.js +98 -72
  19. package/scripts/plugins/optimize-images.js +80 -26
  20. package/scripts/plugins/process-markdown.js +12 -25
  21. package/scripts/plugins/repeat-collection.js +70 -45
  22. package/scripts/plugins/replace-components.js +82 -60
  23. package/scripts/plugins/replace-external-link-protocol.js +16 -31
  24. package/scripts/plugins/replace-include.js +34 -19
  25. package/scripts/plugins/replace-inline.js +6 -3
  26. package/scripts/plugins/replace-template-strings.js +2 -50
  27. package/scripts/plugins/set-active-links.js +57 -26
  28. package/scripts/utils/config/config.js +29 -5
  29. package/scripts/utils/get-src/get-src.js +9 -45
  30. package/scripts/utils/interpolate/interpolate.js +83 -0
  31. package/scripts/utils/logger/logger.js +8 -3
  32. package/scripts/utils/site-pages/site-pages.js +37 -0
  33. package/scripts/utils/source-file/source-file.js +64 -0
  34. package/scripts/utils/user-data/user-data.js +45 -0
  35. package/scripts/utils/util/util.js +88 -46
  36. package/patches/jsdom-fetch-fix.js +0 -52
@@ -6,6 +6,7 @@
6
6
  // IMPORT
7
7
  // -----------------------------
8
8
  import utils from '../utils/util/util.js';
9
+ import { renderTemplate } from '../utils/interpolate/interpolate.js';
9
10
 
10
11
 
11
12
  // DEFINE
@@ -38,25 +39,6 @@ class ReplaceTemplateStrings {
38
39
  // REPLACE STRING VARIABLES WITH MATCHING DATA
39
40
  // Find all template string variables, and replace them with their matching data value from `/config/data.js`
40
41
 
41
- // NOTE: Why do we use `obj[`${src[offset+2]}${g}`]` instead of `obj[g]`?
42
- // ---
43
- // Normally, if you use a regex to find all `${...}` in the src (`/\${(.*)}/g`), the 'g' property in the `.replace()` method will be that match.
44
- // However, this will find these cases as well: `${{...}}`, which is the literal $ and then a Vue-style variable.
45
- // So instead of leaving `${{...}}` in the DOM (so that Vue can replace on the client during page render),
46
- // it would try and replace with a looked up value, not find one, and write an empty string instead,
47
- // So you would get `}` written to the screen instead of `${{...}}` since it would match `${{...}`
48
- // Therefore, we needed to add a negation to the regex, namely `[^{]`, which excludes matches with 2x { after a $.
49
- // So now `${...}` matches, but `${{...}}` doesn't. Great!
50
- // Unfortunately, the native string's `.replace()` method separates capture groups from the pattern match :(
51
- // (You can read about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter)
52
- // So inside the replace's 2nd-parameter function, `g` would be the matched variable template, but missing the first character after the first `{`.
53
- // For example, if the matched variable was `${matchedVar}` (which is the `match` argument), then `g` will be `atchedVar` instead of `matchedVar`.
54
- // So when you do a look up to the data object, no matched value will be returned.
55
- // Therefore, we need to add that missing character back.
56
- // Fortunately, the `.replace()` method provides the index offset where the match occurred, and the full source string.
57
- // So we find the missing character by adjusting the offset by 2 (`offset+2`)
58
- // and then applying it back to `g` to get the correct variable lookup (why 2? Because we need to go past the starting `${`)
59
- // ---
60
42
  // Protect the CONTENT of <script> and <style> blocks from template resolution.
61
43
  // JavaScript template literals like `${name}` and CSS custom properties
62
44
  // should not be replaced with data values. But we still need to resolve
@@ -69,7 +51,7 @@ class ReplaceTemplateStrings {
69
51
  return `${openTag}<!--COOK_PROTECTED_${index}-->${closeTag}`;
70
52
  });
71
53
 
72
- src = this.replaceTemplateVars(src, this.data);
54
+ src = renderTemplate(src, this.data);
73
55
 
74
56
  // Restore protected content
75
57
  this.file.src = src.replace(/<!--COOK_PROTECTED_(\d+)-->/g, (_, i) => protectedContent[i]);
@@ -78,36 +60,6 @@ class ReplaceTemplateStrings {
78
60
  // HELPER METHODS
79
61
  // -----------------------------
80
62
 
81
- /**
82
- * @description Replace ${var} and ${nested.var} template strings with data values
83
- * @param {string} str - Source string
84
- * @param {Object} obj - Data object to resolve variables from
85
- */
86
- replaceTemplateVars(str, obj) {
87
- return str.replace(/\${[^{](.*?)}/g, (match, g, offset, src) => {
88
- // Reconstruct the full key (see long comment above for why offset+2)
89
- const key = `${src[offset + 2]}${g}`;
90
-
91
- // 1. Flat lookup (most common, fast path)
92
- if (obj[key] != null) return String(obj[key]);
93
-
94
- // 2. Dot notation lookup (e.g., "site.css" → obj.site.css)
95
- if (key.includes('.')) {
96
- const parts = key.split('.');
97
- let value = obj;
98
- for (const part of parts) {
99
- if (value == null || typeof value !== 'object') { value = undefined; break; }
100
- value = value[part];
101
- }
102
- if (value != null) return String(value);
103
- }
104
-
105
- // 3. No match — leave the template string as-is
106
- return match;
107
- });
108
- }
109
-
110
-
111
63
  // EXPORT WRAPPER
112
64
  // -----------------------------
113
65
  // Export function wrapper instead of class for `build.js` simplicity
@@ -51,7 +51,7 @@ class SetActiveLinks {
51
51
  const { file } = this;
52
52
 
53
53
  // Make source traversable with JSDOM
54
- let dom = Util.jsdom.dom({src: file.src});
54
+ const dom = Util.fileDom(file);
55
55
 
56
56
  // Find <a> tags and add active state
57
57
  // if their [href] matches the current page url
@@ -60,7 +60,7 @@ class SetActiveLinks {
60
60
  $links.forEach((link,i) => this.setActive({file, link}));
61
61
 
62
62
  // Store updated file source
63
- file.src = Util.setSrc({dom});
63
+ Util.commitDom(file, dom);
64
64
 
65
65
  // END LOGGING
66
66
  this.endLog();
@@ -77,11 +77,61 @@ class SetActiveLinks {
77
77
  * @private
78
78
  */
79
79
  setActive({file, link}) {
80
- const currPath = Util.getFileName(file.path, distPath);
81
- const linkPath = Util.getFileName(link.href, distPath);
82
- const isParent = this.linkIsParent(file.path, linkPath);
83
- if (linkPath === currPath) this.setActiveLink(link);
84
- else if (isParent) this.setParentActiveLink(link);
80
+ // Compare full normalized URL paths — the old last-segment comparison
81
+ // marked /company/about/ active on /legal/about/ and even matched
82
+ // external links whose URL ended in the same segment.
83
+ const pageUrl = this.normalizePagePath(file.path);
84
+ const linkUrl = this.normalizeHref(link.getAttribute('href'));
85
+ if (linkUrl === null) return;
86
+ if (linkUrl === pageUrl) this.setActiveLink(link);
87
+ // Parent-active: the link is a proper ancestor path of the page.
88
+ // Root ('/') is an ancestor of everything — never parent-active.
89
+ else if (linkUrl !== '/' && pageUrl.startsWith(linkUrl)) this.setParentActiveLink(link);
90
+ }
91
+
92
+ /**
93
+ * @description Normalize the built page's file path to its URL path
94
+ * @example dist/legal/about/index.html → /legal/about/
95
+ * @example dist/404.html → /404/
96
+ * @param {String} pagePath
97
+ * @returns {String}
98
+ * @private
99
+ */
100
+ normalizePagePath(pagePath) {
101
+ let p = pagePath.startsWith(`${distPath}/`)
102
+ ? pagePath.slice(distPath.length)
103
+ : (pagePath.startsWith('/') ? pagePath : `/${pagePath}`);
104
+ return this.normalizeUrlPath(p);
105
+ }
106
+
107
+ /**
108
+ * @description Normalize an internal href to a comparable URL path.
109
+ * Returns null for links that can never be "the current page":
110
+ * external URLs, protocol-relative, anchors, non-root-relative paths.
111
+ * @param {String} href
112
+ * @returns {String|null}
113
+ * @private
114
+ */
115
+ normalizeHref(href) {
116
+ if (!href) return null;
117
+ if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//') || href.startsWith('#')) return null;
118
+ const p = href.split(/[?#]/)[0];
119
+ if (!p.startsWith('/')) return null;
120
+ return this.normalizeUrlPath(p);
121
+ }
122
+
123
+ /**
124
+ * @description Shared URL-path normalization: index.html and .html
125
+ * suffixes collapse to directory style with a trailing slash
126
+ * @param {String} p
127
+ * @returns {String}
128
+ * @private
129
+ */
130
+ normalizeUrlPath(p) {
131
+ if (p.endsWith('/index.html')) p = p.slice(0, -'index.html'.length);
132
+ else if (p.endsWith('.html')) p = `${p.slice(0, -'.html'.length)}/`;
133
+ else if (!p.endsWith('/') && !p.split('/').pop().includes('.')) p = `${p}/`;
134
+ return p;
85
135
  }
86
136
 
87
137
  /**
@@ -116,25 +166,6 @@ class SetActiveLinks {
116
166
  this.total.activeParent += 1;
117
167
  }
118
168
 
119
- /**
120
- * @description Return true if `<a>` link's `[href]` target is a parent of the current page
121
- * @param {String} pagePath - The full path of the current page being evaluated
122
- * @param {String} linkPath - The current page `<a>` to evaluate
123
- * @private
124
- */
125
- linkIsParent(pagePath, linkPath) {
126
- const pagePathSplit = pagePath.split(`${distPath}/`)[1];
127
- // Early Exit: No dist path
128
- if (!pagePathSplit) return;
129
- const pagePathParts = pagePathSplit.split('/');
130
- const pagePathPartsLast = pagePathParts.pop();
131
- // Return true if `linkPath` is one of the parts AND it is not the last part (we'll mark it as normal-active instead)
132
- const isActivePage = linkPath === pagePathParts[pagePathParts.length - 1];
133
- const isHierarchyPage = pagePathParts.indexOf(linkPath) > -1;
134
- return !isActivePage && isHierarchyPage;
135
- }
136
-
137
-
138
169
  // LOGGING
139
170
  // -----------------------------
140
171
  // Display additional terminal logging when `process.env.LOGGER` enabled
@@ -1,7 +1,6 @@
1
1
  // IMPORTS
2
2
  // ----------------------------------
3
3
  import fs from 'node:fs';
4
- import merge from 'lodash.merge';
5
4
  import { pathToFileURL } from 'node:url';
6
5
 
7
6
  const cwd = process.cwd();
@@ -251,10 +250,35 @@ const defaultConfig = {
251
250
 
252
251
  // COMBINE CONFIGS
253
252
  // -----------------------------
254
- // NOTE: Using Lodash `merge` instead of `Object.assign` because,
255
- // there will be child objects and arrays, which would override
256
- // instead of combine with the default versions.
257
- const config = merge({}, defaultConfig, userConfig);
253
+
254
+ /**
255
+ * Deep-merge user config over defaults.
256
+ * - Plain objects merge recursively (untouched default keys survive)
257
+ * - Arrays REPLACE the default wholesale — the user's list is exactly
258
+ * what they wrote. (lodash.merge blended arrays index-by-index:
259
+ * `formats: ['webp']` became ['webp','webp'], user excludePaths
260
+ * silently deleted defaults, and arrays could never shrink.)
261
+ * - Everything else (scalars, RegExp, Date, functions) is assigned
262
+ * @param {Object} target - Mutated and returned
263
+ * @param {Object} source - User overrides
264
+ * @returns {Object}
265
+ */
266
+ export function mergeConfigs(target, source) {
267
+ for (const key of Object.keys(source)) {
268
+ const sourceVal = source[key];
269
+ const targetVal = target[key];
270
+ const isPlainObject = (v) => v !== null && typeof v === 'object'
271
+ && !Array.isArray(v) && !(v instanceof RegExp) && !(v instanceof Date);
272
+ if (isPlainObject(sourceVal) && isPlainObject(targetVal)) {
273
+ mergeConfigs(targetVal, sourceVal);
274
+ } else {
275
+ target[key] = sourceVal;
276
+ }
277
+ }
278
+ return target;
279
+ }
280
+
281
+ const config = mergeConfigs(defaultConfig, userConfig);
258
282
 
259
283
 
260
284
 
@@ -6,25 +6,18 @@
6
6
  // IMPORTS
7
7
  // -----------------------------
8
8
  import fs from 'node:fs/promises';
9
- import { pathToFileURL } from 'node:url';
10
- import { existsSync } from 'node:fs';
11
9
  import Logger from '../logger/logger.js';
12
10
  import Util from '../util/util.js';
11
+ import { SourceFile } from '../source-file/source-file.js';
13
12
 
14
13
  // CONFIG
15
14
  import { includePaths, excludePaths, distPath, srcPath } from '../config/config.js';
16
15
 
17
- const cwd = process.cwd();
18
-
19
16
  // DATA STORE
20
- const userDataPath = `${cwd}/config/data.js`;
21
- const userDataPathExists = existsSync(userDataPath);
22
- let data = {};
23
- if (userDataPathExists) {
24
- const dataModule = await import(pathToFileURL(userDataPath));
25
- const exported = dataModule.default || dataModule;
26
- data = typeof exported === 'function' ? await exported() : exported;
27
- }
17
+ // Shared singleton — the SAME instance build.js passes to plugins, so
18
+ // dynamic pages they add are visible here (a second independent load
19
+ // would silently drop them when data.js exports a function)
20
+ import data from '../user-data/user-data.js';
28
21
 
29
22
 
30
23
  // EXPORT
@@ -67,8 +60,6 @@ function getDynamicFiles(files) {
67
60
  async function getSrcConfig({fileName, excludeSrc = false }) {
68
61
  // Early Exit: No file name given
69
62
  if (!fileName) return;
70
- // Init obj
71
- let file = {};
72
63
 
73
64
  // Store if it is a dynamic page
74
65
  const isDynamic = typeof fileName !== 'string';
@@ -88,13 +79,10 @@ async function getSrcConfig({fileName, excludeSrc = false }) {
88
79
  }
89
80
 
90
81
 
91
- // Store filename parts
92
- let {ext,name,nameIfIndex} = Util.getFileParts(fileName);
93
- file.ext = ext;
94
- file.name = name;
95
- file.nameIfIndex = nameIfIndex;
96
- file.path = fileName;
97
- if (isDynamic) file.isDynamic = true;
82
+ // Store filename parts on a SourceFile (lazy string/DOM sync — see
83
+ // scripts/utils/source-file/source-file.js)
84
+ const {ext,name,nameIfIndex} = Util.getFileParts(fileName);
85
+ const file = new SourceFile({ path: fileName, ext, name, nameIfIndex, isDynamic });
98
86
 
99
87
  // Early Exit: Return the file meta details but skip the source
100
88
  if (excludeSrc) return file;
@@ -106,11 +94,6 @@ async function getSrcConfig({fileName, excludeSrc = false }) {
106
94
  // Get and read the file to store its page source
107
95
  else file.src = await fs.readFile(fileName, 'utf-8');
108
96
 
109
- // REMOVE COMMENTS
110
- // Sanitize comments that have non-closing html elements in them. JSDOM will try to close it in the DOM
111
- // but since there is no starting tag (it's in the comment) it will break the dom
112
- file.src = removeCommentTags(file.src);
113
-
114
97
  // Return file info
115
98
  return file;
116
99
  }
@@ -187,25 +170,6 @@ async function getSrcImages(cb) {
187
170
  }
188
171
 
189
172
 
190
- // HELPER METHODS
191
- // -----------------------------
192
-
193
- /**
194
- * @description Remove < and > from comments since non-closed tags
195
- * will have the matching end tag added
196
- */
197
- function removeCommentTags(src) {
198
- const commentsRegex = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm;
199
- const matches = src.match(commentsRegex);
200
- if (!matches) return src;
201
- let replaces;
202
- matches.forEach(m => {
203
- replaces = m.replace('<', '').replace('>', '');
204
- src = src.replace(m, replaces);
205
- });
206
- return src;
207
- }
208
-
209
173
  // HELPER METHODS
210
174
  // -----------------------------
211
175
 
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @file interpolate.js
3
+ * @description THE ${var} interpolator — the single implementation
4
+ * behind every plugin that resolves template variables (components,
5
+ * repeats, layouts, page-level template strings).
6
+ *
7
+ * Semantics (identical everywhere):
8
+ * - `${key}` with a trimmed key; `${ key }` works
9
+ * - `${{...}}` (client-side/Vue-style) is never touched
10
+ * - flat lookup first, then dot-path (`${user.name}`)
11
+ * - all insertions go through the replace callback, so `$&`-style
12
+ * patterns in VALUES are inserted literally, and inserted content is
13
+ * never rescanned by the same pass
14
+ * - unmatched placeholders are left as-is for later pipeline stages
15
+ * (opt-in: unmatched `${slot:x}` placeholders are removed)
16
+ * - null/undefined values leave the placeholder; Dates render as
17
+ * toLocaleDateString(); Arrays join with ', '
18
+ */
19
+
20
+ // `(?!\{)` skips `${{...}}` so client-side template syntax survives
21
+ const VAR_PATTERN = /\$\{(?!\{)([^}]+)\}/g;
22
+
23
+ /**
24
+ * Walk a dot-notation path safely.
25
+ * @param {Object} obj
26
+ * @param {string} path - e.g. "user.name"
27
+ * @returns {*} value or undefined
28
+ */
29
+ export function getNested(obj, path) {
30
+ if (!obj || !path) return undefined;
31
+ let current = obj;
32
+ for (const part of path.split('.')) {
33
+ if (current === null || current === undefined || typeof current !== 'object') return undefined;
34
+ current = current[part];
35
+ }
36
+ return current;
37
+ }
38
+
39
+ /**
40
+ * Default value formatting for insertion into HTML.
41
+ * @param {*} value
42
+ * @returns {string}
43
+ */
44
+ export function formatValue(value) {
45
+ if (value instanceof Date) return value.toLocaleDateString();
46
+ if (Array.isArray(value)) return value.join(', ');
47
+ return String(value);
48
+ }
49
+
50
+ /**
51
+ * Render `${var}` placeholders in a template string.
52
+ * @param {string} template
53
+ * @param {Object} data - Lookup source (flat keys, "slot:name" keys, nested objects)
54
+ * @param {Object} [opts]
55
+ * @property {boolean} [opts.removeUnmatchedSlots=false] - Remove `${slot:x}` with no data
56
+ * @property {Function} [opts.fallback] - (key, match) => string for unmatched keys
57
+ * @returns {string}
58
+ */
59
+ export function renderTemplate(template, data, opts = {}) {
60
+ const { removeUnmatchedSlots = false, fallback } = opts;
61
+
62
+ return template.replace(VAR_PATTERN, (match, rawKey) => {
63
+ const key = rawKey.trim();
64
+
65
+ // Flat lookup first (also covers "slot:name" keys)
66
+ let value = data[key];
67
+
68
+ // Dot-path lookup (e.g. user.name)
69
+ if ((value === undefined || value === null) && key.includes('.')) {
70
+ value = getNested(data, key);
71
+ }
72
+
73
+ if (value !== undefined && value !== null) return formatValue(value);
74
+
75
+ // Unfilled slots are structural — remove rather than ship raw
76
+ if (removeUnmatchedSlots && key.startsWith('slot:')) return '';
77
+
78
+ if (fallback) return fallback(key, match);
79
+
80
+ // Leave unmatched placeholders for later pipeline stages
81
+ return match;
82
+ });
83
+ }
@@ -20,10 +20,15 @@ let types = {
20
20
  // Clone types for persistance option
21
21
  const persist = cloneDeep(types);
22
22
 
23
- // DISABLE OUTPUT IF ENV VARIABLE SET
23
+ // DISABLE OUTPUT IF ENV VARIABLE NOT SET
24
24
  // ------------------------------------
25
- // Mute logging if environment var set
26
- if (!process.env.LOGGER) Object.keys(types).forEach(key => types[key] = () => ({}));
25
+ // Mute verbose logging unless LOGGER is set — but errors and warnings
26
+ // must ALWAYS be visible, or real failures pass silently.
27
+ if (!process.env.LOGGER) {
28
+ Object.keys(types).forEach(key => {
29
+ if (key !== 'error' && key !== 'warning') types[key] = () => ({});
30
+ });
31
+ }
27
32
 
28
33
  // 'ALWAYS SHOW' OPTION
29
34
  // ----------------------------------
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @file site-pages.js
3
+ * @description One shared snapshot of the built site's pages for the
4
+ * post-loop plugins. Walks dist ONCE and parses each page ONCE;
5
+ * generate-fragments and generate-formats consume the same parsed
6
+ * documents instead of each re-walking dist and re-parsing every page
7
+ * (previously 2-3 walks and 2-3 parses per page after the file loop).
8
+ *
9
+ * Consumers must treat the doms as READ-ONLY — they are shared.
10
+ */
11
+
12
+ import { promises as fs } from 'node:fs';
13
+ import Util from '../util/util.js';
14
+ import { distPath as defaultDistPath } from '../config/config.js';
15
+
16
+ /**
17
+ * Collect all built index pages with their source and parsed document.
18
+ * @param {string} [distPathArg] - Dist directory (defaults to config)
19
+ * @returns {Promise<Array<{filePath: string, urlPath: string, src: string, dom: Object}>>}
20
+ */
21
+ export async function collectSitePages(distPathArg = defaultDistPath) {
22
+ const htmlFiles = Util.getPaths(distPathArg, distPathArg, []) || [];
23
+ const indexFiles = htmlFiles.filter(
24
+ f => f.endsWith('/index.html') || f === `${distPathArg}/index.html`
25
+ );
26
+
27
+ const pages = [];
28
+ for (const filePath of indexFiles) {
29
+ const src = await fs.readFile(filePath, 'utf-8');
30
+ const dom = Util.jsdom.dom({ src });
31
+ // dist/blog/my-post/index.html → /blog/my-post/
32
+ const relativePath = filePath.replace(distPathArg, '');
33
+ const urlPath = relativePath.replace(/\/index\.html$/, '/').replace(/^$/, '/');
34
+ pages.push({ filePath, urlPath, src, dom });
35
+ }
36
+ return pages;
37
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @file source-file.js
3
+ * @description The per-page file object passed through the plugin
4
+ * pipeline, with a lazily-synchronized string/DOM pair.
5
+ *
6
+ * Contract:
7
+ * - String plugins read/write `file.src` exactly as before.
8
+ * - DOM plugins call `Util.fileDom(file)` for a shared cached document
9
+ * and `Util.commitDom(file, dom)` when they mutate it.
10
+ * - Serialization happens only when `src` is read AFTER a DOM mutation,
11
+ * and parsing only when `dom` is read after a `src` write — so a run
12
+ * of consecutive DOM plugins costs ONE parse and ONE serialize
13
+ * instead of a round trip per plugin.
14
+ */
15
+
16
+ import Util from '../util/util.js';
17
+
18
+ class SourceFile {
19
+ constructor({ path, ext, name, nameIfIndex, isDynamic }) {
20
+ this.path = path;
21
+ this.ext = ext;
22
+ this.name = name;
23
+ this.nameIfIndex = nameIfIndex;
24
+ if (isDynamic) this.isDynamic = true;
25
+
26
+ this._src = '';
27
+ this._dom = null;
28
+ this._domDirty = false;
29
+ }
30
+
31
+ /** The page source string. Reading flushes pending DOM mutations. */
32
+ get src() {
33
+ if (this._dom && this._domDirty) {
34
+ this._src = Util.setSrc({ dom: this._dom });
35
+ this._domDirty = false;
36
+ }
37
+ return this._src;
38
+ }
39
+
40
+ /** Writing the string invalidates any cached document. */
41
+ set src(value) {
42
+ this._src = value;
43
+ this._dom = null;
44
+ this._domDirty = false;
45
+ }
46
+
47
+ /** The parsed document (lazy, cached until src is written). */
48
+ get dom() {
49
+ if (!this._dom) {
50
+ // `this.src` (not _src) so a pending dirty state can never leak —
51
+ // by construction _dom is null here, so no flush occurs
52
+ this._dom = Util.jsdom.dom({ src: this.src });
53
+ this._domDirty = false;
54
+ }
55
+ return this._dom;
56
+ }
57
+
58
+ /** Mark the cached document as mutated; src serializes on next read. */
59
+ markDomDirty() {
60
+ this._domDirty = true;
61
+ }
62
+ }
63
+
64
+ export { SourceFile };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @file user-data.js
3
+ * @description Single shared loader for the user's `config/data.js`.
4
+ *
5
+ * The data config may export a plain object or a (possibly async)
6
+ * function. Every part of the build MUST share one instance: plugins
7
+ * add to it (addDynamicPage, collections) and other stages read from
8
+ * it. Loading it in more than one module and invoking the function
9
+ * export per-importer produced divergent instances — dynamic pages
10
+ * written to one were invisible to the other — and doubled any remote
11
+ * fetch cost.
12
+ */
13
+
14
+ import { existsSync } from 'node:fs';
15
+ import { pathToFileURL } from 'node:url';
16
+
17
+ // Memoized per base directory (process.cwd() in normal builds)
18
+ const cache = new Map();
19
+
20
+ /**
21
+ * Load (once) and return the user's data object for a project directory.
22
+ * @param {string} [baseDir=process.cwd()] - Project root containing config/data.js
23
+ * @returns {Promise<Object>}
24
+ */
25
+ export async function loadUserData(baseDir = process.cwd()) {
26
+ if (cache.has(baseDir)) return cache.get(baseDir);
27
+
28
+ // Store the in-flight promise so concurrent callers share one evaluation
29
+ const promise = (async () => {
30
+ const userDataPath = `${baseDir}/config/data.js`;
31
+ if (!existsSync(userDataPath)) return {};
32
+ const dataModule = await import(pathToFileURL(userDataPath));
33
+ const exported = dataModule.default || dataModule;
34
+ return typeof exported === 'function' ? await exported() : exported;
35
+ })();
36
+
37
+ cache.set(baseDir, promise);
38
+ const data = await promise;
39
+ // Replace the promise with the resolved value for cheap sync-ish reuse
40
+ cache.set(baseDir, data);
41
+ return data;
42
+ }
43
+
44
+ // The shared singleton for the current project
45
+ export default await loadUserData();