cook-ssg 2.8.0 → 2.9.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cook-ssg",
3
- "version": "2.8.0",
3
+ "version": "2.9.0",
4
4
  "description": "Cook your static pages into a beautifully performing site. Static site generation the web platform way.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,9 +1,13 @@
1
1
  /**
2
2
  * @file layouts.js
3
3
  * @description Public entry point (`cook-ssg/layouts`): the layout checker,
4
- * the layout lister and the format constants.
4
+ * the layout lister, the layout tree (parse and serialize) and the format
5
+ * constants.
5
6
  */
6
7
 
7
8
  export { checkLayout } from './utils/layouts/check.js';
8
9
  export { listLayouts, loadSiteNames } from './utils/layouts/list.js';
10
+ export { parseLayout } from './utils/layouts/tree.js';
11
+ export { serializeLayout } from './utils/layouts/serialize.js';
12
+ export { layoutUsage } from './utils/layouts/usage.js';
9
13
  export { FORMAT, PAGE_LAYOUTS, DOCUMENT_FIELDS } from './utils/layouts/vocabulary.js';
@@ -13,16 +13,18 @@ import {
13
13
  } from './vocabulary.js';
14
14
 
15
15
  // `${…}` placeholders, including `${{…}}` so expressions are caught
16
- const PLACEHOLDER = /\$\{([^}]*)\}/g;
17
- const PLAIN_KEY = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/;
18
- const SLOT_KEY = /^slot:([\w-]+)$/;
16
+ export const PLACEHOLDER = /\$\{([^}]*)\}/g;
17
+ export const PLAIN_KEY = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/;
18
+ export const SLOT_KEY = /^slot:([\w-]+)$/;
19
19
  // "source | pipe:arg as item[, index]" (same grammar as repeat-collection)
20
- const REPEAT = /^(.+?)\s+as\s+(\w+)(?:\s*,\s*(\w+))?$/;
20
+ export const REPEAT = /^(.+?)\s+as\s+(\w+)(?:\s*,\s*(\w+))?$/;
21
21
  const PIPE = /^(limit|offset)\s*:\s*\d+$/;
22
22
  const PAGE_LAYOUT_FIELD = '${pageLayout}';
23
23
 
24
- const tagOf = (el) => el.tagName.toLowerCase();
25
- const isBlank = (node) => node.nodeType === 8 || (node.nodeType === 3 && !node.textContent.trim());
24
+ export const tagOf = (el) => el.tagName.toLowerCase();
25
+ export const isBlank = (node) => node.nodeType === 8 || (node.nodeType === 3 && !node.textContent.trim());
26
+ /** An include block: an empty `<div data-include>`. */
27
+ export const isIncludeElement = (el) => tagOf(el) === 'div' && el.hasAttribute('data-include');
26
28
 
27
29
  /**
28
30
  * Best-effort scan for slots and fields, used for every layout (plain or
@@ -380,7 +382,7 @@ class Checker {
380
382
  }
381
383
 
382
384
  isInclude(el) {
383
- return tagOf(el) === 'div' && el.hasAttribute('data-include');
385
+ return isIncludeElement(el);
384
386
  }
385
387
 
386
388
  include(el, ctx) {
@@ -0,0 +1,155 @@
1
+ /**
2
+ * @file serialize.js
3
+ * @description Write a layout tree (see tree.js) as canonical format-1 HTML:
4
+ * two-space indent, one block per line, the info block first as pretty
5
+ * JSON, double-quoted attributes in a fixed order (data-template,
6
+ * data-page-layout, the rest as the tree has them, then data-repeat,
7
+ * data-if, data-unless), text blocks on one line. Component inner HTML,
8
+ * comments, picture sources and inline script and style text are written
9
+ * exactly as the tree holds them.
10
+ */
11
+
12
+ const INDENT = ' ';
13
+
14
+ const escapeAttr = (value) => String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
15
+ const escapeMarkup = (text) => text
16
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\u00a0/g, '&nbsp;');
17
+ // A text run is literal: a `${` in it must not become a placeholder
18
+ const escapeText = (text) => escapeMarkup(text).replace(/\$\{/g, '&#36;{');
19
+
20
+ /** ` name="value"` for each pair. */
21
+ const attrString = (pairs) => pairs.map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join('');
22
+
23
+ /** A data-repeat value from its parts. */
24
+ function repeatValue({ source, pipes = [], alias, index }) {
25
+ return `${[source, ...pipes].join(' | ')} as ${alias}${index ? `, ${index}` : ''}`;
26
+ }
27
+
28
+ /**
29
+ * The attributes of a block or item, in canonical order.
30
+ * @param {Object} node - has `attrs` and optional `repeat`, `if`, `unless`
31
+ * @param {Array<[string, string]>} [lead] - attributes that go first
32
+ */
33
+ function blockAttrs(node, lead = []) {
34
+ const pairs = [...lead, ...(node.attrs || [])];
35
+ if (node.repeat) pairs.push(['data-repeat', repeatValue(node.repeat)]);
36
+ if (node.if !== undefined) pairs.push(['data-if', node.if]);
37
+ if (node.unless !== undefined) pairs.push(['data-unless', node.unless]);
38
+ return attrString(pairs);
39
+ }
40
+
41
+ /** The info block's lines, JSON indented with the script. */
42
+ function infoLines(info, indent) {
43
+ const json = JSON.stringify(info, null, 2).replace(/</g, '\\u003c');
44
+ return [
45
+ `${indent}<script type="application/json" data-layout-info>`,
46
+ ...json.split('\n').map(line => indent + line),
47
+ `${indent}</script>`,
48
+ ];
49
+ }
50
+
51
+ // INLINE
52
+ // -----------------------------
53
+ function inlineHtml(runs = []) {
54
+ return runs.map((run) => {
55
+ if ('field' in run) return `\${${run.field}}`;
56
+ if ('text' in run) return escapeText(run.text);
57
+ if ('component' in run) return `<${run.component}${attrString(run.attrs || [])}>${run.html ?? ''}</${run.component}>`;
58
+ const open = `<${run.tag}${attrString(run.attrs || [])}>`;
59
+ if (run.tag === 'br' || run.tag === 'img') return open;
60
+ return `${open}${inlineHtml(run.inline)}</${run.tag}>`;
61
+ }).join('');
62
+ }
63
+
64
+ // HEAD
65
+ // -----------------------------
66
+ function headLine(item, indent) {
67
+ if (item.slot) return `${indent}\${slot:${item.slot}}`;
68
+ const open = `<${item.tag}${blockAttrs(item)}>`;
69
+ if (item.tag === 'title') return `${indent}${open}${escapeMarkup(item.text ?? '').replace(/&gt;/g, '>')}</title>`;
70
+ if (item.tag === 'script' || item.tag === 'style') return `${indent}${open}${item.text ?? ''}</${item.tag}>`;
71
+ return indent + open;
72
+ }
73
+
74
+ // BLOCKS
75
+ // -----------------------------
76
+ /** Open tag, children one level in, close tag; or one line when empty. */
77
+ function wrap(open, close, children, indent) {
78
+ if (children.length === 0) return [`${indent}${open}${close}`];
79
+ return [`${indent}${open}`, ...children, `${indent}${close}`];
80
+ }
81
+
82
+ function blockLines(block, indent) {
83
+ const inner = indent + INDENT;
84
+ switch (block.type) {
85
+ case 'content':
86
+ return [`${indent}\${content}`];
87
+ case 'slot':
88
+ return [`${indent}\${slot:${block.name}}`];
89
+ case 'comment':
90
+ return [`${indent}<!--${block.text}-->`];
91
+ case 'text':
92
+ return [`${indent}<${block.tag}${blockAttrs(block)}>${inlineHtml(block.inline)}</${block.tag}>`];
93
+ case 'image':
94
+ if (block.tag === 'picture') return [`${indent}<picture${blockAttrs(block)}>${block.html ?? ''}</picture>`];
95
+ return [`${indent}<img${blockAttrs(block)}>`];
96
+ case 'container':
97
+ return wrap(`<${block.tag}${blockAttrs(block)}>`, `</${block.tag}>`, blocksLines(block.body, inner), indent);
98
+ case 'menu':
99
+ return wrap(`<${block.tag}${blockAttrs(block)}>`, `</${block.tag}>`,
100
+ (block.items || []).flatMap(item => itemLines(item, inner)), indent);
101
+ case 'include':
102
+ return [`${indent}<div${blockAttrs(block, [['data-include', block.path]])}></div>`];
103
+ case 'component':
104
+ return [`${indent}<${block.tag}${blockAttrs(block)}>${block.html ?? ''}</${block.tag}>`];
105
+ default:
106
+ throw new Error(`serializeLayout: unknown block type "${block.type}"`);
107
+ }
108
+ }
109
+
110
+ function itemLines(item, indent) {
111
+ const open = `<li${blockAttrs(item)}>`;
112
+ if (item.body) return wrap(open, '</li>', blocksLines(item.body, indent + INDENT), indent);
113
+ return [`${indent}${open}${inlineHtml(item.inline)}</li>`];
114
+ }
115
+
116
+ const blocksLines = (blocks = [], indent) => blocks.flatMap(block => blockLines(block, indent));
117
+
118
+ function slotLines(slot, indent) {
119
+ const open = `<template${blockAttrs(slot, [['slot', slot.name]])}>`;
120
+ const children = slot.name === 'head'
121
+ ? (slot.body || []).map(item => headLine(item, indent + INDENT))
122
+ : blocksLines(slot.body, indent + INDENT);
123
+ return wrap(open, '</template>', children, indent);
124
+ }
125
+
126
+ /**
127
+ * Write a layout tree as canonical format-1 HTML.
128
+ * @param {Object} tree - A tree from parseLayout (or edited from one)
129
+ * @returns {string}
130
+ */
131
+ export function serializeLayout(tree) {
132
+ const lines = [];
133
+ if (tree.kind === 'base') {
134
+ lines.push('<!doctype html>', `<html${attrString(tree.htmlAttrs || [])}>`, '<head>');
135
+ if (tree.info) lines.push(...infoLines(tree.info, INDENT));
136
+ lines.push(...(tree.head || []).map(item => headLine(item, INDENT)), '</head>');
137
+ const body = [];
138
+ if (tree.pageLayout !== null && tree.pageLayout !== undefined) body.push(['data-page-layout', tree.pageLayout]);
139
+ lines.push(`<body${attrString(body)}>`, ...blocksLines(tree.body, INDENT), '</body>', '</html>');
140
+ } else if (tree.kind === 'child') {
141
+ // Variables are raw strings, as render.js reads them: only `"` is escaped
142
+ const vars = (tree.vars || []).map(([name, value]) =>
143
+ ` data-${name.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}="${String(value).replace(/"/g, '&quot;')}"`).join('');
144
+ const pageLayout = tree.pageLayout !== null && tree.pageLayout !== undefined
145
+ ? ` data-page-layout="${String(tree.pageLayout).replace(/"/g, '&quot;')}"` : '';
146
+ lines.push(`<body data-template="${escapeAttr(tree.parent ?? '')}"${pageLayout}${vars}>`);
147
+ if (tree.info) lines.push(...infoLines(tree.info, INDENT));
148
+ lines.push(...blocksLines(tree.body, INDENT));
149
+ for (const slot of tree.slots || []) lines.push(...slotLines(slot, INDENT));
150
+ lines.push('</body>');
151
+ } else {
152
+ lines.push('<!-- layout-fragment -->', ...blocksLines(tree.body, ''));
153
+ }
154
+ return `${lines.join('\n')}\n`;
155
+ }
@@ -0,0 +1,522 @@
1
+ /**
2
+ * @file tree.js
3
+ * @description Parse a correct format-1 layout (or include fragment) into a
4
+ * layout tree: plain JSON that an editor can change and `serializeLayout`
5
+ * can write back. Only layouts that `checkLayout` passes get a tree; the
6
+ * walk follows the checker's classification block by block.
7
+ *
8
+ * What the tree keeps exactly as written comes from the raw source, not the
9
+ * DOM: a component's inner HTML, a picture's sources, and the text of inline
10
+ * scripts and styles. Comments become comment blocks where a block may
11
+ * stand. A correct layout holding something the tree has no place for (a
12
+ * comment in <head>, a comment inside a text block, …) is refused with a
13
+ * problem rather than opened with that part lost.
14
+ */
15
+
16
+ import { parseLayoutSource, childrenOf } from './parse.js';
17
+ import {
18
+ checkLayout, PLACEHOLDER, SLOT_KEY, REPEAT, tagOf, isIncludeElement,
19
+ } from './check.js';
20
+ import {
21
+ TEXT_ELEMENTS, INLINE_ELEMENTS, CONTAINER_ELEMENTS, LAYOUT_WRAPPERS, MENU_ELEMENTS,
22
+ LAYOUT_ELEMENTS,
23
+ } from './vocabulary.js';
24
+ import { findTemplatedTag, templateDataAttrs } from './render.js';
25
+
26
+ const RAW_TEXT = new Set(['script', 'style', 'textarea', 'title']);
27
+ // Comments, declarations, and start/end tags whose attributes may quote `>`
28
+ const TOKEN = /<!--[\s\S]*?(?:-->|$)|<![^>]*>|<(\/?)([a-zA-Z][a-zA-Z0-9-]*)(?:"[^"]*"|'[^']*'|[^>"'])*>/g;
29
+ const FRAGMENT_MARKER = /^\s*<!--\s*layout-fragment\s*-->/;
30
+ const MARKER_TEXT = /^\s*layout-fragment\s*$/;
31
+ const SPACE = /[ \t\n\r\f]+/g;
32
+ // A character reference for `$` or `{`: decoded, it could read as `${…}`
33
+ const ENCODED_PLACEHOLDER = /&(?:#0*36|#x0*24|dollar|#0*123|#x0*7b|lbrace|lcub)(?![\w])/i;
34
+ // One attribute in a start tag, any quoting (as render.js reads them)
35
+ const ATTR = /([^\s"'>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
36
+ const camel = (attr) => attr.slice('data-'.length).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
37
+
38
+ const BLOCK_ATTRS = ['data-repeat', 'data-if', 'data-unless'];
39
+
40
+ // SOURCE OFFSETS
41
+ // -----------------------------
42
+ /**
43
+ * Every start and end tag in the source, in order. Comments and the raw
44
+ * text of script, style, textarea and title are skipped.
45
+ * @param {string} html
46
+ * @returns {Array<{ name: string, close: boolean, start: number, end: number }>}
47
+ */
48
+ function scanTags(html) {
49
+ const lower = html.toLowerCase();
50
+ const tags = [];
51
+ TOKEN.lastIndex = 0;
52
+ let m;
53
+ while ((m = TOKEN.exec(html))) {
54
+ if (!m[2]) continue;
55
+ const name = m[2].toLowerCase();
56
+ const close = m[1] === '/';
57
+ tags.push({ name, close, start: m.index, end: TOKEN.lastIndex });
58
+ if (!close && RAW_TEXT.has(name)) {
59
+ const at = lower.indexOf(`</${name}`, TOKEN.lastIndex);
60
+ TOKEN.lastIndex = at === -1 ? html.length : at;
61
+ }
62
+ }
63
+ return tags;
64
+ }
65
+
66
+ /**
67
+ * Pair each element, in document order, with the next unused start tag of
68
+ * the same name (as parse.js does for lines), so an element's raw inner
69
+ * HTML can be sliced from the source.
70
+ * @param {string} html
71
+ * @param {Element} root
72
+ * @returns {{ inner: (el: Element) => string|null, openTag: (el: Element) => string|null }}
73
+ * the raw inner source and the raw start tag, or null when unpaired
74
+ */
75
+ function sourceIndex(html, root) {
76
+ const tags = scanTags(html);
77
+ const starts = new Map();
78
+ tags.forEach((tag, i) => {
79
+ if (tag.close) return;
80
+ if (!starts.has(tag.name)) starts.set(tag.name, []);
81
+ starts.get(tag.name).push(i);
82
+ });
83
+
84
+ const index = new WeakMap();
85
+ const used = new Map();
86
+ const visit = (el) => {
87
+ const name = tagOf(el);
88
+ const queue = starts.get(name) || [];
89
+ const next = used.get(name) || 0;
90
+ if (next < queue.length) {
91
+ index.set(el, queue[next]);
92
+ used.set(name, next + 1);
93
+ }
94
+ for (const node of childrenOf(el)) if (node.nodeType === 1) visit(node);
95
+ };
96
+ visit(root);
97
+
98
+ const openTag = (el) => {
99
+ const i = index.get(el);
100
+ return i === undefined ? null : html.slice(tags[i].start, tags[i].end);
101
+ };
102
+ const inner = (el) => {
103
+ const i = index.get(el);
104
+ if (i === undefined) return null;
105
+ const open = tags[i];
106
+ let depth = 1;
107
+ for (let j = i + 1; j < tags.length; j++) {
108
+ if (tags[j].name !== open.name) continue;
109
+ depth += tags[j].close ? -1 : 1;
110
+ if (depth === 0) return html.slice(open.end, tags[j].start);
111
+ }
112
+ return null;
113
+ };
114
+ return { inner, openTag };
115
+ }
116
+
117
+ // HELPERS
118
+ // -----------------------------
119
+ const isComponent = (el) => tagOf(el).includes('-') && !LAYOUT_ELEMENTS.includes(tagOf(el));
120
+
121
+ const attrList = (el, skip = []) => Array.from(el.attributes)
122
+ .filter(a => !skip.includes(a.name.toLowerCase()))
123
+ .map(a => [a.name, a.value]);
124
+
125
+ /**
126
+ * Read a data-repeat expression the way the checker does.
127
+ * @param {string} expr
128
+ * @returns {{ source: string, pipes: string[], alias: string, index?: string }}
129
+ */
130
+ function parseRepeat(expr) {
131
+ const match = expr.trim().match(REPEAT);
132
+ const [source, ...pipes] = match[1].split('|').map(p => p.trim());
133
+ const repeat = { source, pipes, alias: match[2] };
134
+ if (match[3]) repeat.index = match[3];
135
+ return repeat;
136
+ }
137
+
138
+ /** Conditions on an element: `{ if?, unless? }`. */
139
+ function conditions(el) {
140
+ const out = {};
141
+ if (el.hasAttribute('data-if')) out.if = el.getAttribute('data-if');
142
+ if (el.hasAttribute('data-unless')) out.unless = el.getAttribute('data-unless');
143
+ return out;
144
+ }
145
+
146
+ /**
147
+ * Text with fields: split into `{ text }` and `{ field }` runs, whitespace
148
+ * collapsed.
149
+ * @param {string} text - decoded text
150
+ * @returns {Array<{ text: string }|{ field: string }>}
151
+ */
152
+ function textRuns(text) {
153
+ const runs = [];
154
+ let pos = 0;
155
+ for (const match of text.matchAll(PLACEHOLDER)) {
156
+ if (match.index > pos) runs.push({ text: text.slice(pos, match.index).replace(SPACE, ' ') });
157
+ runs.push({ field: match[1].trim() });
158
+ pos = match.index + match[0].length;
159
+ }
160
+ if (pos < text.length) runs.push({ text: text.slice(pos).replace(SPACE, ' ') });
161
+ return runs;
162
+ }
163
+
164
+ /** Merge adjacent text runs; trim the outer edges of a whole run list. */
165
+ function tidyRuns(runs, { trim }) {
166
+ const out = [];
167
+ for (const run of runs) {
168
+ const last = out.at(-1);
169
+ if ('text' in run && last && 'text' in last) last.text += run.text;
170
+ else out.push(run);
171
+ }
172
+ if (trim) {
173
+ const first = out[0];
174
+ if (first && 'text' in first) first.text = first.text.replace(/^ /, '');
175
+ const last = out.at(-1);
176
+ if (last && 'text' in last) last.text = last.text.replace(/ $/, '');
177
+ }
178
+ return out.filter(run => !('text' in run) || run.text !== '');
179
+ }
180
+
181
+ // BUILDER
182
+ // -----------------------------
183
+ class TreeBuilder {
184
+ constructor(html, parsed) {
185
+ this.html = html;
186
+ this.parsed = parsed;
187
+ this.document = parsed.document;
188
+ this.source = sourceIndex(html, this.document.documentElement);
189
+ this.problems = [];
190
+ this.keptComments = new Set();
191
+ this.rawElements = new Set();
192
+ }
193
+
194
+ refuse(el, message) {
195
+ this.problems.push({ line: this.parsed.lineOf(el), message });
196
+ }
197
+
198
+ raw(el) {
199
+ this.rawElements.add(el);
200
+ const inner = this.source.inner(el);
201
+ return inner ?? el.innerHTML;
202
+ }
203
+
204
+ build() {
205
+ const { kind } = this.parsed;
206
+ const tree = {
207
+ kind,
208
+ info: this.info(),
209
+ parent: kind === 'child' ? this.parsed.parent : null,
210
+ vars: [],
211
+ pageLayout: null,
212
+ htmlAttrs: [],
213
+ head: [],
214
+ body: [],
215
+ slots: [],
216
+ };
217
+ if (kind === 'base') this.base(tree);
218
+ else if (kind === 'child') this.child(tree);
219
+ else tree.body = this.blocks(this.document.body, { skipMarker: FRAGMENT_MARKER.test(this.html) });
220
+ this.sweepComments();
221
+ this.sweepEncodedPlaceholders();
222
+ if (kind === 'child') this.checkVars();
223
+ return tree;
224
+ }
225
+
226
+ info() {
227
+ const raw = this.parsed.info;
228
+ if (!raw) return null;
229
+ const { format, label, description, abstract, slots, ...rest } = raw;
230
+ const info = { format, label: label ?? '' };
231
+ if (description !== undefined) info.description = description;
232
+ if (abstract !== undefined) info.abstract = abstract;
233
+ info.slots = slots ?? {};
234
+ return Object.assign(info, rest);
235
+ }
236
+
237
+ // ROOTS
238
+ // -----------------------------
239
+ base(tree) {
240
+ const { documentElement, head, body } = this.document;
241
+ tree.htmlAttrs = attrList(documentElement);
242
+ if (head && head.attributes.length) this.refuse(head, `<head> attributes can't be edited here (${head.attributes[0].name})`);
243
+ tree.head = head ? this.headItems(head) : [];
244
+
245
+ if (body.hasAttribute('data-page-layout')) tree.pageLayout = body.getAttribute('data-page-layout');
246
+ const extra = attrList(body, ['data-page-layout']);
247
+ if (extra.length) this.refuse(body, `<body> attributes besides data-page-layout can't be edited here (${extra.map(a => a[0]).join(', ')})`);
248
+
249
+ tree.body = this.blocks(body, { region: true });
250
+ }
251
+
252
+ child(tree) {
253
+ const { documentElement, body } = this.document;
254
+ const templated = documentElement.hasAttribute('data-template') ? documentElement : body;
255
+
256
+ // The body's variables, read as render.js reads them
257
+ const tag = findTemplatedTag(this.html);
258
+ const vars = tag
259
+ ? Object.entries(templateDataAttrs(tag.attrs))
260
+ : attrList(templated, ['data-template']).filter(([name]) => /^data-/.test(name))
261
+ .map(([name, value]) => [camel(name), value]);
262
+ this.templated = { el: templated, read: Boolean(tag), vars };
263
+ const pageLayout = vars.find(([name]) => name === 'pageLayout');
264
+ tree.pageLayout = pageLayout ? pageLayout[1] : null;
265
+ tree.vars = vars.filter(([name]) => name !== 'pageLayout');
266
+
267
+ for (const node of childrenOf(body)) {
268
+ if (node.nodeType === 1 && tagOf(node) === 'template') tree.slots.push(this.slotTemplate(node));
269
+ }
270
+ tree.body = this.blocks(body, { skipTemplates: true });
271
+ }
272
+
273
+ slotTemplate(template) {
274
+ const slot = {
275
+ name: template.getAttribute('slot').trim(),
276
+ attrs: attrList(template, ['slot', 'data-if', 'data-unless']),
277
+ ...conditions(template),
278
+ };
279
+ slot.body = slot.name === 'head' ? this.headItems(template, { slotHead: true }) : this.blocks(template);
280
+ return slot;
281
+ }
282
+
283
+ // HEAD
284
+ // -----------------------------
285
+ headItems(parent, { slotHead = false } = {}) {
286
+ const items = [];
287
+ for (const node of childrenOf(parent)) {
288
+ if (node.nodeType === 3) {
289
+ if (!slotHead && node.textContent.trim() === '${slot:head}') items.push({ slot: 'head' });
290
+ continue;
291
+ }
292
+ if (node.nodeType !== 1 || node.hasAttribute('data-layout-info')) continue;
293
+ items.push(this.headItem(node));
294
+ }
295
+ return items;
296
+ }
297
+
298
+ headItem(el) {
299
+ const tag = tagOf(el);
300
+ const item = { tag, attrs: attrList(el, ['data-if', 'data-unless']), ...conditions(el) };
301
+ if (tag === 'title') item.text = el.textContent;
302
+ else if (tag === 'script' || tag === 'style') item.text = this.raw(el);
303
+ return item;
304
+ }
305
+
306
+ // BLOCKS
307
+ // -----------------------------
308
+ /**
309
+ * The blocks inside a block container. Placeholders in text become
310
+ * content and slot blocks; comments become comment blocks.
311
+ */
312
+ blocks(parent, { region = false, skipTemplates = false, skipMarker = false } = {}) {
313
+ const out = [];
314
+ let first = true;
315
+ for (const node of childrenOf(parent)) {
316
+ if (node.nodeType === 3) {
317
+ for (const match of node.textContent.matchAll(PLACEHOLDER)) {
318
+ const key = match[1].trim();
319
+ const slot = key.match(SLOT_KEY);
320
+ if (key === 'content') out.push({ type: 'content', attrs: [] });
321
+ else if (slot) out.push({ type: 'slot', name: slot[1], attrs: [] });
322
+ }
323
+ if (node.textContent.trim()) first = false;
324
+ continue;
325
+ }
326
+ if (node.nodeType === 8) {
327
+ this.keptComments.add(node);
328
+ if (!(skipMarker && first && MARKER_TEXT.test(node.data))) {
329
+ out.push({ type: 'comment', attrs: [], text: node.data });
330
+ }
331
+ first = false;
332
+ continue;
333
+ }
334
+ first = false;
335
+ if (node.nodeType !== 1) continue;
336
+ if (node.hasAttribute('data-layout-info') && tagOf(node) === 'script') continue;
337
+ if (skipTemplates && tagOf(node) === 'template') continue;
338
+ if (region && tagOf(node) === 'main') out.push(this.container(node));
339
+ else out.push(this.block(node));
340
+ }
341
+ return out;
342
+ }
343
+
344
+ /** Common fields: attributes (block attributes excepted), conditions, repeat. */
345
+ common(el, skip = []) {
346
+ const out = { attrs: attrList(el, [...BLOCK_ATTRS, ...skip]), ...conditions(el) };
347
+ if (el.hasAttribute('data-repeat')) out.repeat = parseRepeat(el.getAttribute('data-repeat'));
348
+ return out;
349
+ }
350
+
351
+ block(el) {
352
+ const name = tagOf(el);
353
+ if (name.includes('-')) {
354
+ if (LAYOUT_ELEMENTS.includes(name)) return this.container(el);
355
+ return { type: 'component', tag: name, ...this.common(el), html: this.raw(el) };
356
+ }
357
+ if (isIncludeElement(el)) {
358
+ return { type: 'include', path: el.getAttribute('data-include'), ...this.common(el, ['data-include']) };
359
+ }
360
+ if (MENU_ELEMENTS.includes(name)) return this.menu(el);
361
+ if (TEXT_ELEMENTS.includes(name)) {
362
+ return { type: 'text', tag: name, ...this.common(el), inline: this.inline(el, true) };
363
+ }
364
+ if (name === 'img') return { type: 'image', tag: 'img', ...this.common(el) };
365
+ if (name === 'picture') return { type: 'image', tag: 'picture', ...this.common(el), html: this.raw(el) };
366
+ // figure, sectioning, header/footer, div[data-layout]
367
+ return this.container(el);
368
+ }
369
+
370
+ container(el) {
371
+ return { type: 'container', tag: tagOf(el), ...this.common(el), body: this.blocks(el) };
372
+ }
373
+
374
+ menu(el) {
375
+ const items = [];
376
+ for (const node of childrenOf(el)) {
377
+ if (node.nodeType === 1) items.push(this.item(node));
378
+ }
379
+ return { type: 'menu', tag: tagOf(el), ...this.common(el), items };
380
+ }
381
+
382
+ /** An `li`: text-level content, or blocks, never both. */
383
+ item(li) {
384
+ const item = this.common(li);
385
+ let text = false;
386
+ let blocks = false;
387
+ let components = false;
388
+ for (const node of childrenOf(li)) {
389
+ if (node.nodeType === 3 && node.textContent.trim()) text = true;
390
+ else if (node.nodeType === 1 && INLINE_ELEMENTS.includes(tagOf(node))) text = true;
391
+ else if (node.nodeType === 1 && isComponent(node)) components = true;
392
+ else if (node.nodeType === 1) blocks = true;
393
+ }
394
+ // Components alone are blocks; beside text they are inline components
395
+ if (components && !text) blocks = true;
396
+ if (text && blocks) {
397
+ this.refuse(li, 'an <li> that mixes text and blocks can\'t be edited here (wrap the text in a <p>, or move the blocks out)');
398
+ item.inline = [];
399
+ } else if (blocks) {
400
+ item.body = this.blocks(li);
401
+ } else {
402
+ item.inline = this.inline(li, true);
403
+ }
404
+ return item;
405
+ }
406
+
407
+ // INLINE
408
+ // -----------------------------
409
+ inline(el, top = false) {
410
+ const runs = [];
411
+ for (const node of childrenOf(el)) {
412
+ if (node.nodeType === 3) runs.push(...textRuns(node.textContent));
413
+ else if (node.nodeType !== 1) continue; // comments: reported by the sweep
414
+ else if (INLINE_ELEMENTS.includes(tagOf(node))) {
415
+ const tag = tagOf(node);
416
+ if (tag === 'br' || tag === 'img') runs.push({ tag, attrs: attrList(node) });
417
+ else runs.push({ tag, attrs: attrList(node), inline: this.inline(node) });
418
+ } else {
419
+ // The checker allows only components here: kept whole, like a block component
420
+ runs.push({ component: tagOf(node), attrs: attrList(node), html: this.raw(node) });
421
+ }
422
+ }
423
+ return tidyRuns(runs, { trim: top });
424
+ }
425
+
426
+ // SOURCE CHECKS
427
+ // -----------------------------
428
+ /**
429
+ * Refuse an attribute whose source spells `$` or `{` as a character
430
+ * reference: the tree holds decoded values, and written back the value
431
+ * would become a live `${…}` placeholder. A title is checked the same way.
432
+ */
433
+ sweepEncodedPlaceholders() {
434
+ const visit = (el) => {
435
+ const open = this.source.openTag(el);
436
+ if (open && ENCODED_PLACEHOLDER.test(open)) {
437
+ ATTR.lastIndex = open.indexOf(' ') === -1 ? open.length : open.indexOf(' ');
438
+ let m;
439
+ while ((m = ATTR.exec(open))) {
440
+ const value = m[2] ?? m[3] ?? m[4] ?? '';
441
+ if (ENCODED_PLACEHOLDER.test(value)) {
442
+ this.refuse(el, `the ${m[1]} attribute of <${tagOf(el)}> spells $ or { as a character reference, which the layout editor can't keep; write it plainly`);
443
+ }
444
+ }
445
+ }
446
+ if (tagOf(el) === 'title' && ENCODED_PLACEHOLDER.test(this.source.inner(el) ?? '')) {
447
+ this.refuse(el, '<title> spells $ or { as a character reference, which the layout editor can\'t keep; write it plainly');
448
+ }
449
+ if (this.rawElements.has(el)) return;
450
+ for (const node of childrenOf(el)) if (node.nodeType === 1) visit(node);
451
+ };
452
+ visit(this.document.documentElement);
453
+ }
454
+
455
+ /**
456
+ * Refuse a child's body variables unless render.js reads each one exactly
457
+ * as the DOM does (a `>` or `"` in a value, or a character reference,
458
+ * would be lost or changed on the way back).
459
+ */
460
+ checkVars() {
461
+ const { el, read, vars } = this.templated;
462
+ if (!read) {
463
+ this.refuse(el, 'the data-template tag can\'t be read the way Cook renders it');
464
+ return;
465
+ }
466
+ const raw = new Map(vars);
467
+ const dom = new Map();
468
+ const names = new Map();
469
+ for (const { name, value } of Array.from(el.attributes)) {
470
+ const lower = name.toLowerCase();
471
+ if (!lower.startsWith('data-') || lower === 'data-template') continue;
472
+ dom.set(camel(lower), value);
473
+ names.set(camel(lower), lower);
474
+ }
475
+ for (const key of new Set([...raw.keys(), ...dom.keys()])) {
476
+ // A `"` can't be written back inside the canonical double quotes
477
+ if (raw.get(key) !== dom.get(key) || dom.get(key).includes('"')) {
478
+ const attr = names.get(key) ?? `data-${key.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}`;
479
+ this.refuse(el, `the ${attr} value can't be kept by the layout editor (avoid >, " and character references in body variables)`);
480
+ }
481
+ }
482
+ }
483
+
484
+ // COMMENTS
485
+ // -----------------------------
486
+ /** Refuse any comment the tree didn't keep (outside raw-kept elements). */
487
+ sweepComments() {
488
+ const visit = (parent, owner) => {
489
+ const holder = parent.nodeType === 1 ? childrenOf(parent) : Array.from(parent.childNodes);
490
+ for (const node of holder) {
491
+ if (node.nodeType === 8 && !this.keptComments.has(node)) {
492
+ this.refuse(owner, `a comment here can't be kept by the layout editor (<!--${node.data.slice(0, 30)}-->); move it between blocks or remove it`);
493
+ } else if (node.nodeType === 1 && !this.rawElements.has(node)) {
494
+ visit(node, node);
495
+ }
496
+ }
497
+ };
498
+ visit(this.document, this.document.documentElement);
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Parse a format-1 layout or include fragment into a layout tree.
504
+ * @param {string} html - The layout's source
505
+ * @param {Object} [opts]
506
+ * @property {boolean} [opts.fragment=false] - Parse the source as an include fragment
507
+ * @property {string[]} [opts.fields=[]] - Extra known field names (see checkLayout)
508
+ * @property {string[]} [opts.lists=[]] - Extra list-source roots (see checkLayout)
509
+ * @returns {{ ok: boolean, tree: Object|null, problems: Array<{ line: number, message: string }> }}
510
+ * `tree` only when the layout passes checkLayout and the tree can hold all of it
511
+ */
512
+ export function parseLayout(html, { fragment = false, fields = [], lists = [] } = {}) {
513
+ const check = checkLayout(html, { fragment, fields, lists });
514
+ if (!check.ok) return { ok: false, tree: null, problems: check.problems };
515
+
516
+ const builder = new TreeBuilder(html, parseLayoutSource(html, { fragment }));
517
+ const tree = builder.build();
518
+ if (builder.problems.length) {
519
+ return { ok: false, tree: null, problems: builder.problems.sort((a, b) => a.line - b.line) };
520
+ }
521
+ return { ok: true, tree, problems: [] };
522
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @file usage.js
3
+ * @description Finds which pages use which layouts, and which layouts are
4
+ * built on which, so a tool can show "used by N pages" before an edit.
5
+ */
6
+
7
+ import { existsSync, statSync, promises as fs } from 'node:fs';
8
+ import path from 'node:path';
9
+ import { pathToFileURL } from 'node:url';
10
+ import matter from 'gray-matter';
11
+
12
+ import { findTemplatedTag } from './render.js';
13
+
14
+ // Folders under src/ that are not pages
15
+ const SKIP_DIRS = new Set(['layouts', 'includes', 'components']);
16
+
17
+ /** Import config/main.js the way list.js does; null when absent or broken. */
18
+ async function loadMain(siteDir) {
19
+ const file = path.join(siteDir, 'config', 'main.js');
20
+ if (!existsSync(file)) return null;
21
+ try {
22
+ const mod = await import(`${pathToFileURL(file).href}?t=${statSync(file).mtimeMs}`);
23
+ let value = mod.default ?? mod;
24
+ if (typeof value === 'function') value = await value();
25
+ return value && typeof value === 'object' ? value : null;
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ /** The area paths whose subfolders are program folders (valid or colliding). */
32
+ async function loadProgramAreas(siteDir, buildOnlyPaths) {
33
+ const file = path.join(siteDir, 'config', 'programs.json');
34
+ if (!existsSync(file)) return [];
35
+ try {
36
+ const raw = JSON.parse(await fs.readFile(file, 'utf8'));
37
+ const { normalizePrograms } = await import('../../plugins/programs.js');
38
+ const { areas, protectedAreas } = normalizePrograms(raw, { buildOnlyPaths });
39
+ return [...areas, ...protectedAreas].map(a => a.path);
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+
45
+ async function readDirSafe(dir) {
46
+ try {
47
+ return await fs.readdir(dir, { withFileTypes: true });
48
+ } catch {
49
+ return [];
50
+ }
51
+ }
52
+
53
+ /** Page files (.html, .md) under src/, as src-relative paths. */
54
+ async function findPages(srcDir, programAreas) {
55
+ const found = [];
56
+ const walk = async (dir, rel) => {
57
+ for (const entry of await readDirSafe(dir)) {
58
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
59
+ if (entry.isDirectory()) {
60
+ if (!rel && SKIP_DIRS.has(entry.name)) continue;
61
+ // <area>/<program>/... is a program folder
62
+ if (rel && !rel.includes('/') && programAreas.includes(rel)) continue;
63
+ await walk(path.join(dir, entry.name), childRel);
64
+ } else if (entry.isFile() && /\.(html|md)$/.test(entry.name)) {
65
+ found.push(childRel);
66
+ }
67
+ }
68
+ };
69
+ await walk(srcDir, '');
70
+ return found.sort();
71
+ }
72
+
73
+ const bareName = (value) => (typeof value === 'string' && value.trim()
74
+ ? value.trim().replace(/\.html$/, '')
75
+ : null);
76
+
77
+ /** The layout name a page file uses, or null. */
78
+ function pageLayout(rel, source, defaultLayout) {
79
+ const isMarkdown = rel.endsWith('.md');
80
+ let body = source;
81
+ let layout = null;
82
+ if (isMarkdown || source.startsWith('---')) {
83
+ const parsed = matter(source);
84
+ body = parsed.content;
85
+ layout = bareName(parsed.data?.layout);
86
+ }
87
+ if (isMarkdown) return layout ?? bareName(defaultLayout);
88
+ const tag = findTemplatedTag(body);
89
+ return bareName(tag?.name) ?? layout;
90
+ }
91
+
92
+ function add(map, name, value) {
93
+ (map[name] ??= []).push(value);
94
+ }
95
+
96
+ /**
97
+ * Which pages use which layouts, and which layouts are built on which.
98
+ * Never throws; files that can't be read are skipped.
99
+ * @param {string} siteDir - The site's root directory (contains src/)
100
+ * @returns {Promise<{ pages: Record<string, string[]>, layouts: Record<string, string[]> }>}
101
+ * `pages[name]`: site-relative paths (`src/blog/a.md`) of pages using layout `name`;
102
+ * `layouts[name]`: names of layouts whose `data-template` is `name`
103
+ */
104
+ export async function layoutUsage(siteDir) {
105
+ const pages = {};
106
+ const layouts = {};
107
+ try {
108
+ const main = await loadMain(siteDir);
109
+ const defaultLayout = main?.markdown?.layout ?? null;
110
+ const programAreas = await loadProgramAreas(siteDir, main?.buildOnlyPaths ?? []);
111
+ const srcDir = path.join(siteDir, 'src');
112
+
113
+ for (const rel of await findPages(srcDir, programAreas)) {
114
+ try {
115
+ const name = pageLayout(rel, await fs.readFile(path.join(srcDir, rel), 'utf8'), defaultLayout);
116
+ if (name) add(pages, name, `src/${rel}`);
117
+ } catch { /* unreadable or malformed: skipped */ }
118
+ }
119
+
120
+ const layoutDir = path.join(srcDir, 'layouts');
121
+ for (const entry of await readDirSafe(layoutDir)) {
122
+ let name = null;
123
+ let file = null;
124
+ if (entry.isFile() && entry.name.endsWith('.html')) {
125
+ name = entry.name.slice(0, -5);
126
+ file = entry.name;
127
+ } else if (entry.isDirectory() && existsSync(path.join(layoutDir, entry.name, 'index.html'))) {
128
+ name = entry.name;
129
+ file = `${entry.name}/index.html`;
130
+ }
131
+ if (!name) continue;
132
+ try {
133
+ const parent = bareName(findTemplatedTag(await fs.readFile(path.join(layoutDir, file), 'utf8'))?.name);
134
+ if (parent) add(layouts, parent, name);
135
+ } catch { /* skipped */ }
136
+ }
137
+ for (const list of Object.values(layouts)) list.sort();
138
+ } catch { /* never throws */ }
139
+ return { pages, layouts };
140
+ }