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,215 @@
1
+ /**
2
+ * @file auto-components.js
3
+ * @description Auto-detect custom elements in pages and manage JS loading.
4
+ *
5
+ * Scans each built HTML page for custom element tags (contain a hyphen),
6
+ * cross-references against a configurable list of CSS-only elements,
7
+ * and either:
8
+ * - Removes the VB script tag if only CSS-only elements are used
9
+ * - Keeps the VB bundle if JS-requiring elements are found
10
+ * - Generates an import map for per-component loading (when manifest exists)
11
+ */
12
+
13
+ // IMPORTS
14
+ // -----------------------------
15
+ import chalk from 'chalk';
16
+ import { existsSync } from 'node:fs';
17
+ import { promises as fs } from 'node:fs';
18
+ import path from 'node:path';
19
+ import Util from '../utils/util/util.js';
20
+
21
+ // Config
22
+ import { distPath, autoComponents as autoComponentsConfig } from '../utils/config/config.js';
23
+
24
+
25
+ // DEFINE
26
+ // -----------------------------
27
+ class AutoComponents {
28
+ constructor({ file, store, allowType, disallowType }) {
29
+ this.opts = { file, allowType, disallowType };
30
+ this.file = file;
31
+ this.store = store;
32
+
33
+ this.config = {
34
+ enabled: false,
35
+ // Path to component manifest JSON (tag → JS file mapping)
36
+ manifest: null,
37
+ // CSS-only elements that never need JS
38
+ cssOnly: [],
39
+ // Regex pattern to find VB bundle script tags for removal
40
+ bundlePattern: /vanilla-breeze[^"']*\.js/,
41
+ // User overrides
42
+ ...autoComponentsConfig,
43
+ };
44
+
45
+ // Lazily loaded manifest
46
+ if (!this.store._autoComponentsManifest) {
47
+ this.store._autoComponentsManifest = undefined; // not yet loaded
48
+ }
49
+
50
+ // Track stats
51
+ if (!this.store._autoComponentsStats) {
52
+ this.store._autoComponentsStats = { stripped: 0, kept: 0, importMapped: 0 };
53
+ }
54
+ }
55
+
56
+ // INIT
57
+ // -----------------------------
58
+ async init() {
59
+ // Early Exit: Disabled
60
+ if (!this.config.enabled) return;
61
+
62
+ // Early Exit: File type not allowed
63
+ const allowed = Util.isAllowedType(this.opts);
64
+ if (!allowed) return;
65
+
66
+ // Load manifest once
67
+ await this.loadManifest();
68
+
69
+ // Parse HTML for custom elements
70
+ const dom = Util.jsdom.dom({ src: this.file.src });
71
+ const document = dom.window.document;
72
+
73
+ // Find all custom element tags in the document
74
+ const customElements = this.findCustomElements(document);
75
+
76
+ // Separate into CSS-only and JS-requiring
77
+ const jsComponents = customElements.filter(tag => !this.isCssOnly(tag));
78
+
79
+ if (jsComponents.length === 0) {
80
+ // No JS-requiring components — remove VB bundle script
81
+ this.removeVbScript(document);
82
+ this.store._autoComponentsStats.stripped++;
83
+ } else if (this.store._autoComponentsManifest) {
84
+ // We have a manifest — generate import map for only needed components
85
+ this.injectImportMap(document, jsComponents);
86
+ this.removeVbScript(document);
87
+ this.store._autoComponentsStats.importMapped++;
88
+ } else {
89
+ // No manifest — keep the full bundle
90
+ this.store._autoComponentsStats.kept++;
91
+ }
92
+
93
+ // Store updated file source
94
+ this.file.src = Util.setSrc({ dom });
95
+ }
96
+
97
+ /**
98
+ * Find all custom element tag names in the document
99
+ * Custom elements must contain a hyphen per the HTML spec
100
+ * @param {Document} document
101
+ * @returns {string[]} Unique custom element tag names
102
+ */
103
+ findCustomElements(document) {
104
+ const tags = new Set();
105
+ const allElements = document.querySelectorAll('*');
106
+ for (const el of allElements) {
107
+ const tag = el.tagName.toLowerCase();
108
+ if (tag.includes('-')) {
109
+ tags.add(tag);
110
+ }
111
+ }
112
+ return [...tags];
113
+ }
114
+
115
+ /**
116
+ * Check if a custom element is CSS-only (no JS needed)
117
+ * @param {string} tag - Element tag name
118
+ * @returns {boolean}
119
+ */
120
+ isCssOnly(tag) {
121
+ return this.config.cssOnly.includes(tag);
122
+ }
123
+
124
+ /**
125
+ * Load the component manifest (JSON: tag → JS file path)
126
+ * Cached after first load.
127
+ */
128
+ async loadManifest() {
129
+ // Already loaded (or determined to not exist)
130
+ if (this.store._autoComponentsManifest !== undefined) return;
131
+
132
+ if (!this.config.manifest) {
133
+ this.store._autoComponentsManifest = null;
134
+ return;
135
+ }
136
+
137
+ const manifestPath = path.resolve(`${distPath}/${this.config.manifest}`);
138
+ if (!existsSync(manifestPath)) {
139
+ this.store._autoComponentsManifest = null;
140
+ return;
141
+ }
142
+
143
+ try {
144
+ const content = await fs.readFile(manifestPath, 'utf-8');
145
+ this.store._autoComponentsManifest = JSON.parse(content);
146
+ } catch {
147
+ this.store._autoComponentsManifest = null;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Remove the VB bundle <script> tag from the document
153
+ * @param {Document} document
154
+ */
155
+ removeVbScript(document) {
156
+ const scripts = document.querySelectorAll('script[src]');
157
+ for (const script of scripts) {
158
+ const src = script.getAttribute('src') || '';
159
+ if (this.config.bundlePattern.test(src)) {
160
+ script.remove();
161
+ }
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Inject an import map and module scripts for specific components
167
+ * @param {Document} document
168
+ * @param {string[]} jsComponents - Tag names that need JS
169
+ */
170
+ injectImportMap(document, jsComponents) {
171
+ const manifest = this.store._autoComponentsManifest;
172
+ if (!manifest) return;
173
+
174
+ const imports = {};
175
+ const needed = [];
176
+
177
+ for (const tag of jsComponents) {
178
+ const jsPath = manifest[tag];
179
+ if (jsPath) {
180
+ const importName = `vb/${tag}`;
181
+ imports[importName] = jsPath.startsWith('/') ? jsPath : `/${jsPath}`;
182
+ needed.push(importName);
183
+ }
184
+ }
185
+
186
+ if (needed.length === 0) return;
187
+
188
+ const head = document.querySelector('head');
189
+ if (!head) return;
190
+
191
+ // Create import map
192
+ const importMapScript = document.createElement('script');
193
+ importMapScript.setAttribute('type', 'importmap');
194
+ importMapScript.textContent = JSON.stringify({ imports }, null, 2);
195
+ head.appendChild(importMapScript);
196
+
197
+ // Create module script that imports all needed components
198
+ const moduleScript = document.createElement('script');
199
+ moduleScript.setAttribute('type', 'module');
200
+ moduleScript.textContent = needed.map(name => `import "${name}";`).join('\n');
201
+ head.appendChild(moduleScript);
202
+ }
203
+
204
+
205
+ // EXPORT WRAPPER
206
+ // -----------------------------
207
+ static async export(opts) {
208
+ return new AutoComponents(opts).init();
209
+ }
210
+ }
211
+
212
+
213
+ // EXPORT
214
+ // -----------------------------
215
+ export default AutoComponents.export;
@@ -0,0 +1,338 @@
1
+ /**
2
+ * @file bundle.js
3
+ * @description Find `<link>` or `<script>` with `[bundle]` or `[data-bundle]` attributes and bundle the code into one new .js file.
4
+ * Remove the old tag(s) and insert the new bundle file where the last bundled file was, that way it preserves execution order
5
+ * for dependencies below it.
6
+ * The entry is cached, so subsequent pages with the same setup just use the already-cached bundle instead of building it again per page.
7
+ */
8
+
9
+ // IMPORT
10
+ // -----------------------------
11
+ import chalk from 'chalk';
12
+ import fs from 'fs-extra';
13
+ import CleanCSS from 'clean-css';
14
+ import * as terser from 'terser';
15
+ import Logger from '../utils/logger/logger.js';
16
+ import Util from '../utils/util/util.js';
17
+
18
+ const cwd = process.cwd();
19
+
20
+ // Config
21
+ import { bundle, srcPath, distPath } from '../utils/config/config.js';
22
+
23
+
24
+ // DEFINE
25
+ // -----------------------------
26
+ /**
27
+ * @description Find and group `<link>` or `<script>` tags by adding their source to one bundle file
28
+ * and then removing the old, individual tags.
29
+ * The new file is inserted into the page at the location of the last bundled tag to preserve execution order.
30
+ * @param {Object} obj - Deconstructed options object
31
+ * @property {Object} obj.file - The current file's info (name, extension, path, src, etc.)
32
+ * @property {Object} obj.store - The build process' own data store object we'll add the cached include-file content to
33
+ * @property {Array} [obj.allowType] - Allowed file types (Opt-in)
34
+ * @property {Array} [obj.disallowType] - Disallowed file types (Opt-out)
35
+ */
36
+ class Bundle {
37
+ constructor({file, store, allowType, disallowType, excludePaths = []}) {
38
+ this.opts = {file, allowType, disallowType, excludePaths};
39
+ this.file = file;
40
+ this.store = store;
41
+ this.allowType = allowType;
42
+ this.disallowType = disallowType;
43
+ this.excludePaths = excludePaths;
44
+
45
+ // Store # of found elements to bundle
46
+ this.totalAdd = 0;
47
+ // Store # of created bundle files
48
+ this.totalBuild = 0;
49
+
50
+ // Use user-defined paths or set defaults for where to create the bundled files
51
+ this.bundleDistPath = bundle && bundle.distPath || `assets/bundle`;
52
+
53
+ // Init terminal logging
54
+ Util.initLogging.call(this);
55
+ }
56
+
57
+ // BUILD METHODS
58
+ // -----------------------------
59
+ // Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js
60
+
61
+ /**
62
+ * @description Find each `<link>` or `<script>` with `[data-bundle]` or `[bundle]` attribute,
63
+ * add their file path to a group array for bundling, add the new bundle `<link>` or `<script>`
64
+ * above the last-group instance element, and then finally remove all the 'old' `<link>` or `<script>`
65
+ * elements now that we've added the bundled version instead.
66
+ * ---
67
+ * NOTE: This does not create the bundled `.css` or `.js` file. For that see the `build()` method.
68
+ * Instead, this just compiles all the paths to the source we'll add to the new bundle files,
69
+ * as well as inserting the new DOM element and removing all the old DOM elements.
70
+ */
71
+ add() {
72
+ // Early Exit: User disabled bundling
73
+ if (bundle === false || bundle.enabled === false) return;
74
+ // Early Exit: Running locally and `BUNDLE=true` not set
75
+ if (process.env.NODE_ENV === 'development' && !process.env.BUNDLE) return;
76
+ // Early Exit: File type not allowed
77
+ const allowed = Util.isAllowedType(this.opts);
78
+ if (!allowed) return;
79
+
80
+ // Destructure options
81
+ const { file } = this;
82
+
83
+ // Make source traversable with JSDOM
84
+ const dom = Util.jsdom.dom({src: file.src});
85
+ const document = dom.window.document;
86
+
87
+ // Find `<link>` or `<script>` tags with the `[data-bundle]` or `[bundle]` attributes
88
+ const links = document.querySelectorAll('link[data-bundle], link[bundle]');
89
+ const scripts = document.querySelectorAll('script[data-bundle], script[bundle]');
90
+ this.totalAdd = links.length + scripts.length;
91
+
92
+ // Early Exit: No targets found
93
+ if (!this.totalAdd) return;
94
+
95
+ // START LOGGING
96
+ this.startLog('Finding Bundled Links and Scripts', true);
97
+
98
+ // REPLACE INLINE CSS
99
+ this.groupSrcAndInsertBundle(links, 'css');
100
+ // REPLACE INLINE SCRIPT
101
+ this.groupSrcAndInsertBundle(scripts, 'js');
102
+
103
+ // Store updated file source
104
+ file.src = Util.setSrc({dom});
105
+
106
+ // END LOGGING
107
+ this.endAddLog();
108
+ }
109
+
110
+ /**
111
+ * @description From the bundled groups compiled in `add()`,
112
+ * create the bundled `.css` and `.js` files in the desired `/dist` location..
113
+ */
114
+ async build() {
115
+ // Early Exit: User disabled bundling
116
+ if (bundle === false || bundle.enabled === false) return;
117
+ // Get file references
118
+ const cssGroups = this.store.bundle.css;
119
+ const jsGroups = this.store.bundle.js;
120
+ // Store # of files that will be created
121
+ this.totalBuild = Object.keys(cssGroups).length + Object.keys(jsGroups).length;
122
+
123
+ // ADD TERMINAL SECTION HEADING
124
+ if (this.totalBuild > 0) Logger.persist.header(`\nCreate Bundle Files`);
125
+
126
+ // START LOGGING
127
+ this.startLog('Creating Bundled Files');
128
+
129
+ // Create bundle directory if it doesn't already exist
130
+ await Util.createDirectory(`${distPath}/${this.bundleDistPath}`);
131
+
132
+ // Build bundle files
133
+ await this.buildBundles(cssGroups, 'css');
134
+ await this.buildBundles(jsGroups, 'js');
135
+
136
+ // END LOGGING
137
+ this.endBuildLog();
138
+ }
139
+
140
+
141
+ // PRIMARY PROCESS METHODS
142
+ // -----------------------------
143
+
144
+ /**
145
+ * @description Find all `<link>` or `<script>` tags that are bundled together.
146
+ * Store the group name and the file paths, then remove the 'old' DOM element references.
147
+ * Finally, insert a new element that will reference the bundle.
148
+ * ---
149
+ * NOTE: linked bundle file created further in the build process.
150
+ * @param {Array} targets - Array of `<link>` or `<script>` tags to group and then remove.
151
+ * @param {String} type - This method needs to know if we're working on a `<link>` or `<script>` tag (combined method)
152
+ * @private
153
+ */
154
+ async groupSrcAndInsertBundle(targets, type) {
155
+ const elType = type === 'js' ? 'script' : 'link';
156
+ const pathAttr = type === 'js' ? 'src' : 'href';
157
+ const bundleType = this.store.bundle[type];
158
+ const counters = {};
159
+
160
+ // Loop through each found target and add the source path
161
+ // to an appropriate group array.
162
+ targets.forEach(target => {
163
+ // Before storing, add a flag for whether we should minify the source or not
164
+ // For example, if bundling vendor code, it is likely already minified, so we don't want to do it again.
165
+ const minify = !target.hasAttribute('no-minify') && !target.hasAttribute('data-no-minify');
166
+ // Get the element's group by finding the `[bundle]` attribute value
167
+ const {raw,formatted} = this.getGroup(target);
168
+ // If the group hasn't been added to the collection, add it
169
+ if (!bundleType[formatted]) bundleType[formatted] = [];
170
+ const bundleGroup = bundleType[formatted];
171
+ // If the path hasn't been added to the group yet, add it
172
+ const path = target[pathAttr];
173
+ // Map just the paths so we can use indexOf on a flattened string-array, instead of the normal object-array
174
+ const pathsMap = bundleGroup.map(g => g.path);
175
+ // Add the file entry if it doesn't already exist (this way if the same file added on multiple pages, we only add once)
176
+ if (pathsMap.indexOf(path) === -1) bundleGroup.push({ path, minify });
177
+ // Add index of this element in its group as attribute. Will be used in next step
178
+ if (!counters[formatted]) counters[formatted] = 0;
179
+ target.setAttribute('group-index', counters[formatted]);
180
+ // Update counter for next step
181
+ counters[formatted] += 1;
182
+ });
183
+
184
+ // Loop through each target again.
185
+ // If it is the last bundle-group item on the page,
186
+ // we'll insert that bundle call into the DOM above it.
187
+ // ---
188
+ // For all targets we'll remove them from the source
189
+ // now that we're inserting the bundled version instead.
190
+ targets.forEach(target => {
191
+ const {raw,formatted} = this.getGroup(target);
192
+ const numInstancesFoundInGroup = [...targets].filter(t => t.getAttribute('data-bundle') === raw || t.getAttribute('bundle') === raw);
193
+ const groupLen = numInstancesFoundInGroup.length;
194
+ const groupIndex = parseInt(target.getAttribute('group-index'));
195
+ const isLast = groupIndex === groupLen - 1;
196
+ // If the element is the last one of the group on the page,
197
+ // Add the bundled version into the DOM above it
198
+ // NOTE: We're making the path 'relative' (instead of adding `${distPath}/`) since this will be the tag's attribute source reference
199
+ const filePath = `/${this.bundleDistPath}/bundle-${formatted}.${type}`;
200
+ const elOptions = type === 'js' ? ` src="${filePath}"` : ` rel="stylesheet" href="${filePath}"`;
201
+ if (isLast) target.insertAdjacentHTML('beforebegin', `<${elType}${elOptions}></${elType}>`)
202
+ // Then remove the old indiv. instance since the bundle is now loaded
203
+ // NOTE: We remove all 'old' instances since they are now bundled
204
+ target.remove();
205
+ });
206
+ }
207
+
208
+ /**
209
+ * @description Get all referenced files' source and create the new bundled file.
210
+ * @param {Object} targets - The CSS or JS object that contains each found bundle group.
211
+ * @param {String} type - This method needs to know if we're working on a `<link>` or `<script>` tag (combined method)
212
+ * @private
213
+ */
214
+ async buildBundles(targets, type) {
215
+ const groupKeys = Object.keys(targets);
216
+ // Early Exit: No bundle groups found of the given type
217
+ if (!groupKeys) return;
218
+ // Fetch source from targeted group file and combine into one source string.
219
+ // We're effectively bundling the source code here, and then we'll write it
220
+ // to a new file next.
221
+ // ---
222
+ // Loop through each group
223
+ await Promise.all(groupKeys.map(key => this.buildBundle({key, paths: targets[key], type})));
224
+ }
225
+ // Build individual bundle file
226
+ async buildBundle({key, paths, type}) {
227
+ // Init bundled string
228
+ let bundledSrc = '';
229
+ // For each file path, fetch it's source
230
+ // NOTE: This is a synchronous process b/c the code order needs to be maintained
231
+ for (let path of paths) {
232
+ bundledSrc += await this.getSrc(path, type);
233
+ }
234
+ // Create file in designated 'dist' directory, either defined by the user in `/config/main.js`,
235
+ // or via the default location (something like `/dist/assets/bundle`)
236
+ // See: `this.bundleDistPath` defined in the constructor
237
+ await fs.writeFile(`${distPath}/${this.bundleDistPath}/bundle-${key}.${type}`, bundledSrc, 'utf-8');
238
+ }
239
+
240
+
241
+ // HELPER METHODS
242
+ // -----------------------------
243
+
244
+ /**
245
+ * @description Get and format the group name from the `[bundle]` attribute value.
246
+ * @example `data-bundle="My Bundle"` becomes `my-bundle`, for use in the bundled file's name: `data-my-bundle.js`
247
+ * @param {Object} target - The `<link>` or `<script>` element
248
+ * @returns {Object}
249
+ */
250
+ getGroup(target) {
251
+ const raw = target.getAttribute('data-bundle') || target.getAttribute('bundle');
252
+ const formatted = raw.replace(/ /g, '-').toLowerCase();
253
+ return {raw,formatted};
254
+ }
255
+
256
+ async getSrc(entry, type) {
257
+ const { path, minify } = entry;
258
+ // Early Exit: No path for some reason
259
+ if (!path) return '';
260
+ // Get the file's source content
261
+ try {
262
+ // Remove `https://localhost/` when building locally
263
+ const pathSplit = path.split('localhost');
264
+ const pathFormatted = pathSplit[pathSplit.length - 1];
265
+ // Get path starting from the 'src' directory. Example: `/src/assets/plugin/myplugin.js`
266
+ let src = await fs.readFile(`${srcPath}/${pathFormatted}`, 'utf-8');
267
+ // If the source is allowed to by minified, minify it
268
+ if (minify) src = type === 'js' ? await this.minJs(src) : this.minCss(src);
269
+ // Return the found source
270
+ return src;
271
+ }
272
+ catch (err) {
273
+ Util.customKill(err, `Error fetching the source from: ${path}`);
274
+ }
275
+ }
276
+
277
+ async minJs(src) {
278
+ const config = {};
279
+ const result = await terser.minify(src, config);
280
+ return result.code;
281
+ }
282
+
283
+ minCss(src) {
284
+ const config = { inline: ['none'] };
285
+ // Minify source
286
+ return new CleanCSS(config).minify(src).styles;
287
+ }
288
+
289
+
290
+ // LOGGING
291
+ // -----------------------------
292
+ // Display additional terminal logging when `process.env.LOGGER` enabled
293
+
294
+ startLog(label, isAdd) {
295
+ // Early Exit: Logging not allowed for in-page bundle collecting (`add()`)
296
+ // but is for the `build()` process
297
+ if (!process.env.LOGGER && isAdd) return;
298
+ // Start Spinner
299
+ this.loading.start(chalk.magenta(label));
300
+ // Start timer
301
+ this.timer.start();
302
+ }
303
+
304
+ endAddLog() {
305
+ // Early Exit: Logging not allowed
306
+ if (!process.env.LOGGER) return;
307
+ // Stop Spinner and Timer
308
+ if (this.totalAdd > 0) this.loading.stop(`Found ${chalk.magenta(this.totalAdd)} bundle targets ${this.timer.end()}`);
309
+ // If no matches found, stop logger but don't show line in terminal
310
+ else this.loading.kill();
311
+ }
312
+
313
+ endBuildLog() {
314
+ // Stop Spinner and Timer
315
+ const plural = this.totalBuild === 1 ? '' : 's';
316
+ if (this.totalBuild > 0) this.loading.stop(`Created ${chalk.magenta(this.totalBuild)} bundle file${plural} ${this.timer.end()}`);
317
+ // If no matches found, stop logger but don't show line in terminal
318
+ else this.loading.kill();
319
+ }
320
+
321
+
322
+ // EXPORT WRAPPER
323
+ // -----------------------------
324
+ // Export function wrapper instead of class for `build.js` simplicity
325
+ static add(opts) {
326
+ return new Bundle(opts).add();
327
+ }
328
+
329
+ static build(opts) {
330
+ return new Bundle(opts).build();
331
+ }
332
+ }
333
+
334
+ // EXPORT
335
+ // -----------------------------
336
+ const bundleAdd = Bundle.add;
337
+ const bundleBuild = Bundle.build;
338
+ export { bundleAdd, bundleBuild };
@@ -0,0 +1,89 @@
1
+ /**
2
+ * @file copy-src.js
3
+ * @description Copy contents of `/src` to `/dist`
4
+ */
5
+
6
+ // IMPORT
7
+ // -----------------------------
8
+ const cwd = process.cwd();
9
+ import chalk from 'chalk';
10
+ import fs from 'fs-extra';
11
+ import Logger from '../utils/logger/logger.js';
12
+ import Util from '../utils/util/util.js';
13
+
14
+ // Config
15
+ import { buildOnlyPaths, distPath, srcPath } from '../utils/config/config.js';
16
+
17
+ // DEFINE
18
+ // -----------------------------
19
+ class CopySrc {
20
+ constructor() {}
21
+
22
+ // INIT
23
+ // -----------------------------
24
+ // Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js
25
+ async init() {
26
+ // FILE CHANGE
27
+ // If only a single page was updated, just copy it
28
+ const isValidPageChange = Util.validatePageChange();
29
+ if (isValidPageChange) {
30
+ // Store start and end paths
31
+ const changedPath = process.env.DEV_CHANGED_PAGE;
32
+ const changedSrcPath = changedPath;
33
+ const changedDistPath = changedPath.replace(srcPath, distPath);
34
+ // Show terminal message: Start
35
+ Logger.persist.header(`\nCopied Updated Page`);
36
+ // Copy changed page to `/dist` only
37
+ await fs.copy(changedSrcPath, changedDistPath).catch(err => Util.customError(err, 'CopySrc.init(): Page Change'));
38
+ // Show terminal message
39
+ Logger.persist.success(`/${changedSrcPath} copied to /${changedDistPath}`);
40
+ }
41
+ // FULL BUILD
42
+ // Otherwise, copy all contents of `/src` to `/dist`
43
+ else {
44
+ // Show terminal message: Start
45
+ Logger.persist.header('\nCopy /src to /dist');
46
+ // Copy contents of `/src` to `/dist` (exclude targets by extension - markdown)
47
+ await fs.copy(srcPath, distPath, { filter: this.excludeByExtension }).catch(err => Util.customError(err, 'CopySrc.init(): Full Build'));
48
+ // Show terminal message
49
+ Logger.persist.success(`Content from /${srcPath} copied to /${distPath}`);
50
+ }
51
+ }
52
+
53
+ // HELPER METHODS
54
+ // -----------------------------
55
+
56
+ // Filter out files/directories that shouldn't be copied to dist
57
+ excludeByExtension(src,dest) {
58
+ // Skip build-only directories (includes, components, layouts, etc.)
59
+ if (buildOnlyPaths && buildOnlyPaths.length) {
60
+ for (const buildOnlyDir of buildOnlyPaths) {
61
+ // Match src/dirname or src/dirname/... paths
62
+ const pattern = new RegExp(`(^|/)${srcPath}/${buildOnlyDir}(/|$)`);
63
+ if (pattern.test(src)) return false;
64
+ }
65
+ }
66
+ // Skip directories (allow them to be traversed, filtering happens on files/subdirs)
67
+ if (fs.lstatSync(src).isDirectory()) return true;
68
+ // ---
69
+ // MARKDOWN
70
+ // Don't copy markdown files
71
+ const markdownPattern = /.*(?<!.md)$/;
72
+ const isNotMarkdown = markdownPattern.test(src);
73
+ // Copy the file if it passes the regex (not a .md file)
74
+ return isNotMarkdown;
75
+ }
76
+
77
+
78
+ // EXPORT WRAPPER
79
+ // -----------------------------
80
+ // Export function wrapper instead of class for `build.js` simplicity
81
+ static async export(opts) {
82
+ return new CopySrc(opts).init();
83
+ }
84
+ }
85
+
86
+
87
+ // EXPORT
88
+ // -----------------------------
89
+ export default CopySrc.export;