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,75 @@
1
+ /**
2
+ * @file process-html-frontmatter.js
3
+ * @description Parse YAML front matter from HTML files.
4
+ *
5
+ * HTML files can include YAML front matter delimited by --- at the top:
6
+ *
7
+ * ---
8
+ * layout: element
9
+ * title: button
10
+ * category: native
11
+ * ---
12
+ * <section>...</section>
13
+ *
14
+ * The front matter is stripped from file.src and stored on file.frontMatter.
15
+ * A `layout` key in front matter is equivalent to data-template="name" —
16
+ * applyTemplate checks file.frontMatter.layout as a fallback.
17
+ */
18
+
19
+ // IMPORTS
20
+ // -----------------------------
21
+ import matter from 'gray-matter';
22
+ import Util from '../utils/util/util.js';
23
+
24
+
25
+ // DEFINE
26
+ // -----------------------------
27
+ class ProcessHtmlFrontmatter {
28
+ constructor({ file, allowType, disallowType }) {
29
+ this.opts = { file, allowType, disallowType };
30
+ this.file = file;
31
+ }
32
+
33
+ // INIT
34
+ // -----------------------------
35
+ async init() {
36
+ // Early Exit: File type not allowed
37
+ const allowed = Util.isAllowedType(this.opts);
38
+ if (!allowed) return;
39
+
40
+ // Early Exit: No front matter delimiter at start of file
41
+ if (!this.file.src.startsWith('---')) return;
42
+
43
+ // Parse front matter
44
+ const { data: frontMatter, content } = matter(this.file.src);
45
+
46
+ // Early Exit: No front matter found
47
+ if (!frontMatter || Object.keys(frontMatter).length === 0) return;
48
+
49
+ // Derive currentPath from file path if not set in front matter.
50
+ // e.g., dist/pages/docs/elements/native/button.html → /docs/elements/native/button/
51
+ if (!frontMatter.currentPath && this.file.path) {
52
+ const distMatch = this.file.path.match(/dist\/(?:pages\/)?(.*?)(?:\/index)?\.html$/);
53
+ if (distMatch) {
54
+ frontMatter.currentPath = '/' + distMatch[1] + '/';
55
+ }
56
+ }
57
+
58
+ // Store parsed front matter on the file object
59
+ this.file.frontMatter = frontMatter;
60
+
61
+ // Strip front matter from source, leaving just the HTML content
62
+ this.file.src = content.trim();
63
+ }
64
+
65
+ // EXPORT WRAPPER
66
+ // -----------------------------
67
+ static async export(opts) {
68
+ return new ProcessHtmlFrontmatter(opts).init();
69
+ }
70
+ }
71
+
72
+
73
+ // EXPORT
74
+ // -----------------------------
75
+ export default ProcessHtmlFrontmatter.export;
@@ -0,0 +1,384 @@
1
+ /**
2
+ * @file process-markdown.js
3
+ * @description Convert markdown files to HTML with front matter support
4
+ */
5
+
6
+ // IMPORTS
7
+ // -----------------------------
8
+ import chalk from 'chalk';
9
+ import { promises as fs } from 'node:fs';
10
+ import { existsSync, lstatSync } from 'node:fs';
11
+ import path from 'node:path';
12
+ import { marked } from 'marked';
13
+ import matter from 'gray-matter';
14
+ import Logger from '../utils/logger/logger.js';
15
+ import Util from '../utils/util/util.js';
16
+
17
+ // Config
18
+ import { distPath, srcPath, markdown as markdownConfig } from '../utils/config/config.js';
19
+
20
+
21
+ // DEFINE
22
+ // -----------------------------
23
+ /**
24
+ * @description Process markdown files from /src and convert to HTML in /dist
25
+ * @param {Object} opts - Options object
26
+ * @property {Object} opts.store - Build process data store
27
+ * @property {Object} opts.data - User data from config/data.js
28
+ */
29
+ class ProcessMarkdown {
30
+ constructor({ store, data }) {
31
+ this.store = store;
32
+ this.data = data;
33
+ this.config = {
34
+ // Default layout template (null = no wrapper)
35
+ layout: null,
36
+ // Directory for layout templates
37
+ layoutPath: 'layouts',
38
+ // Directory for markdown content (relative to src)
39
+ contentPath: '',
40
+ // Generate collections from directories
41
+ collections: true,
42
+ // marked options
43
+ markedOptions: {
44
+ gfm: true,
45
+ breaks: false,
46
+ },
47
+ // User overrides
48
+ ...markdownConfig,
49
+ };
50
+
51
+ // Initialize collections store
52
+ if (!this.store.collections) {
53
+ this.store.collections = {};
54
+ }
55
+
56
+ // Cache for layout templates
57
+ if (!this.store.cachedLayouts) {
58
+ this.store.cachedLayouts = {};
59
+ }
60
+
61
+ // Track processed files
62
+ this.processedFiles = [];
63
+ }
64
+
65
+ // INIT
66
+ // -----------------------------
67
+ async init() {
68
+ // Configure marked
69
+ marked.setOptions(this.config.markedOptions);
70
+
71
+ // Find all markdown files in /src
72
+ const markdownFiles = this.findMarkdownFiles(srcPath);
73
+
74
+ // Early exit if no markdown files
75
+ if (!markdownFiles.length) {
76
+ return;
77
+ }
78
+
79
+ // Show terminal message
80
+ Logger.persist.header('\nProcess Markdown');
81
+
82
+ // Process each markdown file
83
+ for (const filePath of markdownFiles) {
84
+ await this.processFile(filePath);
85
+ }
86
+
87
+ // Build collections from processed files
88
+ this.buildCollections();
89
+
90
+ // Expose collections to data store for use in templates
91
+ this.data.collections = this.store.collections;
92
+
93
+ // Show terminal message
94
+ Logger.persist.success(`Converted ${this.processedFiles.length} markdown files`);
95
+ }
96
+
97
+ /**
98
+ * Find all markdown files recursively
99
+ * @param {string} dir - Directory to search
100
+ * @returns {string[]} Array of file paths
101
+ */
102
+ findMarkdownFiles(dir) {
103
+ const files = [];
104
+
105
+ if (!existsSync(dir)) {
106
+ return files;
107
+ }
108
+
109
+ const entries = Util.getPaths(dir, dir, []);
110
+
111
+ for (const entry of entries) {
112
+ if (entry.endsWith('.md')) {
113
+ files.push(entry);
114
+ }
115
+ }
116
+
117
+ return files;
118
+ }
119
+
120
+ /**
121
+ * Process a single markdown file
122
+ * @param {string} filePath - Path to markdown file
123
+ */
124
+ async processFile(filePath) {
125
+ try {
126
+ // Read markdown file
127
+ const content = await fs.readFile(filePath, 'utf-8');
128
+
129
+ // Parse front matter
130
+ const { data: frontMatter, content: markdownContent } = matter(content);
131
+
132
+ // Convert markdown to HTML
133
+ const htmlContent = marked(markdownContent);
134
+
135
+ // Build page data
136
+ const pageData = this.buildPageData(filePath, frontMatter, htmlContent);
137
+
138
+ // Get layout if specified
139
+ const layout = frontMatter.layout || this.config.layout;
140
+
141
+ // Build final HTML
142
+ let finalHtml;
143
+ if (layout) {
144
+ finalHtml = await this.applyLayout(layout, pageData);
145
+ } else {
146
+ // No layout - wrap in basic HTML structure
147
+ finalHtml = this.buildBasicHtml(pageData);
148
+ }
149
+
150
+ // Calculate output path
151
+ const outputPath = this.getOutputPath(filePath);
152
+
153
+ // Ensure directory exists
154
+ await Util.createDirectory(path.dirname(outputPath));
155
+
156
+ // Write HTML file
157
+ await fs.writeFile(outputPath, finalHtml, 'utf-8');
158
+
159
+ // Track for collections
160
+ this.processedFiles.push({
161
+ ...pageData,
162
+ outputPath,
163
+ });
164
+
165
+ } catch (err) {
166
+ Util.customError(err, `ProcessMarkdown: ${filePath}`);
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Build page data object from front matter and content
172
+ * @param {string} filePath - Original file path
173
+ * @param {Object} frontMatter - Parsed front matter
174
+ * @param {string} htmlContent - Converted HTML content
175
+ * @returns {Object} Page data object
176
+ */
177
+ buildPageData(filePath, frontMatter, htmlContent) {
178
+ // Get relative path from src
179
+ const relativePath = filePath.replace(`${srcPath}/`, '');
180
+
181
+ // Get URL path (without .md extension)
182
+ const urlPath = '/' + relativePath.replace(/\.md$/, '/').replace(/\/index\/$/, '/');
183
+
184
+ // Get collection name from directory
185
+ const pathParts = relativePath.split('/');
186
+ const collection = pathParts.length > 1 ? pathParts[0] : null;
187
+
188
+ // Get file name without extension
189
+ const fileName = path.basename(filePath, '.md');
190
+
191
+ return {
192
+ // Front matter fields (user-defined)
193
+ ...frontMatter,
194
+ // Generated fields
195
+ content: htmlContent,
196
+ url: urlPath,
197
+ slug: fileName,
198
+ collection,
199
+ sourcePath: filePath,
200
+ // Default title from filename if not in front matter
201
+ title: frontMatter.title || Util.convertToCapSpaces(fileName, 'kebab'),
202
+ // Keep date as timezone-safe string for templates
203
+ // gray-matter auto-parses YAML dates to Date objects, so extract YYYY-MM-DD
204
+ date: frontMatter.date
205
+ ? (frontMatter.date instanceof Date
206
+ ? frontMatter.date.toISOString().split('T')[0]
207
+ : String(frontMatter.date))
208
+ : null,
209
+ // Parsed Date for sorting
210
+ _dateSort: frontMatter.date ? new Date(frontMatter.date) : null,
211
+ };
212
+ }
213
+
214
+ /**
215
+ * Apply a layout template to page content
216
+ * @param {string} layoutName - Layout template name
217
+ * @param {Object} pageData - Page data object
218
+ * @returns {string} Final HTML
219
+ */
220
+ async applyLayout(layoutName, pageData) {
221
+ // Get layout template
222
+ const layoutContent = await this.getLayout(layoutName);
223
+
224
+ if (!layoutContent) {
225
+ // Fallback to basic HTML if layout not found
226
+ console.log(chalk.yellow(` Layout "${layoutName}" not found, using basic HTML`));
227
+ return this.buildBasicHtml(pageData);
228
+ }
229
+
230
+ // Replace template variables in layout
231
+ let html = layoutContent;
232
+
233
+ // Replace ${content} with the markdown-converted HTML
234
+ html = html.replace(/\$\{content\}/g, pageData.content);
235
+
236
+ // Replace other ${variable} placeholders with page data
237
+ html = html.replace(/\$\{([^}]+)\}/g, (match, key) => {
238
+ const trimmedKey = key.trim();
239
+
240
+ // Check page data first
241
+ if (pageData[trimmedKey] !== undefined) {
242
+ return pageData[trimmedKey];
243
+ }
244
+
245
+ // Then check global data
246
+ if (this.data[trimmedKey] !== undefined) {
247
+ return this.data[trimmedKey];
248
+ }
249
+
250
+ // Leave unmatched placeholders as-is (for later processing)
251
+ return match;
252
+ });
253
+
254
+ return html;
255
+ }
256
+
257
+ /**
258
+ * Get layout template content (with caching)
259
+ * @param {string} layoutName - Layout name
260
+ * @returns {string|null} Layout content or null
261
+ */
262
+ async getLayout(layoutName) {
263
+ // Check cache
264
+ if (this.store.cachedLayouts[layoutName] !== undefined) {
265
+ return this.store.cachedLayouts[layoutName];
266
+ }
267
+
268
+ // Build possible paths
269
+ const layoutFileName = layoutName.endsWith('.html') ? layoutName : `${layoutName}.html`;
270
+ const possiblePaths = [
271
+ path.resolve(`${srcPath}/${this.config.layoutPath}/${layoutFileName}`),
272
+ path.resolve(`${srcPath}/${this.config.layoutPath}/${layoutName}/index.html`),
273
+ path.resolve(`${distPath}/${this.config.layoutPath}/${layoutFileName}`),
274
+ path.resolve(`${distPath}/${this.config.layoutPath}/${layoutName}/index.html`),
275
+ ];
276
+
277
+ // Try each path
278
+ for (const layoutPath of possiblePaths) {
279
+ if (existsSync(layoutPath)) {
280
+ try {
281
+ const content = await fs.readFile(layoutPath, 'utf-8');
282
+ this.store.cachedLayouts[layoutName] = content;
283
+ return content;
284
+ } catch (err) {
285
+ // Continue to next path
286
+ }
287
+ }
288
+ }
289
+
290
+ // Not found
291
+ this.store.cachedLayouts[layoutName] = null;
292
+ return null;
293
+ }
294
+
295
+ /**
296
+ * Build basic HTML wrapper when no layout is specified
297
+ * @param {Object} pageData - Page data
298
+ * @returns {string} HTML string
299
+ */
300
+ buildBasicHtml(pageData) {
301
+ return `<!DOCTYPE html>
302
+ <html lang="en">
303
+ <head>
304
+ <meta charset="UTF-8">
305
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
306
+ <title>${pageData.title}</title>
307
+ </head>
308
+ <body>
309
+ ${pageData.content}
310
+ </body>
311
+ </html>`;
312
+ }
313
+
314
+ /**
315
+ * Calculate output path for HTML file
316
+ * @param {string} inputPath - Input markdown file path
317
+ * @returns {string} Output HTML file path
318
+ */
319
+ getOutputPath(inputPath) {
320
+ // Replace src with dist
321
+ let outputPath = inputPath.replace(srcPath, distPath);
322
+
323
+ // Replace .md with /index.html for clean URLs
324
+ // e.g., /blog/my-post.md -> /blog/my-post/index.html
325
+ outputPath = outputPath.replace(/\.md$/, '/index.html');
326
+
327
+ // Handle index.md -> index.html (not index/index.html)
328
+ outputPath = outputPath.replace(/\/index\/index\.html$/, '/index.html');
329
+
330
+ return outputPath;
331
+ }
332
+
333
+ /**
334
+ * Build collections from processed files
335
+ */
336
+ buildCollections() {
337
+ if (!this.config.collections) return;
338
+
339
+ for (const page of this.processedFiles) {
340
+ if (page.collection) {
341
+ // Initialize collection array if needed
342
+ if (!this.store.collections[page.collection]) {
343
+ this.store.collections[page.collection] = [];
344
+ }
345
+
346
+ // Add page to collection (without full content to save memory)
347
+ this.store.collections[page.collection].push({
348
+ title: page.title,
349
+ url: page.url,
350
+ slug: page.slug,
351
+ date: page.date,
352
+ description: page.description,
353
+ // Include any other front matter fields except content
354
+ ...Object.fromEntries(
355
+ Object.entries(page).filter(([key]) =>
356
+ !['content', 'sourcePath', 'outputPath', 'collection'].includes(key)
357
+ )
358
+ ),
359
+ });
360
+ }
361
+ }
362
+
363
+ // Sort collections by date (newest first)
364
+ for (const collectionName of Object.keys(this.store.collections)) {
365
+ this.store.collections[collectionName].sort((a, b) => {
366
+ if (!a._dateSort && !b._dateSort) return 0;
367
+ if (!a._dateSort) return 1;
368
+ if (!b._dateSort) return -1;
369
+ return b._dateSort - a._dateSort;
370
+ });
371
+ }
372
+ }
373
+
374
+ // EXPORT WRAPPER
375
+ // -----------------------------
376
+ static async export(opts) {
377
+ return new ProcessMarkdown(opts).init();
378
+ }
379
+ }
380
+
381
+
382
+ // EXPORT
383
+ // -----------------------------
384
+ export default ProcessMarkdown.export;