cook-ssg 2.0.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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +445 -0
  3. package/bin/cook.js +66 -0
  4. package/package.json +75 -0
  5. package/patches/jsdom-fetch-fix.js +52 -0
  6. package/scripts/build.js +212 -0
  7. package/scripts/dev.js +119 -0
  8. package/scripts/plugins/apply-template.js +226 -0
  9. package/scripts/plugins/auto-components.js +215 -0
  10. package/scripts/plugins/bundle.js +338 -0
  11. package/scripts/plugins/copy-src.js +89 -0
  12. package/scripts/plugins/create-dir-from-file.js +144 -0
  13. package/scripts/plugins/create-dist.js +55 -0
  14. package/scripts/plugins/custom-plugins.js +118 -0
  15. package/scripts/plugins/declarative-shadow-dom.js +164 -0
  16. package/scripts/plugins/escape-code-blocks.js +54 -0
  17. package/scripts/plugins/generate-formats.js +361 -0
  18. package/scripts/plugins/generate-fragments.js +126 -0
  19. package/scripts/plugins/generate-sitemap-xml.js +216 -0
  20. package/scripts/plugins/minify-src.js +253 -0
  21. package/scripts/plugins/optimize-images.js +389 -0
  22. package/scripts/plugins/process-html-frontmatter.js +75 -0
  23. package/scripts/plugins/process-markdown.js +384 -0
  24. package/scripts/plugins/repeat-collection.js +296 -0
  25. package/scripts/plugins/replace-components.js +496 -0
  26. package/scripts/plugins/replace-external-link-protocol.js +171 -0
  27. package/scripts/plugins/replace-include.js +273 -0
  28. package/scripts/plugins/replace-inline.js +217 -0
  29. package/scripts/plugins/replace-template-strings.js +121 -0
  30. package/scripts/plugins/set-active-links.js +175 -0
  31. package/scripts/utils/config/config.js +277 -0
  32. package/scripts/utils/get-src/get-src.js +241 -0
  33. package/scripts/utils/logger/logger.js +47 -0
  34. package/scripts/utils/performance/performance.js +35 -0
  35. package/scripts/utils/spinner/spinner.js +112 -0
  36. package/scripts/utils/timer/timer.js +40 -0
  37. package/scripts/utils/util/util.js +719 -0
@@ -0,0 +1,273 @@
1
+ /**
2
+ * @file replace-includes.js
3
+ * @description Replace include markers with corresponding code
4
+ */
5
+
6
+ // IMPORT
7
+ // -----------------------------
8
+ import chalk from 'chalk';
9
+ import { promises as fs } from 'node:fs';
10
+ import path from 'node:path';
11
+ import Util from '../utils/util/util.js';
12
+
13
+ // Config
14
+ import { convertPageToDirectory, distPath, srcPath } from '../utils/config/config.js';
15
+
16
+
17
+ // DEFINE
18
+ // -----------------------------
19
+ /**
20
+ * @description Replace include markers with corresponding code
21
+ * @param {Object} obj - Deconstructed options object
22
+ * @property {Object} obj.file - The current file's info (name, extension, path, src, etc.)
23
+ * @property {Object} obj.store - The build process' own data store object we'll add the cached include-file content to
24
+ * @property {Array} [obj.allowType] - Allowed file types (Opt-in)
25
+ * @property {Array} [obj.disallowType] - Disallowed file types (Opt-out)
26
+ */
27
+ class ReplaceInclude {
28
+ constructor({file, store, allowType, disallowType, excludePaths = [], _depth = 0}) {
29
+ this.opts = {file, allowType, disallowType, excludePaths};
30
+ this.file = file;
31
+ this.store = store;
32
+ this.allowType = allowType;
33
+ this.disallowType = disallowType;
34
+ this.excludePaths = excludePaths;
35
+ this._depth = _depth;
36
+
37
+ // Maximum nesting depth to prevent infinite recursion
38
+ this.MAX_DEPTH = 5;
39
+
40
+ // Store holder for total # of includes
41
+ this.total = 0;
42
+
43
+ // Add object to internal store for holding the cached include content
44
+ if (!this.store.cachedIncludes) this.store.cachedIncludes = {};
45
+
46
+ // Init terminal logging
47
+ if (process.env.LOGGER) Util.initLogging.call(this);
48
+ }
49
+
50
+ // INIT
51
+ // -----------------------------
52
+ // Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js
53
+ async init() {
54
+ // Early Exit: File type not allowed
55
+ const allowed = Util.isAllowedType(this.opts);
56
+ if (!allowed) return;
57
+
58
+ // Store string source as traversable DOM
59
+ let dom = Util.jsdom.dom({src: this.file.src});
60
+ // Allow `[include]` or `[data-include]` by default
61
+ const includeSelector = Util.getSelector(Util.attr.include);
62
+ const includeItems = dom.window.document.querySelectorAll(includeSelector);
63
+ this.total = includeItems.length;
64
+
65
+ // Early Exit: No includes
66
+ if (!includeItems) return;
67
+
68
+ // START LOGGING
69
+ this.startLog();
70
+
71
+ // Loop through each found include call and replace with fetched file source
72
+ for (let item of includeItems) {
73
+ await this.replaceInclude(item);
74
+ }
75
+
76
+ // Store updated file source
77
+ this.file.src = Util.setSrc({dom});
78
+
79
+ // Nested includes: if the injected content contains further includes,
80
+ // resolve them recursively up to MAX_DEPTH to prevent infinite loops.
81
+ if (this._depth < this.MAX_DEPTH) {
82
+ const checkDom = Util.jsdom.dom({src: this.file.src});
83
+ const nestedSelector = Util.getSelector(Util.attr.include);
84
+ const nestedIncludes = checkDom.window.document.querySelectorAll(nestedSelector);
85
+ if (nestedIncludes.length) {
86
+ await new ReplaceInclude({
87
+ file: this.file,
88
+ store: this.store,
89
+ allowType: this.allowType,
90
+ disallowType: this.disallowType,
91
+ excludePaths: this.excludePaths,
92
+ _depth: this._depth + 1,
93
+ }).init();
94
+ }
95
+ }
96
+
97
+ // END LOGGING
98
+ this.endLog();
99
+ }
100
+
101
+
102
+ // REPLACE INDIV. INCLUDE
103
+ // -----------------------------
104
+ /**
105
+ * @description Replace include with corresponding source code
106
+ * @param {Object} el - The current include to replace
107
+ * Caches includes' content that was already fetched, to speed up performance.
108
+ * @private
109
+ */
110
+ async replaceInclude(el) {
111
+ // If attribute found and it has a path
112
+ const hasInclude = this.hasAttribute(el, Util.attr.include);
113
+ if (hasInclude && hasInclude.path && hasInclude.path.length) {
114
+ try {
115
+ // Init vars
116
+ let content;
117
+
118
+ // Get full system path to the include file
119
+ // Read from srcPath since build-only dirs (includes/) may not be in dist
120
+ const includePath = path.resolve(`${srcPath}/${hasInclude.path}`);
121
+
122
+ // CHECK IF CACHED VERSION
123
+ // If this path was already looked up previously, use the stored-in-memory source instead of fetching and reading the file again.
124
+ // NOTE: Include file could be empty, resulting in an empty string (''). Since this is treated as falsey by default,
125
+ // we explicitly check for undefined or null (we need Null Coalescing Operator in Node now, cmon!)
126
+ const cachedTarget = this.store.cachedIncludes[includePath];
127
+ if ([undefined, null].indexOf(cachedTarget) === -1) content = cachedTarget;
128
+
129
+ // OTHERWISE, GET THE INCLUDE FILE'S CONTENT (`fs.readFile`)
130
+ else content = await this.fetchIncludeSrc(includePath);
131
+
132
+ // ADD CONTENT TO DOM
133
+ // Add included content in DOM before placeholder element
134
+ el.insertAdjacentHTML('afterend', content);
135
+ // Add any attributes that were on the include element to the first replaced DOM element (that is valid)
136
+ // A 'valid' element is a non- style/script/template etc. element. See the check in the method for the full list
137
+ // NOTE: If an include has multiple 'top-level' elements, they will be applied to the first one
138
+ this.addAttributesToReplacedDOM(el);
139
+ // Remove placeholder element from DOM (`<div include="/includes/xxxx"></div>`)
140
+ el.remove();
141
+ }
142
+ catch (err) {
143
+ Util.customError(err, `replace-includes.js`);
144
+ }
145
+ }
146
+ }
147
+
148
+
149
+ // PROCESS METHODS
150
+ // -----------------------------
151
+
152
+ /**
153
+ * @description Lookup the include file, by path, and get its source content.
154
+ * @param
155
+ * @returns {String}
156
+ * @private
157
+ */
158
+ async fetchIncludeSrc(path) {
159
+ // Store raw path
160
+ let formattedIncludePath = path;
161
+ // Format the path before doing a file lookup, in case the user added a malformed path
162
+ const hasExtension = !!path.match(/.html/g);
163
+ // Include files are read from src/ where they are in their original form
164
+ // (not directory-converted), so just add .html if missing
165
+ if (!hasExtension) formattedIncludePath = `${path}.html`;
166
+ // Get and return content of target include file
167
+ try {
168
+ // Get source from file
169
+ const fetchedSrc = await fs.readFile(formattedIncludePath, 'utf-8');
170
+ // Add entry to cached object store
171
+ this.store.cachedIncludes[path] = fetchedSrc;
172
+ // Return source
173
+ return fetchedSrc;
174
+ }
175
+ catch (err) {
176
+ Util.customKill(`fetchInlineSrc(): ${err}`);
177
+ }
178
+ }
179
+
180
+
181
+ // HELPER METHODS
182
+ // -----------------------------
183
+
184
+ /**
185
+ * @description If the include element had other attributes added, apply them to the first replaced, valid element found.
186
+ * @example The replaced source has a `<style>` tag followed by 2 sibling `<div>` tags. We add the attributes to the first `<div>`
187
+ * @param {Object} el - The `[data-include]` or `[include]` element that is replaced
188
+ * @private
189
+ */
190
+ addAttributesToReplacedDOM(el) {
191
+ const targetEl = this.getValidNextElement(el);
192
+ // Early Exit: No valid element found
193
+ if (!targetEl) return;
194
+ // Loop through each attribute on the include element
195
+ for (let i=0; i<el.attributes.length; i++) {
196
+ const name = el.attributes[i].name;
197
+ const value = el.attributes[i].value;
198
+ const isValidAttr = Util.attr.include.indexOf(name) === -1;
199
+ if (isValidAttr) targetEl.setAttribute(name, value);
200
+ }
201
+ }
202
+
203
+ /**
204
+ * @description Get the next valid element sibling (excludes style/script/etc. elements)
205
+ * @param {Object} el - The `[data-include]` or `[include]` element that is replaced
206
+ * @private
207
+ */
208
+ getValidNextElement(el) {
209
+ const invalidTypes = ['DESCRIPTION','LINK','META','SCRIPT','STYLE','TEMPLATE','TITLE'];
210
+ let nextEl = el.nextElementSibling, targetEl;
211
+ while (nextEl) {
212
+ // If a valid element type, store it
213
+ const isValid = invalidTypes.indexOf(nextEl.nodeName) === -1;
214
+ if (isValid) targetEl = nextEl;
215
+ // Stop the loop if valid element found, or go to the next one
216
+ nextEl = targetEl ? false : nextEl.nextElementSibling;
217
+ }
218
+ return targetEl;
219
+ }
220
+
221
+ /**
222
+ * @description Match target attribute(s) against target DOM element
223
+ * @param {Object} el - The element to check attributes
224
+ * @param {*} attrs - The attributes to compare against
225
+ * @returns {Boolean}
226
+ * @private
227
+ */
228
+ hasAttribute(el, attrs) {
229
+ let tmpArr = [];
230
+ if (typeof attrs === 'string') tmpArr.push({ type: Util.attr.include, path: el.getAttribute(Util.attr.include) });
231
+ else attrs.forEach(a => tmpArr.push({ type: a, path: el.getAttribute(a) }));
232
+ // Filter out falsey
233
+ tmpArr = tmpArr.filter(a => a.path);
234
+ // Return boolean
235
+ return tmpArr[0] || false;
236
+ }
237
+
238
+
239
+ // LOGGING
240
+ // -----------------------------
241
+ // Display additional terminal logging when `process.env.LOGGER` enabled
242
+
243
+ startLog() {
244
+ // Early Exit: Logging not allowed
245
+ if (!process.env.LOGGER) return;
246
+ // Start Spinner
247
+ this.loading.start(chalk.magenta('Replacing Includes'));
248
+ // Start timer
249
+ this.timer.start();
250
+ }
251
+
252
+ endLog() {
253
+ // Early Exit: Logging not allowed
254
+ if (!process.env.LOGGER) return;
255
+ // Stop Spinner and Timer
256
+ if (this.total > 0) this.loading.stop(`Replaced ${chalk.magenta(this.total)} includes ${this.timer.end()}`);
257
+ // If no matches found, stop logger but don't show line in terminal
258
+ else this.loading.kill();
259
+ }
260
+
261
+
262
+ // EXPORT WRAPPER
263
+ // -----------------------------
264
+ // Export function wrapper instead of class for `build.js` simplicity
265
+ static async export(opts) {
266
+ return new ReplaceInclude(opts).init();
267
+ }
268
+ }
269
+
270
+
271
+ // EXPORT
272
+ // -----------------------------
273
+ export default ReplaceInclude.export;
@@ -0,0 +1,217 @@
1
+ /**
2
+ * @file replace-inline.js
3
+ * @description Replace external `<link>` and `<script>` calls inline
4
+ */
5
+
6
+ // IMPORT
7
+ // -----------------------------
8
+ import chalk from 'chalk';
9
+ import fs from 'fs-extra';
10
+ import Util from '../utils/util/util.js';
11
+
12
+ // Config
13
+ import { distPath } from '../utils/config/config.js';
14
+
15
+ // DEFINE
16
+ // -----------------------------
17
+ /**
18
+ * @description Replace external `<link>` and `<script>` calls inline
19
+ * @param {Object} obj - Deconstructed options object
20
+ * @property {Object} obj.file - The current file's info (name, extension, path, src, etc.)
21
+ * @property {Object} obj.store - The build process' own data store object we'll add the cached inline-file content to
22
+ * @property {Array} [obj.allowType] - Allowed file types (Opt-in)
23
+ * @property {Array} [obj.disallowType] - Disallowed file types (Opt-out)
24
+ */
25
+ class ReplaceInline {
26
+ constructor({file, store, allowType, disallowType, excludePaths = []}) {
27
+ this.opts = {file, allowType, disallowType, excludePaths};
28
+ this.file = file;
29
+ this.store = store;
30
+ this.allowType = allowType;
31
+ this.disallowType = disallowType;
32
+ this.excludePaths = excludePaths;
33
+
34
+ // Store holder for total # of replaced inline elements
35
+ this.total = 0;
36
+
37
+ // Add object to internal store for holding the cached include content
38
+ if (!this.store.cachedInline) this.store.cachedInline = {};
39
+
40
+ // Init terminal logging
41
+ if (process.env.LOGGER) Util.initLogging.call(this);
42
+ }
43
+
44
+ // INIT
45
+ // -----------------------------
46
+ // Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js
47
+ async init() {
48
+ // Early Exit: File type not allowed
49
+ const allowed = Util.isAllowedType(this.opts);
50
+ if (!allowed) return;
51
+ // Early Exit: Do not replace files locally
52
+ if (process.env.NODE_ENV === 'development') return;
53
+
54
+ // Destructure options
55
+ const { file } = this;
56
+
57
+ // Make source traversable with JSDOM
58
+ let dom = Util.jsdom.dom({src: file.src});
59
+
60
+ // Store all <link inline> and <scripts inline>
61
+ const inlineLinkSelector = Util.getSelector(Util.attr.inline, 'link');
62
+ const inlineScriptSelector = Util.getSelector(Util.attr.inline, 'script');
63
+ const links = dom.window.document.querySelectorAll(inlineLinkSelector);
64
+ const scripts = dom.window.document.querySelectorAll(inlineScriptSelector);
65
+ this.total = links.length + scripts.length;
66
+
67
+ // START LOGGING
68
+ this.startLog();
69
+
70
+ // REPLACE INLINE CSS
71
+ await this.replaceLinks({links, file});
72
+ // REPLACE INLINE SCRIPT
73
+ await this.replaceScripts({scripts, file});
74
+
75
+ // Store updated file source
76
+ file.src = Util.setSrc({dom});
77
+
78
+ // END LOGGING
79
+ this.endLog();
80
+ }
81
+
82
+
83
+ // PROCESS METHODS
84
+ // -----------------------------
85
+
86
+ /**
87
+ * @description TODO
88
+ * @param {Object} opts - Options object
89
+ * @property {Object} links - Query-selected group of `<link>` tags
90
+ * @property {Object} file - The current file being modified
91
+ * @private
92
+ */
93
+ async replaceLinks({links}) {
94
+ await Promise.all([...links].map(el => this.replaceTag(el,'href')));
95
+ }
96
+
97
+ /**
98
+ * @description TODO
99
+ * @param {Object} opts - Options object
100
+ * @property {Object} scripts - Query-selected group of `<script>` tags
101
+ * @property {Object} file - The current file being modified
102
+ * @private
103
+ */
104
+ async replaceScripts({scripts}) {
105
+ await Promise.all([...scripts].map(el => this.replaceTag(el,'src')));
106
+ }
107
+
108
+ /**
109
+ * @description Replace target tag with inline source equivalent
110
+ * @param {Object} el - The target `<link>` or `<script>` tag to replace
111
+ * @param {String} type - Either `href` or `src`, depending on the tag type
112
+ * @param {Object} scope - Reference to `this` context
113
+ */
114
+ async replaceTag(el,type) {
115
+ // Init vars
116
+ let content;
117
+
118
+ // Format path-to-source
119
+ // If running locally, it adds `https://localhost` to the path
120
+ // So our early exit would fail without formatting
121
+ const formatPath = this.formatPath(el[type]);
122
+ // Early Exit: Not a relative path to CSS file, likely external
123
+ if (formatPath.charAt(0) !== '/') return;
124
+
125
+ // CHECK IF CACHED VERSION
126
+ // If this path was already looked up previously, use the stored-in-memory source instead of fetching and reading the file again.
127
+ // NOTE: Include file could be empty, resulting in an empty string (''). Since this is treated as falsey by default,
128
+ // we explicitly check for undefined or null (we need Null Coalescing Operator in Node now, cmon!)
129
+ const cachedTarget = this.store.cachedInline[formatPath];
130
+ if ([undefined, null].indexOf(cachedTarget) === -1) content = cachedTarget;
131
+
132
+ // OTHERWISE, GET THE INCLUDE FILE'S CONTENT (`fs.readFile`)
133
+ else content = await this.fetchInlineSrc(formatPath);
134
+
135
+ // ADD CONTENT TO DOM
136
+ // Add new `<style>` tag and then delete `<link>`
137
+ const tagType = type === 'href' ? 'style' : 'script';
138
+ el.insertAdjacentHTML('beforebegin', `<${tagType}>${content}</${tagType}>`);
139
+ el.remove();
140
+ // Show terminal message
141
+ // Logger.success(`/${this.file.path} - Replaced link[${Util.attr.inline}]: ${ chalk.green(formatPath) }`);
142
+ }
143
+
144
+ /**
145
+ * @description Lookup the inline file, by path, and get its source content.
146
+ * @param
147
+ * @returns {String}
148
+ * @private
149
+ */
150
+ async fetchInlineSrc(path) {
151
+ const replacePath = `${distPath}${path}`;
152
+ try {
153
+ // Get source from file
154
+ const fetchedSrc = await fs.readFile(replacePath, 'utf-8');
155
+ // Add entry to cached object store
156
+ this.store.cachedInline[path] = fetchedSrc;
157
+ // Return source
158
+ return fetchedSrc;
159
+ }
160
+ catch (err) {
161
+ Util.customKill(`fetchInlineSrc(): ${err}`);
162
+ }
163
+ }
164
+
165
+
166
+ // HELPER METHODS
167
+ // -----------------------------
168
+
169
+ /**
170
+ * @description Remove localhost path when testing locally
171
+ * NOTE: If running `dev:prod` locally, the href will include `https://localhost`
172
+ * so the path would be something like: `/dist/https://localhost/assets/css/...`.
173
+ * So, we strip that out for local testing
174
+ * @param {String} path - The string path to format
175
+ * @returns {String}
176
+ * @private
177
+ */
178
+ formatPath(path) {
179
+ const pathSplit = path.split('https://localhost');
180
+ return pathSplit[pathSplit.length - 1];
181
+ }
182
+
183
+
184
+ // LOGGING
185
+ // -----------------------------
186
+ // Display additional terminal logging when `process.env.LOGGER` enabled
187
+
188
+ startLog() {
189
+ // Early Exit: Logging not allowed
190
+ if (!process.env.LOGGER) return;
191
+ // Start Spinner
192
+ this.loading.start(chalk.magenta('Replacing Inlines'));
193
+ // Start timer
194
+ this.timer.start();
195
+ }
196
+
197
+ endLog() {
198
+ // Early Exit: Logging not allowed
199
+ if (!process.env.LOGGER) return;
200
+ // Stop Spinner and Timer
201
+ if (this.total > 0) this.loading.stop(`Replaced ${chalk.magenta(this.total)} inlines ${this.timer.end()}`);
202
+ // If no matches found, stop logger but don't show line in terminal
203
+ else this.loading.kill();
204
+ }
205
+
206
+
207
+ // EXPORT WRAPPER
208
+ // -----------------------------
209
+ // Export function wrapper instead of class for `build.js` simplicity
210
+ static async export(opts) {
211
+ return new ReplaceInline(opts).init();
212
+ }
213
+ }
214
+
215
+ // EXPORT
216
+ // -----------------------------
217
+ export default ReplaceInline.export;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * @file replace-template-strings.js
3
+ * @description Compiles ES6 template strings in HTML/CSS files
4
+ */
5
+
6
+ // IMPORT
7
+ // -----------------------------
8
+ import utils from '../utils/util/util.js';
9
+
10
+
11
+ // DEFINE
12
+ // -----------------------------
13
+ /**
14
+ * @description Converts file into a function and returns the rendered value as the file source
15
+ * @param {Object} obj - Deconstructed options object
16
+ * @property {Object} obj.file - The current file's info (name, extension, path, src, etc.)
17
+ * @property {Object} obj.data - The user's custom data from the `data.js` config file, so they can access it in their custom plugins
18
+ * @property {Array} [obj.allowType] - Allowed file types (Opt-in)
19
+ * @property {Array} [obj.disallowType] - Disallowed file types (Opt-out)
20
+ */
21
+ class ReplaceTemplateStrings {
22
+ constructor({file, data, allowType, disallowType}) {
23
+ this.opts = {file, data, allowType, disallowType};
24
+ this.file = file;
25
+ this.data = data;
26
+ this.allowType = allowType;
27
+ this.disallowType = disallowType;
28
+ }
29
+
30
+ // INIT
31
+ // -----------------------------
32
+ // Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js
33
+ async init() {
34
+ // Early Exit: File type not allowed
35
+ const allowed = utils.isAllowedType(this.opts);
36
+ if (!allowed) return;
37
+
38
+ // REPLACE STRING VARIABLES WITH MATCHING DATA
39
+ // Find all template string variables, and replace them with their matching data value from `/config/data.js`
40
+
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
+ // Protect the CONTENT of <script> and <style> blocks from template resolution.
61
+ // JavaScript template literals like `${name}` and CSS custom properties
62
+ // should not be replaced with data values. But we still need to resolve
63
+ // vars in attributes (e.g., <script src="${site.js}">).
64
+ const protectedContent = [];
65
+ let src = this.file.src.replace(/(<(?:script|style)\b[^>]*>)([\s\S]*?)(<\/(?:script|style)>)/gi, (match, openTag, content, closeTag) => {
66
+ if (!content.trim()) return match; // Empty — nothing to protect
67
+ const index = protectedContent.length;
68
+ protectedContent.push(content);
69
+ return `${openTag}<!--COOK_PROTECTED_${index}-->${closeTag}`;
70
+ });
71
+
72
+ src = this.replaceTemplateVars(src, this.data);
73
+
74
+ // Restore protected content
75
+ this.file.src = src.replace(/<!--COOK_PROTECTED_(\d+)-->/g, (_, i) => protectedContent[i]);
76
+ }
77
+
78
+ // HELPER METHODS
79
+ // -----------------------------
80
+
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
+ // EXPORT WRAPPER
112
+ // -----------------------------
113
+ // Export function wrapper instead of class for `build.js` simplicity
114
+ static async export(opts) {
115
+ return new ReplaceTemplateStrings(opts).init();
116
+ }
117
+ }
118
+
119
+ // EXPORT
120
+ // -----------------------------
121
+ export default ReplaceTemplateStrings.export;