cook-ssg 2.7.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,357 @@
1
+ /**
2
+ * @file conditionals.js
3
+ * @description `data-if="key"` / `data-unless="key"` sections.
4
+ *
5
+ * A tag-matching string transform, never a DOM re-serialize: bytes outside
6
+ * an affected element never change, and HTML with no marker comes back as
7
+ * the same string. For a key the lookup knows, the element is removed
8
+ * (`data-if` and not set, or `data-unless` and set) or the attribute is
9
+ * stripped (with its preceding whitespace). An unknown key is left in place
10
+ * for a later pass.
11
+ *
12
+ * Evaluation happens in three places:
13
+ * - layout time (`layoutConditionals`, via render.js): page fields, slots
14
+ * and site data;
15
+ * - each `data-repeat` item (repeat-collection.js): `alias.x` keys;
16
+ * - the late pass (`lateConditionals`, conditional-sections.js): whatever
17
+ * is left, from site data and front matter, missing meaning not set.
18
+ *
19
+ * Keys whose first segment is the alias of an enclosing `data-repeat`
20
+ * (`… as post`, `… as item, index`) are never looked up here: they belong
21
+ * to the repeat, which resolves them per item.
22
+ */
23
+
24
+ import { getNested } from '../interpolate/interpolate.js';
25
+
26
+ const MARKER = /data-(?:if|unless)/i;
27
+ const CONDITIONAL_ATTR = /^data-(if|unless)$/i;
28
+ const REPEAT_ATTR = /^data-repeat$/i;
29
+ const REPEAT_ALIASES = /\sas\s+(\w+)(?:\s*,\s*(\w+))?\s*$/;
30
+
31
+ const VOID = new Set([
32
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen',
33
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
34
+ ]);
35
+ // Elements whose content is text, not markup
36
+ const RAW_TEXT = new Set(['script', 'style', 'textarea', 'title']);
37
+
38
+ const isSpace = (c) => c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f';
39
+ const isLetter = (c) => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
40
+
41
+ /**
42
+ * Whether a value counts as set: false for undefined, null, '', false, []
43
+ * and whitespace-only strings; true otherwise.
44
+ * @param {*} value
45
+ * @returns {boolean}
46
+ */
47
+ export function isSet(value) {
48
+ if (value === undefined || value === null || value === false) return false;
49
+ if (typeof value === 'string') return value.trim() !== '';
50
+ if (Array.isArray(value)) return value.length > 0;
51
+ return true;
52
+ }
53
+
54
+ /**
55
+ * Read the tag that starts at `i` (which holds `<`).
56
+ * @param {string} html
57
+ * @param {number} i
58
+ * @returns {null|{ type: 'start'|'end'|'other', name?: string, end: number,
59
+ * selfClosing?: boolean, attrs?: Array<{ name: string, value: string|null, start: number, end: number }> }}
60
+ * null when the `<` is plain text. Attribute `start` includes the
61
+ * whitespace before the attribute.
62
+ */
63
+ function readTag(html, i) {
64
+ const len = html.length;
65
+ const next = html[i + 1];
66
+
67
+ // Comment
68
+ if (html.startsWith('<!--', i)) {
69
+ const close = html.indexOf('-->', i + 4);
70
+ return { type: 'other', end: close === -1 ? len : close + 3 };
71
+ }
72
+ // Doctype, CDATA, processing instruction
73
+ if (next === '!' || next === '?') {
74
+ const close = html.indexOf('>', i + 2);
75
+ return { type: 'other', end: close === -1 ? len : close + 1 };
76
+ }
77
+ // End tag
78
+ if (next === '/') {
79
+ if (!isLetter(html[i + 2] || '')) return null;
80
+ let p = i + 2;
81
+ while (p < len && !isSpace(html[p]) && html[p] !== '/' && html[p] !== '>') p++;
82
+ const name = html.slice(i + 2, p).toLowerCase();
83
+ const close = html.indexOf('>', p);
84
+ return { type: 'end', name, end: close === -1 ? len : close + 1 };
85
+ }
86
+ // Start tag
87
+ if (!isLetter(next || '')) return null;
88
+ let p = i + 1;
89
+ while (p < len && !isSpace(html[p]) && html[p] !== '/' && html[p] !== '>') p++;
90
+ const name = html.slice(i + 1, p).toLowerCase();
91
+
92
+ const attrs = [];
93
+ let selfClosing = false;
94
+ let end = len;
95
+ while (p < len) {
96
+ const start = p;
97
+ while (p < len && isSpace(html[p])) p++;
98
+ if (p >= len) break;
99
+ const c = html[p];
100
+ if (c === '>') { end = p + 1; break; }
101
+ if (c === '/') {
102
+ if (html[p + 1] === '>') { selfClosing = true; end = p + 2; break; }
103
+ p++;
104
+ continue;
105
+ }
106
+ // Attribute name
107
+ const nameStart = p;
108
+ p++; // at least one character (covers a stray `=` or quote)
109
+ while (p < len && !isSpace(html[p]) && html[p] !== '/' && html[p] !== '>' && html[p] !== '=') p++;
110
+ const attrName = html.slice(nameStart, p);
111
+ // Optional value
112
+ let value = null;
113
+ let q = p;
114
+ while (q < len && isSpace(html[q])) q++;
115
+ if (html[q] === '=') {
116
+ q++;
117
+ while (q < len && isSpace(html[q])) q++;
118
+ const quote = html[q];
119
+ if (quote === '"' || quote === "'") {
120
+ const close = html.indexOf(quote, q + 1);
121
+ const valueEnd = close === -1 ? len : close;
122
+ value = html.slice(q + 1, valueEnd);
123
+ p = close === -1 ? len : close + 1;
124
+ } else {
125
+ const valueStart = q;
126
+ while (q < len && !isSpace(html[q]) && html[q] !== '>') q++;
127
+ value = html.slice(valueStart, q);
128
+ p = q;
129
+ }
130
+ }
131
+ attrs.push({ name: attrName, value, start, end: p });
132
+ }
133
+
134
+ return { type: 'start', name, attrs, selfClosing, end };
135
+ }
136
+
137
+ /**
138
+ * Index just past the close tag of a raw-text element whose start tag
139
+ * ends at `from` (end of input when it never closes).
140
+ */
141
+ function rawTextEnd(html, name, from) {
142
+ const pattern = new RegExp(`</${name}(?=[\\s/>])`, 'gi');
143
+ pattern.lastIndex = from;
144
+ const m = pattern.exec(html);
145
+ if (!m) return html.length;
146
+ const close = html.indexOf('>', m.index);
147
+ return close === -1 ? html.length : close + 1;
148
+ }
149
+
150
+ // Start tags that close an open <p>
151
+ const CLOSES_P = new Set([
152
+ 'address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl',
153
+ 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3',
154
+ 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'menu', 'nav', 'ol',
155
+ 'p', 'pre', 'section', 'table', 'ul',
156
+ ]);
157
+ // Elements with an optional end tag, and the start tags that end them
158
+ const IMPLIED_END = {
159
+ li: new Set(['li']),
160
+ dt: new Set(['dt', 'dd']),
161
+ dd: new Set(['dt', 'dd']),
162
+ option: new Set(['option', 'optgroup']),
163
+ optgroup: new Set(['optgroup']),
164
+ tr: new Set(['tr', 'tbody', 'thead', 'tfoot']),
165
+ td: new Set(['td', 'th', 'tr', 'tbody', 'thead', 'tfoot']),
166
+ th: new Set(['td', 'th', 'tr', 'tbody', 'thead', 'tfoot']),
167
+ thead: new Set(['tbody', 'tfoot']),
168
+ tbody: new Set(['tbody', 'tfoot']),
169
+ };
170
+
171
+ /** Whether a `<startName>` start tag ends an open `open` element. */
172
+ function closesImplicitly(open, startName) {
173
+ if (open === 'p') return CLOSES_P.has(startName);
174
+ return !!IMPLIED_END[open] && IMPLIED_END[open].has(startName);
175
+ }
176
+
177
+ /**
178
+ * Index just past the element whose start tag was read at `tag`.
179
+ * Void and self-closing elements end with their tag. Nested elements of
180
+ * the same name are counted. HTML's optional end tags are modelled: a
181
+ * `p` ends at a start tag that closes a p, an `li` at the next `li`, a
182
+ * `dt`/`dd` at the next dt/dd, an `option` at option/optgroup, a `tr` at
183
+ * tr, a `td`/`th` at td/th/tr. Any element ends where a close tag for
184
+ * something not open inside it appears (its parent closing), or at the
185
+ * end of input, so removal never runs past the enclosing element.
186
+ */
187
+ function elementEnd(html, tag) {
188
+ if (VOID.has(tag.name) || tag.selfClosing) return tag.end;
189
+ if (RAW_TEXT.has(tag.name)) return rawTextEnd(html, tag.name, tag.end);
190
+
191
+ const stack = [tag.name];
192
+ let j = tag.end;
193
+ while (true) {
194
+ const k = html.indexOf('<', j);
195
+ if (k === -1) return html.length;
196
+ const t = readTag(html, k);
197
+ if (!t) { j = k + 1; continue; }
198
+ if (t.type === 'start') {
199
+ // Optional end tags: this start tag may close open elements
200
+ while (stack.length && closesImplicitly(stack[stack.length - 1], t.name)) stack.pop();
201
+ if (!stack.length) return k;
202
+ if (RAW_TEXT.has(t.name) && !t.selfClosing) j = rawTextEnd(html, t.name, t.end);
203
+ else {
204
+ if (!VOID.has(t.name) && !t.selfClosing) stack.push(t.name);
205
+ j = t.end;
206
+ }
207
+ } else if (t.type === 'end') {
208
+ const at = stack.lastIndexOf(t.name);
209
+ if (at === -1) return k; // a parent closing: the element ended implicitly
210
+ stack.length = at;
211
+ if (!stack.length) return t.end;
212
+ j = t.end;
213
+ } else {
214
+ j = t.end;
215
+ }
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Apply `data-if` / `data-unless` to HTML.
221
+ * @param {string} html - A fragment or a full document
222
+ * @param {(key: string) => { known: boolean, value?: any }} lookup
223
+ * @returns {string} `html` itself when it has no marker
224
+ */
225
+ export function applyConditionals(html, lookup) {
226
+ if (typeof html !== 'string' || !MARKER.test(html)) return html;
227
+
228
+ let out = '';
229
+ let copied = 0;
230
+ let i = 0;
231
+ // Enclosing data-repeat elements: { end, aliases }
232
+ const repeats = [];
233
+ const aliased = (key) => {
234
+ const first = key.split('.')[0];
235
+ return repeats.some((r) => r.aliases.includes(first));
236
+ };
237
+
238
+ while ((i = html.indexOf('<', i)) !== -1) {
239
+ const tag = readTag(html, i);
240
+ if (!tag) { i++; continue; }
241
+ if (tag.type !== 'start') { i = tag.end; continue; }
242
+
243
+ while (repeats.length && repeats[repeats.length - 1].end <= i) repeats.pop();
244
+
245
+ // A data-repeat's aliases cover the element itself and everything in it
246
+ let pushedRepeat = false;
247
+ const repeat = tag.attrs.find((a) => REPEAT_ATTR.test(a.name));
248
+ const aliasMatch = repeat && repeat.value && repeat.value.match(REPEAT_ALIASES);
249
+ if (aliasMatch) {
250
+ repeats.push({ end: elementEnd(html, tag), aliases: [aliasMatch[1], aliasMatch[2]].filter(Boolean) });
251
+ pushedRepeat = true;
252
+ }
253
+
254
+ let remove = false;
255
+ const strip = [];
256
+ for (const attr of tag.attrs) {
257
+ const kind = attr.name.match(CONDITIONAL_ATTR);
258
+ if (!kind) continue;
259
+ const key = (attr.value || '').trim();
260
+ if (!key || aliased(key)) continue;
261
+ const result = lookup(key);
262
+ if (!result || !result.known) continue;
263
+ const set = isSet(result.value);
264
+ const keep = kind[1].toLowerCase() === 'if' ? set : !set;
265
+ if (keep) strip.push(attr);
266
+ else remove = true;
267
+ }
268
+
269
+ if (remove) {
270
+ const end = elementEnd(html, tag);
271
+ out += html.slice(copied, i);
272
+ copied = end;
273
+ i = end;
274
+ if (pushedRepeat) repeats.pop();
275
+ continue;
276
+ }
277
+
278
+ if (strip.length) {
279
+ let rebuilt = '';
280
+ let from = i;
281
+ for (const attr of strip) {
282
+ rebuilt += html.slice(from, attr.start);
283
+ from = attr.end;
284
+ }
285
+ rebuilt += html.slice(from, tag.end);
286
+ out += html.slice(copied, i) + rebuilt;
287
+ copied = tag.end;
288
+ }
289
+
290
+ // Raw text is not markup: skip to its close tag
291
+ i = RAW_TEXT.has(tag.name) && !tag.selfClosing ? rawTextEnd(html, tag.name, tag.end) : tag.end;
292
+ }
293
+
294
+ if (copied === 0) return html;
295
+ return out + html.slice(copied);
296
+ }
297
+
298
+ /**
299
+ * The value of a key in an object: `slot:*` keys are flat, others may be
300
+ * dotted paths.
301
+ */
302
+ function valueOf(obj, key) {
303
+ if (!obj) return undefined;
304
+ if (Object.hasOwn(obj, key)) return obj[key];
305
+ return getNested(obj, key);
306
+ }
307
+
308
+ const hasRoot = (obj, key) => !!obj && typeof obj === 'object' && Object.hasOwn(obj, key.split('.')[0]);
309
+
310
+ /**
311
+ * Layout-time conditionals (the `conditionals` hook of renderLayout).
312
+ * Known: `slot:*` keys (set = non-blank), keys in page data, keys in site
313
+ * data. Anything else is left for the late pass.
314
+ * @param {string} html
315
+ * @param {Object} pageData
316
+ * @param {Object} data
317
+ * @returns {string}
318
+ */
319
+ export function layoutConditionals(html, pageData = {}, data = {}) {
320
+ const lookup = (key) => {
321
+ if (key.startsWith('slot:')) return { known: true, value: pageData ? pageData[key] : undefined };
322
+ if (hasRoot(pageData, key)) return { known: true, value: valueOf(pageData, key) };
323
+ if (hasRoot(data, key)) return { known: true, value: valueOf(data, key) };
324
+ return { known: false };
325
+ };
326
+ const result = applyConditionals(html, lookup);
327
+
328
+ // A whole child-layout slot template: render.js unwraps it, so its own
329
+ // data-if/data-unless never reaches a later pass. Decide it now, a key
330
+ // still unknown counting as not set.
331
+ if (typeof result !== 'string') return result;
332
+ const lead = result.match(/^\s*/)[0].length;
333
+ const tag = result[lead] === '<' ? readTag(result, lead) : null;
334
+ if (tag && tag.type === 'start' && tag.name === 'template'
335
+ && tag.attrs.some((a) => /^slot$/i.test(a.name))
336
+ && tag.attrs.some((a) => CONDITIONAL_ATTR.test(a.name))) {
337
+ const openTag = result.slice(lead, tag.end);
338
+ const decided = applyConditionals(`${openTag}</template>`, (key) => {
339
+ const r = lookup(key);
340
+ return r.known ? r : { known: true, value: undefined };
341
+ });
342
+ // Removed: only this template element goes, what follows stays
343
+ if (!decided) return result.slice(0, lead) + result.slice(elementEnd(result, tag));
344
+ return result.slice(0, lead) + decided.slice(0, -'</template>'.length) + result.slice(tag.end);
345
+ }
346
+ return result;
347
+ }
348
+
349
+ /**
350
+ * Late-pass conditionals: every key is known; a missing one is not set.
351
+ * @param {string} html
352
+ * @param {Object} values - `{ ...data, ...frontMatter }`
353
+ * @returns {string}
354
+ */
355
+ export function lateConditionals(html, values = {}) {
356
+ return applyConditionals(html, (key) => ({ known: true, value: valueOf(values, key) }));
357
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * @file list.js
3
+ * @description Lists a site's layouts and includes with their check
4
+ * results, parent chains and slots, and loads the site's field and list
5
+ * names (from config/data.js and config/main.js) for the checker.
6
+ */
7
+
8
+ import { existsSync, statSync, promises as fs } from 'node:fs';
9
+ import path from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ import { checkLayout } from './check.js';
13
+
14
+ const FRAGMENT_MARKER = /^\s*<!--\s*layout-fragment\s*-->/;
15
+
16
+ /** Import a site config file; returns { value } or { error } or { missing }. */
17
+ async function importConfig(file) {
18
+ if (!existsSync(file)) return { missing: true };
19
+ try {
20
+ // Bust the module cache by mtime so a long-lived caller sees edits
21
+ const url = `${pathToFileURL(file).href}?t=${statSync(file).mtimeMs}`;
22
+ const mod = await import(url);
23
+ let value = mod.default ?? mod;
24
+ if (typeof value === 'function') value = await value();
25
+ return { value };
26
+ } catch (err) {
27
+ return { error: err?.message ?? String(err) };
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Read the field and list names a site makes available to layouts.
33
+ * Never throws; a config file that fails to load is reported in `problems`.
34
+ * @param {string} siteDir - The site's root directory
35
+ * @returns {Promise<{ fields: string[], lists: string[], problems: Array<{ file: string, line: number, message: string }> }>}
36
+ */
37
+ export async function loadSiteNames(siteDir) {
38
+ const fields = new Set();
39
+ const lists = new Set(['programs', 'programAreas']);
40
+ const problems = [];
41
+
42
+ const data = await importConfig(path.join(siteDir, 'config', 'data.js'));
43
+ if (data.error) problems.push({ file: 'config/data.js', line: 1, message: `config/data.js could not be loaded (${data.error})` });
44
+ else if (data.value && typeof data.value === 'object') {
45
+ for (const [key, value] of Object.entries(data.value)) {
46
+ fields.add(key);
47
+ if (Array.isArray(value)) lists.add(key);
48
+ }
49
+ }
50
+
51
+ const main = await importConfig(path.join(siteDir, 'config', 'main.js'));
52
+ if (main.error) problems.push({ file: 'config/main.js', line: 1, message: `config/main.js could not be loaded (${main.error})` });
53
+ else if (main.value && typeof main.value === 'object') {
54
+ const declared = main.value.layouts?.fields;
55
+ if (Array.isArray(declared)) declared.filter(f => typeof f === 'string').forEach(f => fields.add(f));
56
+ }
57
+
58
+ return { fields: [...fields], lists: [...lists], problems };
59
+ }
60
+
61
+ async function readDirSafe(dir) {
62
+ try {
63
+ return await fs.readdir(dir, { withFileTypes: true });
64
+ } catch {
65
+ return [];
66
+ }
67
+ }
68
+
69
+ /** Layout files: layouts/<name>.html and layouts/<dir>/index.html. */
70
+ async function findLayoutFiles(dir) {
71
+ const found = [];
72
+ for (const entry of await readDirSafe(dir)) {
73
+ if (entry.isFile() && entry.name.endsWith('.html')) {
74
+ found.push({ name: entry.name.slice(0, -5), file: entry.name });
75
+ } else if (entry.isDirectory() && existsSync(path.join(dir, entry.name, 'index.html'))) {
76
+ found.push({ name: entry.name, file: `${entry.name}/index.html` });
77
+ }
78
+ }
79
+ return found.sort((a, b) => a.name.localeCompare(b.name));
80
+ }
81
+
82
+ /** Include files: every .html under includes/, as paths relative to it. */
83
+ async function findIncludeFiles(dir, base = dir) {
84
+ const found = [];
85
+ for (const entry of await readDirSafe(dir)) {
86
+ const full = path.join(dir, entry.name);
87
+ if (entry.isDirectory()) found.push(...await findIncludeFiles(full, base));
88
+ else if (entry.isFile() && entry.name.endsWith('.html')) {
89
+ const file = path.relative(base, full).split(path.sep).join('/');
90
+ found.push({ name: file.slice(0, -5), file, full });
91
+ }
92
+ }
93
+ return found.sort((a, b) => a.file.localeCompare(b.file));
94
+ }
95
+
96
+ /** Walk parents from `entry`; returns the chain and any chain problem. */
97
+ function resolveChain(entry, byName) {
98
+ const chain = [entry.name];
99
+ let current = entry;
100
+ while (current.parent) {
101
+ const next = byName.get(current.parent);
102
+ if (!next) {
103
+ return { chain, problem: `parent layout "${current.parent}" not found` };
104
+ }
105
+ if (chain.includes(next.name)) {
106
+ return { chain, problem: `layouts form a cycle: ${[...chain, next.name].join(' → ')}` };
107
+ }
108
+ chain.push(next.name);
109
+ current = next;
110
+ }
111
+ return { chain, problem: null };
112
+ }
113
+
114
+ /**
115
+ * List a site's layouts and includes with their check results.
116
+ * @param {string} siteDir - The site's root directory (contains src/)
117
+ * @param {Object} [opts]
118
+ * @property {string[]} [opts.fields] - Known field names (default: loaded from the site config)
119
+ * @property {string[]} [opts.lists] - Known list roots (default: loaded from the site config)
120
+ * @returns {Promise<{ problems: Array<{ file: string, line: number, message: string }>, layouts: Object[], includes: Array<{ name: string, file: string, ok: boolean, problems: Array }> }>}
121
+ */
122
+ export async function listLayouts(siteDir, { fields, lists } = {}) {
123
+ let configProblems = [];
124
+ if (!fields || !lists) {
125
+ const names = await loadSiteNames(siteDir);
126
+ fields = fields ?? names.fields;
127
+ lists = lists ?? names.lists;
128
+ configProblems = names.problems;
129
+ }
130
+
131
+ const layoutDir = path.join(siteDir, 'src', 'layouts');
132
+ const entries = [];
133
+ for (const { name, file } of await findLayoutFiles(layoutDir)) {
134
+ let source = '';
135
+ try { source = await fs.readFile(path.join(layoutDir, file), 'utf8'); } catch { /* unreadable: treated as empty */ }
136
+ const result = checkLayout(source, { fields, lists });
137
+ const info = result.info && typeof result.info === 'object' ? result.info : {};
138
+ const declared = info.slots && typeof info.slots === 'object' && !Array.isArray(info.slots) ? info.slots : {};
139
+ entries.push({
140
+ name,
141
+ file,
142
+ kind: result.kind,
143
+ ok: result.ok,
144
+ editable: false,
145
+ label: typeof info.label === 'string' && info.label ? info.label : name,
146
+ description: typeof info.description === 'string' ? info.description : '',
147
+ abstract: info.abstract === true,
148
+ parent: result.parent ?? null,
149
+ chain: [name],
150
+ slots: result.slots.map(slot => ({
151
+ name: slot,
152
+ label: typeof declared[slot]?.label === 'string' ? declared[slot].label : slot,
153
+ })),
154
+ problems: [...result.problems],
155
+ });
156
+ }
157
+
158
+ const byName = new Map(entries.map(e => [e.name, e]));
159
+ for (const entry of entries) {
160
+ const { chain, problem } = resolveChain(entry, byName);
161
+ entry.chain = chain;
162
+ // Plain layouts never fail: no chain problem for them
163
+ if (problem && entry.kind !== 'plain') entry.problems.push({ line: 1, message: problem });
164
+ entry.editable = !problem && chain.every(n => byName.get(n).ok);
165
+ if (entry.problems.length) entry.ok = false;
166
+ }
167
+
168
+ const includes = [];
169
+ const includeDir = path.join(siteDir, 'src', 'includes');
170
+ for (const { name, file, full } of await findIncludeFiles(includeDir)) {
171
+ let source = '';
172
+ try { source = await fs.readFile(full, 'utf8'); } catch { /* unreadable */ }
173
+ if (FRAGMENT_MARKER.test(source)) {
174
+ const result = checkLayout(source, { fields, lists, fragment: true });
175
+ includes.push({ name, file, ok: result.ok, problems: result.problems });
176
+ } else {
177
+ includes.push({ name, file, ok: false, problems: [] });
178
+ }
179
+ }
180
+
181
+ return { problems: configProblems, layouts: entries, includes };
182
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @file parse.js
3
+ * @description Parse a layout's source into a DOM, decide its kind
4
+ * (base, child or fragment), read its info block, and map elements back
5
+ * to source line numbers.
6
+ */
7
+
8
+ import { parseHTML } from 'linkedom';
9
+
10
+ const RAW_TEXT = new Set(['script', 'style', 'textarea', 'title']);
11
+
12
+ // Comments, doctype-like declarations, and start tags (name captured)
13
+ const TOKEN = /<!--[\s\S]*?(?:-->|$)|<![^>]*>|<([a-zA-Z][a-zA-Z0-9-]*)/g;
14
+
15
+ /**
16
+ * Collect every start tag in the source, in order, grouped by tag name.
17
+ * Comments and the raw text of script/style are skipped.
18
+ * @param {string} html
19
+ * @returns {Map<string, number[]>} tag name → source lines, in order
20
+ */
21
+ function scanStartTags(html) {
22
+ const tags = new Map();
23
+ let line = 1;
24
+ let counted = 0;
25
+ const lineAt = (offset) => {
26
+ for (; counted < offset; counted++) if (html.charCodeAt(counted) === 10) line++;
27
+ return line;
28
+ };
29
+
30
+ TOKEN.lastIndex = 0;
31
+ let match;
32
+ while ((match = TOKEN.exec(html))) {
33
+ if (!match[1]) continue;
34
+ const name = match[1].toLowerCase();
35
+ if (!tags.has(name)) tags.set(name, []);
36
+ tags.get(name).push(lineAt(match.index));
37
+
38
+ if (RAW_TEXT.has(name)) {
39
+ const close = html.toLowerCase().indexOf(`</${name}`, TOKEN.lastIndex);
40
+ TOKEN.lastIndex = close === -1 ? html.length : close;
41
+ }
42
+ }
43
+ return tags;
44
+ }
45
+
46
+ /**
47
+ * Child nodes of an element, looking through `<template>` to its content.
48
+ * @param {Element} el
49
+ * @returns {Node[]}
50
+ */
51
+ export function childrenOf(el) {
52
+ const holder = el.tagName === 'TEMPLATE' && el.content ? el.content : el;
53
+ return Array.from(holder.childNodes);
54
+ }
55
+
56
+ /**
57
+ * Pair each element, in document order, with the next unused start tag of
58
+ * the same name. Elements the parser implied take their parent's line.
59
+ * @param {Element} root
60
+ * @param {Map<string, number[]>} tags
61
+ * @returns {WeakMap<Element, number>}
62
+ */
63
+ function mapLines(root, tags) {
64
+ const lines = new WeakMap();
65
+ const used = new Map();
66
+ const visit = (el, parentLine) => {
67
+ const name = el.tagName.toLowerCase();
68
+ const queue = tags.get(name) || [];
69
+ const next = used.get(name) || 0;
70
+ let line = parentLine;
71
+ if (next < queue.length) {
72
+ line = queue[next];
73
+ used.set(name, next + 1);
74
+ }
75
+ lines.set(el, line);
76
+ for (const node of childrenOf(el)) {
77
+ if (node.nodeType === 1) visit(node, line);
78
+ }
79
+ };
80
+ visit(root, 1);
81
+ return lines;
82
+ }
83
+
84
+ /**
85
+ * Parse layout source.
86
+ * @param {string} html
87
+ * @param {Object} [opts]
88
+ * @property {boolean} [opts.fragment=false] - Treat the source as a fragment
89
+ * @returns {{ document: Document, kind: 'base'|'child'|'fragment', info: Object|null,
90
+ * infoError: string|null, parent: string|null, lineOf: (el: Element) => number }}
91
+ */
92
+ export function parseLayoutSource(html, { fragment = false } = {}) {
93
+ let kind = 'fragment';
94
+ let document;
95
+
96
+ if (!fragment) {
97
+ ({ document } = parseHTML(html));
98
+ const top = document.documentElement;
99
+ const templated = [top, document.body].find(el => el && el.hasAttribute('data-template'));
100
+ if (templated) kind = 'child';
101
+ else if (/<!doctype|<html[\s>]|<head[\s>]/i.test(html)) kind = 'base';
102
+ }
103
+
104
+ if (kind === 'fragment') {
105
+ ({ document } = parseHTML(`<!doctype html><html><head></head><body>${html}</body></html>`));
106
+ } else if (kind === 'child' && document.documentElement.tagName !== 'HTML') {
107
+ // A bare `<body data-template>` parses with <body> as the root and a
108
+ // detached document.body; wrap it so document.body is the real one.
109
+ ({ document } = parseHTML(`<!doctype html><html><head></head>${html}</html>`));
110
+ }
111
+
112
+ let parent = null;
113
+ if (kind === 'child') {
114
+ const templated = [document.documentElement, document.body].find(el => el && el.hasAttribute('data-template'));
115
+ parent = templated.getAttribute('data-template').trim() || null;
116
+ }
117
+
118
+ let info = null;
119
+ let infoError = null;
120
+ const script = document.querySelector('script[data-layout-info]');
121
+ if (script) {
122
+ try {
123
+ info = JSON.parse(script.textContent);
124
+ } catch (err) {
125
+ infoError = err.message;
126
+ }
127
+ }
128
+
129
+ const lines = mapLines(document.documentElement, scanStartTags(html));
130
+ const lineOf = (el) => lines.get(el) ?? 1;
131
+
132
+ return { document, kind, info, infoError, parent, lineOf };
133
+ }