cook-ssg 2.6.0 → 2.8.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.
@@ -0,0 +1,214 @@
1
+ /**
2
+ * @file programs.js
3
+ * @description Programs: folders of hand-written HTML/JS (`src/<area>/<slug>/`)
4
+ * that Cook leaves untouched. Reads config/programs.json, validates areas and
5
+ * cards, exposes `programs` / `programAreas` data, and answers "is this path
6
+ * inside a program folder" (isInProgram) for the other build passes.
7
+ */
8
+
9
+ import chalk from 'chalk';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { getPrograms, srcPath, buildOnlyPaths } from '../utils/config/config.js';
13
+
14
+ const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
15
+ const isSlug = (v) => typeof v === 'string' && SLUG.test(v);
16
+ const TAG = '[programs] ';
17
+ export const RESERVED_AREAS = ['media', 'assets', 'layouts', 'includes'];
18
+
19
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
20
+
21
+ /**
22
+ * Validate raw config/programs.json.
23
+ * @param {unknown} raw
24
+ * @param {{ srcEntries: string[], buildOnlyPaths: string[], hasIndex: (area: string, slug: string) => boolean }} ctx
25
+ */
26
+ export function normalizePrograms(raw, { srcEntries = [], buildOnlyPaths: buildOnly = [], hasIndex = () => true } = {}) {
27
+ const warnings = [];
28
+ const areas = [];
29
+ const programs = [];
30
+ // A slug-shaped area that collides with a page folder (R10): no programs data, but its
31
+ // subfolders stay program folders (untouched) and its sandboxed cards keep their rule.
32
+ const protectedAreas = [];
33
+ const protectedPrograms = [];
34
+ if (!isObj(raw)) return { areas, programs, warnings, protectedAreas, protectedPrograms };
35
+
36
+ const taken = new Set(srcEntries);
37
+ const buildOnlySet = new Set(buildOnly.map(p => String(p).replace(/^\/+|\/+$/g, '')));
38
+ const byPath = Object.create(null);
39
+ const protectedByPath = Object.create(null);
40
+
41
+ for (const a of Array.isArray(raw.areas) ? raw.areas : []) {
42
+ const p = isObj(a) ? a.path : undefined;
43
+ let why = null;
44
+ if (!isSlug(p)) why = 'use one lowercase segment (a-z, 0-9, hyphens)';
45
+ else if (RESERVED_AREAS.includes(p)) why = 'that name is reserved';
46
+ else if (buildOnlySet.has(p)) why = 'it is a buildOnlyPaths entry';
47
+ else if (byPath[p] || protectedByPath[p]) why = 'duplicate area';
48
+ else if (taken.has(p)) {
49
+ const area = { path: p, sandbox: a.sandbox === true };
50
+ protectedByPath[p] = area;
51
+ protectedAreas.push(area);
52
+ warnings.push(`${TAG}area ${JSON.stringify(p)} ignored: the site already has a page or folder with that name `
53
+ + '(no programs data for it; its subfolders still ship untouched as program folders)');
54
+ continue;
55
+ }
56
+ if (why) {
57
+ warnings.push(`${TAG}area ${JSON.stringify(p)} ignored: ${why}`);
58
+ continue;
59
+ }
60
+ const area = { path: p, title: typeof a.title === 'string' && a.title ? a.title : p, sandbox: a.sandbox === true };
61
+ byPath[p] = area;
62
+ areas.push(area);
63
+ }
64
+
65
+ const seen = new Set();
66
+ for (const c of Array.isArray(raw.programs) ? raw.programs : []) {
67
+ const label = isObj(c) ? `${c.area}/${c.slug}` : JSON.stringify(c);
68
+ if (isObj(c) && protectedByPath[c.area]) {
69
+ if (isSlug(c.slug) && !seen.has(label)) {
70
+ seen.add(label);
71
+ protectedPrograms.push({
72
+ area: c.area, slug: c.slug, sandbox: typeof c.sandbox === 'boolean' ? c.sandbox : protectedByPath[c.area].sandbox,
73
+ });
74
+ }
75
+ continue;
76
+ }
77
+ if (!isObj(c) || !byPath[c.area]) {
78
+ warnings.push(`${TAG}program ${label} ignored: unknown area`);
79
+ continue;
80
+ }
81
+ if (!isSlug(c.slug)) {
82
+ warnings.push(`${TAG}program ${label} ignored: bad slug (use a-z, 0-9, hyphens)`);
83
+ continue;
84
+ }
85
+ if (seen.has(label)) {
86
+ warnings.push(`${TAG}program ${label} ignored: duplicate`);
87
+ continue;
88
+ }
89
+ seen.add(label);
90
+ const tags = Array.isArray(c.tags) ? c.tags.filter(t => typeof t === 'string') : [];
91
+ programs.push({
92
+ ...c,
93
+ title: typeof c.title === 'string' && c.title ? c.title : c.slug,
94
+ tags,
95
+ url: `/${c.area}/${c.slug}/`,
96
+ sandbox: typeof c.sandbox === 'boolean' ? c.sandbox : byPath[c.area].sandbox,
97
+ hasIndex: !!hasIndex(c.area, c.slug),
98
+ });
99
+ }
100
+ return { areas, programs, warnings, protectedAreas, protectedPrograms };
101
+ }
102
+
103
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : Infinity);
104
+
105
+ function sortPrograms(list) {
106
+ return list.slice().sort((a, b) => {
107
+ const da = String(a.date || ''), db = String(b.date || '');
108
+ if (da !== db) return da < db ? 1 : -1;
109
+ const o = num(a.order) - num(b.order);
110
+ if (o) return o < 0 ? -1 : 1;
111
+ return String(a.title).localeCompare(String(b.title));
112
+ });
113
+ }
114
+
115
+ // Names in src/ that an area path may not reuse. A page `demos.html|md` is the
116
+ // area's list page (with or without the `demos/` folder yet), so it does not
117
+ // count; a folder holding pages of its own (a blog) does, as does any other file.
118
+ function readSrcEntries(dir) {
119
+ let ents;
120
+ try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
121
+ const holdsPages = (name) => {
122
+ try {
123
+ return fs.readdirSync(path.join(dir, name), { withFileTypes: true })
124
+ .some(e => e.isFile() && /\.(html|md)$/.test(e.name) && e.name !== 'index.html');
125
+ } catch { return false; }
126
+ };
127
+ const out = new Set();
128
+ for (const e of ents) {
129
+ if (e.isDirectory()) { if (holdsPages(e.name)) out.add(e.name); }
130
+ else if (!/\.(html|md)$/.test(e.name)) out.add(e.name);
131
+ }
132
+ return [...out];
133
+ }
134
+
135
+ function load() {
136
+ const hasIndex = (area, slug) => fs.existsSync(path.join(srcPath, area, slug, 'index.html'));
137
+ return normalizePrograms(getPrograms(), { srcEntries: readSrcEntries(srcPath), buildOnlyPaths, hasIndex });
138
+ }
139
+
140
+ let areaPaths = [];
141
+
142
+ /** Every area whose subfolders are program folders: the valid ones and the colliding ones (R10). */
143
+ const protectedPaths = ({ areas, protectedAreas }) => [...areas, ...protectedAreas].map(a => a.path);
144
+
145
+ /** Compute the area list for this build (programsData calls it). */
146
+ export function loadProgramAreas() {
147
+ areaPaths = protectedPaths(load());
148
+ return areaPaths;
149
+ }
150
+
151
+ /** Valid area paths from the current config. */
152
+ export function programAreaPaths() {
153
+ return load().areas.map(a => a.path);
154
+ }
155
+
156
+ /**
157
+ * Is relPath (relative to src or dist, `/` separators) inside <area>/<sub>/?
158
+ * @param {string} relPath
159
+ */
160
+ export function isInProgram(relPath) {
161
+ if (!areaPaths.length || typeof relPath !== 'string') return false;
162
+ const parts = relPath.replace(/\\/g, '/').replace(/^\.?\/+/, '').split('/');
163
+ return parts.length >= 3 && areaPaths.includes(parts[0]);
164
+ }
165
+
166
+ /**
167
+ * Is filePath (as the build passes see it, e.g. `dist/demos/x/y.html`) inside a
168
+ * program folder? baseDir is the directory the path is relative to (dist, src).
169
+ * @param {string} filePath
170
+ * @param {string} baseDir
171
+ */
172
+ export function isProgramFile(filePath, baseDir) {
173
+ if (!areaPaths.length || typeof filePath !== 'string') return false;
174
+ return isInProgram(path.relative(baseDir, filePath).split(path.sep).join('/'));
175
+ }
176
+
177
+ /** Set `programs` and `programAreas` on the data store. */
178
+ export async function programsData({ data }) {
179
+ const loaded = load();
180
+ const { areas, programs, warnings } = loaded;
181
+ areaPaths = protectedPaths(loaded);
182
+ for (const w of warnings) console.log(chalk.yellow(w));
183
+ const shown = sortPrograms(programs.filter(p => p.listed === true && p.hasIndex))
184
+ .map(({ hasIndex, ...card }) => card);
185
+ data.programs = shown;
186
+ const byArea = Object.create(null);
187
+ for (const a of areas) byArea[a.path] = shown.filter(p => p.area === a.path);
188
+ data.programAreas = byArea;
189
+ }
190
+
191
+ const SANDBOX_RULE = 'Content-Security-Policy: sandbox allow-scripts allow-forms allow-popups allow-pointer-lock allow-modals';
192
+
193
+ /**
194
+ * Cloudflare Pages / Netlify `_headers` text: the site's own rules, then a
195
+ * sandbox block for each sandboxed program (listed or not), in program order.
196
+ * @param {Array<{area: string, slug: string, sandbox?: boolean}>} programs
197
+ * @param {string|null} existing - The site's own `_headers` text, if any
198
+ * @returns {string|null} null when no program is sandboxed
199
+ */
200
+ export function programHeaders(programs, existing) {
201
+ const sandboxed = (programs || []).filter(p => p.sandbox === true);
202
+ if (!sandboxed.length) return null;
203
+ const blocks = sandboxed.map(p => `/${p.area}/${p.slug}/*\n ${SANDBOX_RULE}\n`).join('\n');
204
+ return existing ? `${existing}\n${blocks}` : blocks;
205
+ }
206
+
207
+ /**
208
+ * Programs (listed and unlisted) from the current config, for `_headers`: the valid ones,
209
+ * then those in a colliding area (R10), whose sandbox rule must still be written.
210
+ */
211
+ export function allPrograms() {
212
+ const { programs, protectedPrograms } = load();
213
+ return [...programs, ...protectedPrograms];
214
+ }
@@ -22,6 +22,7 @@
22
22
  import chalk from 'chalk';
23
23
  import Util from '../utils/util/util.js';
24
24
  import { renderTemplate as interpolate, getNested } from '../utils/interpolate/interpolate.js';
25
+ import { applyConditionals, isSet } from '../utils/layouts/conditionals.js';
25
26
 
26
27
  // Config
27
28
  import { repeat as repeatConfig } from '../utils/config/config.js';
@@ -111,8 +112,9 @@ class RepeatCollection {
111
112
  * @param {Element} element - The element with data-repeat
112
113
  * @param {Document} document - The document object
113
114
  * @param {Object} outerContext - Enclosing iteration context (loop vars)
115
+ * @param {string[]} [outerAliases] - Loop variable names of enclosing repeats
114
116
  */
115
- processRepeatElement(element, document, outerContext = {}) {
117
+ processRepeatElement(element, document, outerContext = {}, outerAliases = []) {
116
118
  const expression = element.getAttribute(this.config.attribute);
117
119
  if (!expression) return;
118
120
 
@@ -156,6 +158,10 @@ class RepeatCollection {
156
158
  // Create a document fragment to hold all repeated elements
157
159
  const fragment = document.createDocumentFragment();
158
160
 
161
+ // Loop variable names visible inside this repeat: data-if/data-unless
162
+ // keys under one of them (`post.image`) are decided per item here
163
+ const aliases = [...outerAliases, parsed.itemName, ...(parsed.indexName ? [parsed.indexName] : [])];
164
+
159
165
  // Generate repeated elements
160
166
  collection.forEach((item, index) => {
161
167
  // Clone the original element
@@ -179,8 +185,13 @@ class RepeatCollection {
179
185
  context[parsed.indexName] = index;
180
186
  }
181
187
 
182
- // Replace template variables in the content
183
- const renderedContent = this.renderTemplate(template, context);
188
+ // The element's own data-if/data-unless on a loop variable: decide it
189
+ if (!this.keepForItem(clone, aliases, context)) return;
190
+
191
+ // data-if/data-unless on loop variables inside the item, then
192
+ // replace template variables in the content
193
+ const itemTemplate = this.applyItemConditionals(template, aliases, context);
194
+ const renderedContent = this.renderTemplate(itemTemplate, context);
184
195
  clone.innerHTML = renderedContent;
185
196
 
186
197
  // Also process attributes on the clone itself
@@ -188,7 +199,7 @@ class RepeatCollection {
188
199
 
189
200
  // Recursively expand nested data-repeat elements with this
190
201
  // iteration's context, so they can loop over loop variables
191
- this.processNestedRepeats(clone, document, context);
202
+ this.processNestedRepeats(clone, document, context, aliases);
192
203
 
193
204
  fragment.appendChild(clone);
194
205
  });
@@ -203,8 +214,9 @@ class RepeatCollection {
203
214
  * @param {Element} container - The clone to search within
204
215
  * @param {Document} document - The document object
205
216
  * @param {Object} context - The iteration context of the enclosing loop
217
+ * @param {string[]} aliases - Loop variable names of the enclosing loops
206
218
  */
207
- processNestedRepeats(container, document, context) {
219
+ processNestedRepeats(container, document, context, aliases) {
208
220
  const nested = Array.from(container.querySelectorAll(`[${this.config.attribute}]`))
209
221
  .filter(el => {
210
222
  // Keep only repeats whose nearest repeat ancestor is the container
@@ -216,8 +228,58 @@ class RepeatCollection {
216
228
  return true;
217
229
  });
218
230
  for (const el of nested) {
219
- this.processRepeatElement(el, document, context);
231
+ this.processRepeatElement(el, document, context, aliases);
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Lookup for data-if/data-unless inside a repeated item: keys under a
237
+ * loop variable are known (from the iteration context); any other key
238
+ * is left for the late pass.
239
+ * @param {string[]} aliases
240
+ * @param {Object} context
241
+ * @returns {(key: string) => { known: boolean, value?: any }}
242
+ */
243
+ itemLookup(aliases, context) {
244
+ return (key) => (aliases.includes(key.split('.')[0])
245
+ ? { known: true, value: this.getNestedValue(context, key) }
246
+ : { known: false });
247
+ }
248
+
249
+ /**
250
+ * Apply data-if/data-unless on loop variables to an item's template.
251
+ * Returns the template itself when it has neither marker.
252
+ * @param {string} template
253
+ * @param {string[]} aliases
254
+ * @param {Object} context
255
+ * @returns {string}
256
+ */
257
+ applyItemConditionals(template, aliases, context) {
258
+ return applyConditionals(template, this.itemLookup(aliases, context));
259
+ }
260
+
261
+ /**
262
+ * Decide the repeated element's own data-if/data-unless when its key is
263
+ * a loop variable: false drops this item; true strips the attribute.
264
+ * Other keys stay for the late pass.
265
+ * @param {Element} clone
266
+ * @param {string[]} aliases
267
+ * @param {Object} context
268
+ * @returns {boolean} Whether the item is kept
269
+ */
270
+ keepForItem(clone, aliases, context) {
271
+ const lookup = this.itemLookup(aliases, context);
272
+ for (const name of ['data-if', 'data-unless']) {
273
+ if (!clone.hasAttribute(name)) continue;
274
+ const key = clone.getAttribute(name).trim();
275
+ if (!key) continue;
276
+ const result = lookup(key);
277
+ if (!result.known) continue;
278
+ const set = isSet(result.value);
279
+ if (name === 'data-if' ? !set : set) return false;
280
+ clone.removeAttribute(name);
220
281
  }
282
+ return true;
221
283
  }
222
284
 
223
285
  /**
@@ -14,6 +14,22 @@ import Util from '../utils/util/util.js';
14
14
  import { convertPageToDirectory, distPath, srcPath } from '../utils/config/config.js';
15
15
 
16
16
 
17
+ // A format-1 fragment's leading marker (see utils/layouts/list.js) and the
18
+ // line break after it. It is for `cook check-layouts`, not for the page.
19
+ const FRAGMENT_MARKER = /^(\s*)<!--\s*layout-fragment\s*-->[ \t]*\r?\n?/;
20
+
21
+ /**
22
+ * Remove a leading `<!-- layout-fragment -->` marker from include content.
23
+ * Content without the marker is returned as is.
24
+ * @param {string} content
25
+ * @returns {string}
26
+ */
27
+ function stripFragmentMarker(content) {
28
+ if (typeof content !== 'string' || !content.includes('layout-fragment')) return content;
29
+ return content.replace(FRAGMENT_MARKER, '$1');
30
+ }
31
+
32
+
17
33
  // DEFINE
18
34
  // -----------------------------
19
35
  /**
@@ -139,6 +155,7 @@ class ReplaceInclude {
139
155
  console.warn(chalk.yellow(` [include] Not found: "${filePath}" referenced in ${this.file.path}`));
140
156
  content = `<!-- cook:include-not-found ${filePath} -->`;
141
157
  }
158
+ content = stripFragmentMarker(content);
142
159
  src = src.substring(0, match.index) + content + src.substring(match.index + match[0].length);
143
160
  onReplace();
144
161
  }
@@ -195,7 +212,7 @@ class ReplaceInclude {
195
212
  // ADD CONTENT TO DOM
196
213
  // Replace the include element with the fetched content using outerHTML.
197
214
  // This keeps content in the correct DOM context (e.g., <head> stays in <head>).
198
- el.outerHTML = content;
215
+ el.outerHTML = stripFragmentMarker(content);
199
216
  }
200
217
  catch (err) {
201
218
  Util.customWarn(err, `replace-includes.js: ${this.file.path}`);
@@ -35,6 +35,20 @@ function getTheme() {
35
35
  }
36
36
  }
37
37
 
38
+ // config/programs.json (written by Vanilla Press): areas of hand-written programs and their cards
39
+ const programsJsonPath = `${cwd}/config/programs.json`;
40
+
41
+ /** The programs config. Re-read on every call, like getTheme. */
42
+ function getPrograms() {
43
+ if (!fs.existsSync(programsJsonPath)) return undefined;
44
+ try {
45
+ return JSON.parse(fs.readFileSync(programsJsonPath, 'utf8'));
46
+ } catch (err) {
47
+ console.log(chalk.yellow(`[programs] config/programs.json: ${err.message}`));
48
+ return undefined;
49
+ }
50
+ }
51
+
38
52
 
39
53
  // DEFINE DEFAULT CONFIG
40
54
  // -----------------------------
@@ -335,7 +349,7 @@ const config = mergeConfigs(defaultConfig, userConfig);
335
349
  export default config;
336
350
 
337
351
  // Named exports for destructuring imports
338
- export { getTheme };
352
+ export { getTheme, getPrograms };
339
353
  export const {
340
354
  activeLink,
341
355
  autoComponents,
@@ -8,6 +8,7 @@
8
8
  import fs from 'node:fs/promises';
9
9
  import Logger from '../logger/logger.js';
10
10
  import Util from '../util/util.js';
11
+ import { isProgramFile } from '../../plugins/programs.js';
11
12
  import { SourceFile } from '../source-file/source-file.js';
12
13
 
13
14
  // CONFIG
@@ -116,7 +117,8 @@ async function getSrcFiles() {
116
117
  const isValidPageChange = Util.validatePageChange();
117
118
  if (isValidPageChange) {
118
119
  const getDistVersionOfChangedPage = process.env.DEV_CHANGED_PAGE.replace(srcPath, distPath);
119
- files = [getDistVersionOfChangedPage];
120
+ // A file inside a program folder is only copied (copySrc), never built
121
+ files = isProgramFile(getDistVersionOfChangedPage, distPath) ? [] : [getDistVersionOfChangedPage];
120
122
  }
121
123
  // FULL BUILD
122
124
  // Otherwise, find all allowed files, loop through them, and run the build plugins on them
@@ -134,6 +136,8 @@ async function getSrcFiles() {
134
136
  files = Util.getPaths(distPath, distPath, excludedPaths);
135
137
  // Get only the allowed files by extension (.css, .html)
136
138
  files = files.filter(fileName => manualAllow(fileName, userAllowedPaths) || Util.isExtension(fileName, allowedExt));
139
+ // Program folders ship untouched
140
+ files = files.filter(fileName => !isProgramFile(fileName, distPath));
137
141
  // Move known include files to the front of the array, so they are ideally built first
138
142
  // before being replaced in other page files.
139
143
  files = files.sort((a,b) => {
@@ -164,7 +168,7 @@ async function getSrcImages(cb) {
164
168
  // Get images in `/dist`
165
169
  let images = Util.getPaths(distPath, distPath, excludedPaths);
166
170
  // Get only the allowed images by extension (.css, .html)
167
- images = images.filter(fileName => Util.isExtension(fileName, allowedExt));
171
+ images = images.filter(fileName => Util.isExtension(fileName, allowedExt) && !isProgramFile(fileName, distPath));
168
172
  // Run tasks on matched images
169
173
  if (cb) cb(images);
170
174
  }