@zvndev/darkmown 0.18.0 → 0.20.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/src/compiler.js CHANGED
@@ -1,2753 +1,26 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import MarkdownIt from "markdown-it";
4
- import { imageSize } from "image-size";
5
-
6
- /**
7
- * @typedef {import("./config.js").Paths} Paths
8
- */
9
-
10
- /**
11
- * Frontmatter values are scalars or inline arrays of scalars.
12
- * @typedef {string | number | boolean | null | Array<string | number | boolean | null>} FrontmatterValue
13
- */
14
-
15
- /**
16
- * Parsed page frontmatter, keyed by field name.
17
- * @typedef {Record<string, FrontmatterValue>} Meta
18
- */
19
-
20
- /**
21
- * Collected output assets for a compiled document.
22
- * @typedef {object} Assets
23
- * @property {Set<string>} skins Public hrefs of compiled skin stylesheets.
24
- * @property {Set<string>} scripts Public hrefs of colocated page scripts.
25
- * @property {Map<string, string>} files Source path → public href for emitted assets.
26
- * @property {boolean} runtime Whether the reactive runtime is required.
27
- */
28
-
29
- /**
30
- * Per-document compilation accumulator shared across includes/sections.
31
- * @typedef {object} Compilation
32
- * @property {Assets} assets
33
- * @property {Map<string, unknown>} state Declared state keys → initial values.
34
- * @property {Set<string>} stores Page-global store names (a subset of state keys).
35
- * @property {string[]} warnings Non-fatal authoring hints.
36
- * @property {number} sectionCounter Counter for auto-generated section ids.
37
- */
38
-
39
- /**
40
- * A lexical scope chain for static interpolation values (include args, loop vars).
41
- * @typedef {object} Scope
42
- * @property {Scope | null} parent
43
- * @property {Record<string, unknown>} vars
44
- */
45
-
46
- /**
47
- * Per-file compile context threaded through the directive handlers.
48
- * @typedef {object} Ctx
49
- * @property {string} file Absolute path to the file being compiled.
50
- * @property {Paths} context Resolved project paths.
51
- * @property {string[]} stack Include stack (real paths) for cycle detection.
52
- * @property {Scope} scope Static value scope chain.
53
- * @property {Compilation} comp Shared compilation accumulator.
54
- * @property {string[]} sections Active section-id scope chain.
55
- * @property {string | null} loopItem Name of the current reactive loop item, if any.
56
- * @property {string} [loopKey] State key of the list being looped, if any.
57
- * @property {boolean} [loopMeta] Inside a loop body, so `$index`/`$first`/… are valid.
58
- * @property {MarkdownIt} [md] Markdown-it instance selected for this file.
59
- */
60
-
61
- /**
62
- * A compiled page document.
63
- * @typedef {object} CompiledDocument
64
- * @property {Meta} meta
65
- * @property {string} html
66
- * @property {Assets} assets
67
- * @property {string[]} warnings
68
- */
69
-
70
- /**
71
- * A compiled page: the document plus its full HTML shell.
72
- * @typedef {object} CompiledPage
73
- * @property {Meta} meta
74
- * @property {string} html
75
- * @property {Assets} assets
76
- * @property {string[]} warnings
77
- */
78
-
79
- const md = new MarkdownIt({ html: true });
80
- md.use(bindingPlugin);
81
- md.use(attrsPlugin);
82
-
83
- // Raw HTML in markdown passes through by default (a documented design choice).
84
- // Pages can opt out with frontmatter `html: false` for untrusted content; the
85
- // stricter instance is built lazily so the default path stays a single instance.
86
- /** @type {MarkdownIt | null} */
87
- let mdNoHtml = null;
88
- /**
89
- * Pick the markdown-it instance for a page (raw HTML on by default, off with `html: false`).
90
- * @param {Meta} [meta]
91
- * @returns {MarkdownIt}
92
- */
93
- function selectMd(meta) {
94
- // Frontmatter scalars stay strings (no coercion), so accept both forms.
95
- if (meta?.html !== false && meta?.html !== "false") return md;
96
- if (!mdNoHtml) {
97
- mdNoHtml = new MarkdownIt({ html: false });
98
- mdNoHtml.use(bindingPlugin);
99
- mdNoHtml.use(attrsPlugin);
100
- }
101
- return mdNoHtml;
102
- }
103
-
104
- const pageIncludeExtensions = [".md", ".wd"];
105
-
106
- /**
107
- * Compile a page source file into a full HTML document plus its assets.
108
- * @param {string} file Absolute path to the source `.md`/`.wd` file.
109
- * @param {Paths} context Resolved project paths.
110
- * @returns {CompiledPage}
111
- */
112
- export function compilePage(file, context) {
113
- const compiled = compileDocument(file, context);
114
- const title = compiled.meta.title || "Darkmown";
115
- const description = compiled.meta.description || "";
116
- // Optional `image:` frontmatter sets the social-share preview (absolute URL).
117
- const image = typeof compiled.meta.image === "string" ? compiled.meta.image : "";
118
- /** @type {string[]} */
119
- const social = [];
120
- if (description) social.push(`<meta name="description" content="${escapeHtml(description)}">`);
121
- if (description || image) {
122
- social.push(`<meta property="og:title" content="${escapeHtml(title)}">`);
123
- if (description) social.push(`<meta property="og:description" content="${escapeHtml(description)}">`);
124
- social.push(`<meta property="og:type" content="website">`);
125
- }
126
- if (image) {
127
- social.push(`<meta property="og:image" content="${escapeHtml(image)}">`);
128
- social.push(`<meta name="twitter:image" content="${escapeHtml(image)}">`);
129
- }
130
- if (description || image) {
131
- social.push(`<meta name="twitter:card" content="${image ? "summary_large_image" : "summary"}">`);
132
- }
133
- const descriptionTag = social.length ? `\n ${social.join("\n ")}` : "";
134
- const favicon = "data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2032%2032'%3E%3Crect%20width='32'%20height='32'%20rx='6'%20fill='%2318221d'/%3E%3Ctext%20x='16'%20y='23'%20text-anchor='middle'%20font-family='Georgia,serif'%20font-size='19'%20font-weight='bold'%20fill='%23f7f3ea'%3ED%3C/text%3E%3C/svg%3E";
135
- const cssLinks = [...compiled.assets.skins].map((href) => `<link rel="stylesheet" href="${href}">`).join("\n");
136
- const scriptSrcs = compiled.assets.runtime ? ["/__wd/runtime.js", ...compiled.assets.scripts] : [...compiled.assets.scripts];
137
- const scripts = scriptSrcs.map((src) => `<script type="module" src="${src}"></script>`).join("\n");
138
- // Cross-document view transitions: opt in per page with `transitions: true` in
139
- // frontmatter to emit a CSS-only stylesheet — a smooth same-origin transition
140
- // on navigation, with zero JavaScript. Ignored by browsers without support
141
- // (graceful, transition-free fallback) and only applies to same-origin
142
- // navigations where both the outgoing and incoming page opt in.
143
- //
144
- // The default UA animation cross-fades the root: outgoing opacity 1→0 while
145
- // incoming 0→1, both at once. Mid-navigation that leaves the two pages
146
- // superimposed at ~50% opacity — headings ghost over headings. We override it
147
- // with a directional fade+slide (old lifts up and out, new rises up and in) so
148
- // the pages move past each other instead of stacking. Short + eased = peppy.
149
- const wantTransitions = compiled.meta.transitions === true || compiled.meta.transitions === "true";
150
- const transitions = wantTransitions
151
- ? `\n <style>
152
- @view-transition { navigation: auto; }
153
- ::view-transition-old(root) { animation: wd-nav-out 200ms cubic-bezier(0.4, 0, 1, 1) both; }
154
- ::view-transition-new(root) { animation: wd-nav-in 200ms cubic-bezier(0, 0, 0.2, 1) both; }
155
- @keyframes wd-nav-out { to { opacity: 0; transform: translateY(-1rem); } }
156
- @keyframes wd-nav-in { from { opacity: 0; transform: translateY(1rem); } }
157
- @media (prefers-reduced-motion: reduce) {
158
- ::view-transition-old(root), ::view-transition-new(root) { animation-duration: 1ms; }
159
- @keyframes wd-nav-out { to { opacity: 0; } }
160
- @keyframes wd-nav-in { from { opacity: 0; } }
161
- }
162
- </style>`
163
- : "";
164
-
165
- // The latency half of smooth navigation — and what kills the white flash. A
166
- // declarative speculationrules script (the browser interprets it — not
167
- // framework runtime JS, so the zero-JS invariant holds) *prerenders* the next
168
- // same-origin page on hover/pointerdown. Prefetch only warms the cache, so the
169
- // page still has to render on click — that render gap is the white flash. A
170
- // prerender renders the whole page in a hidden tab ahead of the click, so
171
- // activation is instant: no render gap, and the view transition fires on the
172
- // already-painted page. Safe now that pages are light. Eagerness `moderate` =
173
- // ~200ms hover / pointerdown, capped at two. Mark a link `{.no-prefetch}` to
174
- // opt it out; `rel=nofollow` links are never speculated. Browsers without
175
- // support (or with preloading disabled) ignore the tag and navigate normally.
176
- const speculation = wantTransitions
177
- ? `\n <script type="speculationrules">{"prerender":[{"where":{"and":[{"href_matches":"/*"},{"not":{"selector_matches":".no-prefetch"}},{"not":{"selector_matches":"[rel~=nofollow]"}}]},"eagerness":"moderate"}]}</script>`
178
- : "";
179
-
180
- const body = enhanceImages(compiled.html, context);
181
-
182
- return {
183
- meta: compiled.meta,
184
- html: `<!doctype html>
185
- <html lang="en">
186
- <head>
187
- <meta charset="utf-8">
188
- <meta name="viewport" content="width=device-width, initial-scale=1">
189
- <title>${escapeHtml(title)}</title>${descriptionTag}
190
- <link rel="icon" href="${favicon}">
191
- ${cssLinks}${transitions}${speculation}
192
- </head>
193
- <body>
194
- ${body}
195
- ${scripts}
196
- </body>
197
- </html>`,
198
- assets: compiled.assets,
199
- warnings: compiled.warnings
200
- };
201
- }
202
-
203
- /**
204
- * Harden every `<img>` in the assembled page body — compile-time only, zero
205
- * runtime JS. Bare markdown images reflow the page as they decode (cumulative
206
- * layout shift — the literal "jump" on navigation) and load eagerly. This
207
- * stamps intrinsic `width`/`height` (read from the file on disk so the browser
208
- * reserves space), `decoding="async"` on all, and a load-priority split: the
209
- * first image is the LCP candidate (eager + `fetchpriority="high"`), the rest
210
- * lazy-load. Author-set attributes are never overwritten.
211
- * @param {string} html Assembled page body HTML.
212
- * @param {Paths} paths Resolved project paths.
213
- * @returns {string}
214
- */
215
- export function enhanceImages(html, paths) {
216
- let index = 0;
217
- return html.replace(/<img\b[^>]*?\/?>/g, (tag) => {
218
- const i = index++;
219
- const has = (/** @type {string} */ attr) => new RegExp(`\\b${attr}\\s*=`, "i").test(tag);
220
- /** @type {string[]} */
221
- const add = [];
222
- // Dimensions only when the author hasn't sized it — adding one axis to a
223
- // manually-sized image would distort its aspect ratio.
224
- if (!has("width") && !has("height")) {
225
- const dim = measureImage(srcOf(tag), paths);
226
- if (dim) add.push(`width="${dim.width}"`, `height="${dim.height}"`);
227
- }
228
- if (!has("decoding")) add.push(`decoding="async"`);
229
- if (i === 0) {
230
- // First image is the LCP candidate: stays eager, gets a priority hint.
231
- if (!has("fetchpriority")) add.push(`fetchpriority="high"`);
232
- } else if (!has("loading")) {
233
- add.push(`loading="lazy"`);
234
- }
235
- if (!add.length) return tag;
236
- return `${tag.replace(/\s*\/?>\s*$/, "")} ${add.join(" ")}>`;
237
- });
238
- }
239
-
240
- /**
241
- * Extract the `src` attribute value from an `<img>` tag, or "" if absent.
242
- * @param {string} tag
243
- * @returns {string}
244
- */
245
- function srcOf(tag) {
246
- const m = tag.match(/\bsrc\s*=\s*["']([^"']*)["']/i);
247
- return m ? m[1] : "";
248
- }
249
-
250
- /**
251
- * Read an image's intrinsic dimensions from disk, or null when the src is
252
- * remote/relative/unreadable. Resolution mirrors the asset emit: `/__wd/media/x`
253
- * comes from the shelf (`site/_`), other absolute paths from `site/pages`.
254
- * @param {string} src
255
- * @param {Paths} paths
256
- * @returns {{ width: number, height: number } | null}
257
- */
258
- function measureImage(src, paths) {
259
- if (!src || /^(https?:)?\/\//i.test(src) || src.startsWith("data:")) return null;
260
- let filePath;
261
- if (src.startsWith("/__wd/media/")) {
262
- filePath = path.join(paths.shelfRoot, src.slice("/__wd/media/".length));
263
- } else if (src.startsWith("/")) {
264
- filePath = path.join(paths.routesRoot, src.slice(1));
265
- } else {
266
- return null; // page-relative: the source directory is lost after assembly
267
- }
268
- try {
269
- const { width, height } = imageSize(fs.readFileSync(filePath));
270
- if (typeof width === "number" && typeof height === "number") return { width, height };
271
- } catch {
272
- /* missing or unreadable — degrade to no dimensions */
273
- }
274
- return null;
275
- }
276
-
277
- /**
278
- * Compile a source file into its body HTML, frontmatter, and assets (no page shell).
279
- * @param {string} file Absolute path to the source file.
280
- * @param {Paths} context Resolved project paths.
281
- * @param {string[]} [stack] Include stack for cycle detection.
282
- * @param {Record<string, unknown>} [vars] Initial static scope variables.
283
- * @returns {CompiledDocument}
284
- */
285
- export function compileDocument(file, context, stack = [], vars = {}) {
286
- const comp = createCompilation();
287
- const result = compileFile(file, context, stack, createScope(null, vars), comp, [], null);
288
- return { meta: result.meta, html: result.html, assets: comp.assets, warnings: comp.warnings };
289
- }
290
-
291
- /** @returns {Compilation} */
292
- function createCompilation() {
293
- return {
294
- assets: { skins: new Set(), scripts: new Set(), files: new Map(), runtime: false },
295
- state: new Map(),
296
- stores: new Set(),
297
- warnings: [],
298
- sectionCounter: 0
299
- };
300
- }
301
-
302
- /**
303
- * @param {Scope | null} parent
304
- * @param {Record<string, unknown>} [vars]
305
- * @returns {Scope}
306
- */
307
- function createScope(parent, vars = {}) {
308
- return { parent, vars: { ...vars } };
309
- }
310
-
311
- /**
312
- * Compile a single file: parse frontmatter, collect assets, render body.
313
- * @param {string} file
314
- * @param {Paths} context
315
- * @param {string[]} stack
316
- * @param {Scope} scope
317
- * @param {Compilation} comp
318
- * @param {string[]} sections
319
- * @param {string | null} loopItem
320
- * @returns {{ meta: Meta, html: string }}
321
- */
322
- function compileFile(file, context, stack, scope, comp, sections, loopItem) {
323
- const real = fs.realpathSync(file);
324
- if (stack.includes(real)) {
325
- throw new Error(`Include cycle detected: ${[...stack, real].map((p) => path.basename(p)).join(" -> ")}`);
326
- }
327
-
328
- const raw = fs.readFileSync(file, "utf8");
329
- const { meta, body } = parseFrontmatter(raw, file);
330
- collectColocatedAssets(file, context, comp.assets);
331
-
332
- if (path.extname(file) === ".md") {
333
- scanMarkdownHints(body, file, comp);
334
- return { meta, html: selectMd(meta).render(body, {}) };
335
- }
336
-
337
- // Expose this file's frontmatter to the body under `meta` so `{ meta.title }`,
338
- // `{ meta.tags }`, and `@loop meta.tags into tag` resolve as static values.
339
- /** @type {Ctx} */
340
- const ctx = { file, context, stack: [...stack, real], scope: createScope(scope, { meta }), comp, sections, loopItem, md: selectMd(meta) };
341
- return { meta, html: compileBody(body.replace(/\r\n?/g, "\n").split("\n"), ctx) };
342
- }
343
-
344
- /**
345
- * Split a raw file into its frontmatter `meta` and `body`.
346
- * @param {string} raw Full file contents.
347
- * @param {string} [file] Source path, used only for error messages.
348
- * @returns {{ meta: Meta, body: string }}
349
- */
350
- export function parseFrontmatter(raw, file) {
351
- if (!raw.startsWith("---\n")) return { meta: {}, body: raw };
352
- const end = raw.indexOf("\n---", 3);
353
- if (end === -1) {
354
- const where = file ? ` in ${file}` : "";
355
- throw new Error(`Unterminated frontmatter${where}: opening "---" has no closing "---". Use: --- on its own line to open and another --- to close, then the page body.`);
356
- }
357
- const front = raw.slice(4, end).trim();
358
- const body = raw.slice(end + 4).replace(/^\n/, "");
359
- /** @type {Meta} */
360
- const meta = {};
361
- for (const line of front.split("\n")) {
362
- const match = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
363
- if (match) meta[match[1]] = parseFrontmatterValue(match[2]);
364
- }
365
- return { meta, body };
366
- }
367
-
368
- // Frontmatter values are scalars, except an inline flow array `[a, b, c]`.
369
- // Block sequences (`- item` on following lines) are intentionally out of scope —
370
- // the parser stays single-pass and line-based.
371
- /**
372
- * @param {string} raw
373
- * @returns {FrontmatterValue}
374
- */
375
- function parseFrontmatterValue(raw) {
376
- const value = raw.trim();
377
- if (value.startsWith("[") && value.endsWith("]")) return parseInlineArray(value);
378
- return stripQuotes(value);
379
- }
380
-
381
- /**
382
- * @param {string} raw
383
- * @returns {string[]}
384
- */
385
- function parseInlineArray(raw) {
386
- const inner = raw.slice(1, -1);
387
- if (inner.trim() === "") return [];
388
- /** @type {string[]} */
389
- const items = [];
390
- let buf = "";
391
- let quote = null;
392
- let quoted = false;
393
- const push = () => {
394
- items.push(quoted ? buf : buf.trim());
395
- buf = "";
396
- quoted = false;
397
- };
398
- for (const char of inner) {
399
- if (quote) {
400
- if (char === quote) quote = null;
401
- else buf += char;
402
- } else if ((char === '"' || char === "'") && buf.trim() === "") {
403
- quote = char;
404
- quoted = true;
405
- buf = ""; // drop any whitespace between the comma and the opening quote
406
- } else if (char === ",") {
407
- push();
408
- } else {
409
- buf += char;
410
- }
411
- }
412
- push();
413
- return items;
414
- }
415
-
416
- // ---------------------------------------------------------------------------
417
- // Block parser: directives + prose segments
418
- // ---------------------------------------------------------------------------
419
-
420
- /**
421
- * Parse a `.wd` body line-by-line into HTML, mixing directives and prose.
422
- * @param {string[]} lines
423
- * @param {Ctx} ctx
424
- * @returns {string}
425
- */
426
- function compileBody(lines, ctx) {
427
- /** @type {string[]} */
428
- const out = [];
429
- /** @type {string[]} */
430
- let prose = [];
431
- let fence = null;
432
-
433
- const flush = () => {
434
- if (!prose.length) return;
435
- const text = prose.join("\n");
436
- prose = [];
437
- if (text.trim()) out.push(renderProse(text, ctx));
438
- };
439
-
440
- for (let i = 0; i < lines.length; i++) {
441
- const line = lines[i];
442
- const fenceMatch = line.match(/^(```+|~~~+)/);
443
- if (fence) {
444
- prose.push(line);
445
- if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) fence = null;
446
- continue;
447
- }
448
- if (fenceMatch) {
449
- fence = fenceMatch[1];
450
- prose.push(line);
451
- continue;
452
- }
453
-
454
- if (/^@include\s/.test(line)) {
455
- flush();
456
- out.push(handleInclude(line, ctx));
457
- continue;
458
- }
459
- if (/^@loop\s/.test(line)) {
460
- flush();
461
- const block = scanBlock(lines, i, /^@loop\s/, "@endloop", ctx.file);
462
- const split = splitEmptyBranch(block.body);
463
- out.push(handleLoop(line, split.body, split.empty, ctx));
464
- i = block.end;
465
- continue;
466
- }
467
- const container = line.match(/^:::\s*(.*)$/);
468
- if (container) {
469
- flush();
470
- if (!container[1].trim()) throw new Error(`Stray ::: close with no open container in ${ctx.file}`);
471
- const block = scanContainer(lines, i, ctx.file);
472
- out.push(handleContainer(container[1].trim(), block.body, ctx));
473
- i = block.end;
474
- continue;
475
- }
476
- if (/^:state\s/.test(line)) {
477
- flush();
478
- out.push(handleState(line, ctx));
479
- continue;
480
- }
481
- if (/^:store\s/.test(line)) {
482
- flush();
483
- out.push(handleStore(line, ctx));
484
- continue;
485
- }
486
- if (/^:fetch\s/.test(line)) {
487
- flush();
488
- out.push(handleFetch(line, ctx));
489
- continue;
490
- }
491
- if (/^:computed\s/.test(line)) {
492
- flush();
493
- out.push(handleComputed(line, ctx));
494
- continue;
495
- }
496
- if (/^:effect\s/.test(line)) {
497
- flush();
498
- out.push(handleEffect(line, ctx));
499
- continue;
500
- }
501
- if (/^:form\s/.test(line)) {
502
- flush();
503
- const block = scanBlock(lines, i, /^:form\s/, ":endform", ctx.file);
504
- out.push(handleForm(line, block.body, ctx));
505
- i = block.end;
506
- continue;
507
- }
508
- if (/^:input\s/.test(line)) {
509
- flush();
510
- out.push(handleInput(line, ctx));
511
- continue;
512
- }
513
- if (/^:textarea\s/.test(line)) {
514
- flush();
515
- out.push(handleTextarea(line, ctx));
516
- continue;
517
- }
518
- if (/^:select\s/.test(line)) {
519
- flush();
520
- const opts = [];
521
- let j = i + 1;
522
- while (j < lines.length && /^\s*-\s+/.test(lines[j])) { opts.push(lines[j]); j++; }
523
- out.push(handleSelect(line, opts, ctx));
524
- i = j - 1;
525
- continue;
526
- }
527
- const choiceMatch = line.match(/^:(checkbox|radio)\s/);
528
- if (choiceMatch) {
529
- flush();
530
- const opts = [];
531
- let j = i + 1;
532
- while (j < lines.length && /^\s*-\s+/.test(lines[j])) { opts.push(lines[j]); j++; }
533
- out.push(handleChoiceGroup(line, opts, ctx, /** @type {"checkbox" | "radio"} */ (choiceMatch[1])));
534
- i = j - 1;
535
- continue;
536
- }
537
- if (/^:bind\s/.test(line)) {
538
- flush();
539
- out.push(handleBind(line, ctx));
540
- continue;
541
- }
542
- if (/^:submit\s/.test(line)) {
543
- flush();
544
- out.push(handleSubmit(line, ctx));
545
- continue;
546
- }
547
- if (/^:button\s/.test(line)) {
548
- flush();
549
- out.push(handleButton(line, ctx));
550
- continue;
551
- }
552
- if (/^:if\s/.test(line)) {
553
- flush();
554
- const block = scanConditional(lines, i, ctx.file);
555
- out.push(handleIf(line, block.truthy, block.falsy, ctx));
556
- i = block.end;
557
- continue;
558
- }
559
- const demo = renderDemoDirective(line, ctx);
560
- if (demo) {
561
- flush();
562
- out.push(demo);
563
- continue;
564
- }
565
- if (/^@repeat\b/.test(line)) {
566
- throw new Error(`@repeat was replaced by @loop in ${ctx.file}. Use: @loop /data.json into item ... @endloop`);
567
- }
568
- if (/^:for\b/.test(line)) {
569
- throw new Error(`:for was replaced by @loop in ${ctx.file}. Use: @loop items into item ... @endloop`);
570
- }
571
- if (/^(@endloop|:endif|:endfor|:endform|:else)\s*$/.test(line)) {
572
- throw new Error(`Stray "${line.trim()}" with no matching opener in ${ctx.file}`);
573
- }
574
- prose.push(line);
575
- }
576
-
577
- flush();
578
- return out.join("\n");
579
- }
580
-
581
- /**
582
- * Capture lines from an opener until a matching close token, honoring nesting and fences.
583
- * @param {string[]} lines
584
- * @param {number} start Index of the opening line.
585
- * @param {RegExp} openRe Pattern that re-opens a nested block.
586
- * @param {string} endToken Literal closing token (e.g. `@endloop`).
587
- * @param {string} file Source path for errors.
588
- * @returns {{ body: string[], end: number }}
589
- */
590
- function scanBlock(lines, start, openRe, endToken, file) {
591
- /** @type {string[]} */
592
- const body = [];
593
- let depth = 0;
594
- let fence = null;
595
- for (let i = start + 1; i < lines.length; i++) {
596
- const line = lines[i];
597
- const fenceMatch = line.match(/^(```+|~~~+)/);
598
- if (fence) {
599
- if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) fence = null;
600
- body.push(line);
601
- continue;
602
- }
603
- if (fenceMatch) {
604
- fence = fenceMatch[1];
605
- body.push(line);
606
- continue;
607
- }
608
- if (openRe.test(line)) depth++;
609
- if (line.trim() === endToken) {
610
- if (depth === 0) return { body, end: i };
611
- depth--;
612
- }
613
- body.push(line);
614
- }
615
- throw new Error(`Missing ${endToken} for "${lines[start]}" in ${file}`);
616
- }
617
-
618
- /**
619
- * Split a `@loop` body at a top-level `@empty` into the rows body and the empty
620
- * branch. Honors nested `@loop … @endloop` (so an inner loop's `@empty` is not
621
- * mistaken for the outer one) and fenced code.
622
- * @param {string[]} body
623
- * @returns {{ body: string[], empty: string[] | null }}
624
- */
625
- function splitEmptyBranch(body) {
626
- /** @type {string[]} */
627
- const rows = [];
628
- /** @type {string[] | null} */
629
- let empty = null;
630
- let target = rows;
631
- let depth = 0;
632
- let fence = null;
633
- for (const line of body) {
634
- const fenceMatch = line.match(/^(```+|~~~+)/);
635
- if (fence) {
636
- if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) fence = null;
637
- target.push(line);
638
- continue;
639
- }
640
- if (fenceMatch) { fence = fenceMatch[1]; target.push(line); continue; }
641
- if (/^@loop\s/.test(line)) depth++;
642
- if (line.trim() === "@endloop") depth--;
643
- if (depth === 0 && line.trim() === "@empty") { empty = []; target = empty; continue; }
644
- target.push(line);
645
- }
646
- return { body: rows, empty };
647
- }
648
-
649
- /**
650
- * Capture the body of a `:::` container up to its matching close, honoring nesting.
651
- * @param {string[]} lines
652
- * @param {number} start Index of the opening line.
653
- * @param {string} file Source path for errors.
654
- * @returns {{ body: string[], end: number }}
655
- */
656
- function scanContainer(lines, start, file) {
657
- /** @type {string[]} */
658
- const body = [];
659
- let depth = 0;
660
- let fence = null;
661
- for (let i = start + 1; i < lines.length; i++) {
662
- const line = lines[i];
663
- const fenceMatch = line.match(/^(```+|~~~+)/);
664
- if (fence) {
665
- if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) fence = null;
666
- body.push(line);
667
- continue;
668
- }
669
- if (fenceMatch) {
670
- fence = fenceMatch[1];
671
- body.push(line);
672
- continue;
673
- }
674
- const marker = line.match(/^:::\s*(.*)$/);
675
- if (marker) {
676
- if (marker[1].trim()) {
677
- depth++;
678
- } else if (depth === 0) {
679
- return { body, end: i };
680
- } else {
681
- depth--;
682
- }
683
- }
684
- body.push(line);
685
- }
686
- throw new Error(`Missing closing ::: for "${lines[start]}" in ${file}`);
687
- }
688
-
689
- /**
690
- * Split an `:if … :else if … :else … :endif` chain into the first condition's
691
- * truthy body and a falsy body. A bare `:else` works as before. The first
692
- * `:else if B` is **desugared** into a nested `:if` that lives in the falsy
693
- * branch: the falsy body becomes `[":if B", …rest…, ":endif"]`, which re-enters
694
- * `compileBody`/`handleIf` recursively. A whole `:if/:else if/:else` chain
695
- * therefore compiles to nested `data-wd-if` regions the runtime already drives —
696
- * identical behavior for static, reactive, and loop-row conditionals.
697
- * @param {string[]} lines
698
- * @param {number} start Index of the `:if` line.
699
- * @param {string} file Source path for errors.
700
- * @returns {{ truthy: string[], falsy: string[], end: number }}
701
- */
702
- function scanConditional(lines, start, file) {
703
- /** @type {string[]} */
704
- const truthy = [];
705
- /** @type {string[]} */
706
- const falsy = [];
707
- let current = truthy;
708
- // "truthy": collecting the :if body. "else": a bare :else closed the chain —
709
- // no further branches allowed. "elseif": the first :else if was desugared into
710
- // a nested :if inside `falsy`; subsequent depth-0 :else if/:else lines belong to
711
- // that nested chain and are emitted verbatim for the recursive compile to split.
712
- let mode = "truthy";
713
- let depth = 0;
714
- let fence = null;
715
- for (let i = start + 1; i < lines.length; i++) {
716
- const line = lines[i];
717
- const fenceMatch = line.match(/^(```+|~~~+)/);
718
- if (fence) {
719
- if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) fence = null;
720
- current.push(line);
721
- continue;
722
- }
723
- if (fenceMatch) {
724
- fence = fenceMatch[1];
725
- current.push(line);
726
- continue;
727
- }
728
- if (/^:if\s/.test(line)) depth++;
729
- if (line.trim() === ":endif") {
730
- if (depth === 0) {
731
- if (mode === "elseif") falsy.push(":endif"); // close the synthesized nested :if
732
- return { truthy, falsy, end: i };
733
- }
734
- depth--;
735
- }
736
- if (depth === 0 && mode !== "elseif") {
737
- const t = line.trim();
738
- const elseIf = t.match(/^:else if\s+(.+?)\s*$/);
739
- if (elseIf) {
740
- if (mode === "else") throw new Error(`":else if" after ":else" in ${file}. ":else" must be the last branch — order the "else if" conditions before the bare ":else".`);
741
- falsy.push(`:if ${elseIf[1]}`); // desugar the chain tail into a nested :if
742
- current = falsy;
743
- mode = "elseif";
744
- continue;
745
- }
746
- if (t === ":else") {
747
- if (mode === "else") throw new Error(`Duplicate ":else" in ${file}. A conditional may have only one bare ":else".`);
748
- current = falsy;
749
- mode = "else";
750
- continue;
751
- }
752
- }
753
- current.push(line);
754
- }
755
- throw new Error(`Missing :endif for "${lines[start]}" in ${file}`);
756
- }
757
-
758
- // ---------------------------------------------------------------------------
759
- // Directive handlers
760
- // ---------------------------------------------------------------------------
761
-
762
- /**
763
- * @param {string} line
764
- * @param {Ctx} ctx
765
- * @returns {string}
766
- */
767
- function handleInclude(line, ctx) {
768
- const match = line.match(/^@include\s+(\S+)(?:\s+with\s+(.+))?$/);
769
- if (!match) throw new Error(`Malformed @include in ${ctx.file}: ${line}`);
770
- const target = resolveInclude(match[1], ctx.file, ctx.context);
771
- const args = parseIncludeArgs(match[2] || "", ctx);
772
- const scope = createScope(ctx.scope, args);
773
- const child = compileFile(target, ctx.context, ctx.stack, scope, ctx.comp, ctx.sections, ctx.loopItem);
774
- return child.html;
775
- }
776
-
777
- /**
778
- * @param {string} raw
779
- * @param {Ctx} ctx
780
- * @returns {Record<string, unknown>}
781
- */
782
- function parseIncludeArgs(raw, ctx) {
783
- /** @type {Record<string, unknown>} */
784
- const args = {};
785
- const re = /([A-Za-z0-9_-]+)=("[^"]*"|'[^']*'|\{[^}]*\}|\S+)/g;
786
- for (const match of raw.matchAll(re)) {
787
- const value = match[2];
788
- if (value.startsWith("{")) {
789
- const expr = value.slice(1, -1).trim();
790
- const resolved = lookupPath(expr, ctx);
791
- if (!resolved.found) {
792
- throw new Error(`@include argument ${match[1]}={ ${expr} } in ${ctx.file} does not match any value in scope`);
793
- }
794
- args[match[1]] = resolved.value;
795
- } else {
796
- args[match[1]] = parseScalar(value);
797
- }
798
- }
799
- return args;
800
- }
801
-
802
- /**
803
- * @param {string} header
804
- * @param {string[]} bodyLines
805
- * @param {Ctx} ctx
806
- * @returns {string}
807
- */
808
- function handleContainer(header, bodyLines, ctx) {
809
- let rest = header.trim();
810
- let tag = "section";
811
- /** @type {string[]} Static classes baked into class="". */
812
- const extraClass = [];
813
- /** @type {[string, string][]} Reactive loop-item class bindings (data-wd-each-class). */
814
- const eachClasses = [];
815
- /** @type {[string, string][]} Global state-driven class bindings (data-wd-class). */
816
- const stateClasses = [];
817
- let id = "";
818
- // Leading tag/name token (anything not starting with . or #). "section" keeps
819
- // the <section> tag; any other name becomes a <div> and also a class.
820
- const lead = rest.match(/^([^\s.#]\S*)/);
821
- let nameToken = "section";
822
- if (lead) { nameToken = lead[1]; rest = rest.slice(lead[0].length).trim(); }
823
- if (nameToken !== "section") { tag = "div"; extraClass.push(nameToken); }
824
- while (rest.length) {
825
- if (rest.startsWith("#")) {
826
- const m = rest.match(/^#(\S+)/);
827
- id = (m ? m[1] : "");
828
- rest = rest.slice((m ? m[0] : rest).length).trim();
829
- continue;
830
- }
831
- const cm = rest.match(/^\.([A-Za-z_][\w-]*)/);
832
- if (!cm) throw new Error(`Unexpected token "${rest.split(/\s+/)[0]}" in container "::: ${header}" in ${ctx.file}`);
833
- const cls = cm[1];
834
- rest = rest.slice(cm[0].length).trim();
835
- // Optional `when <predicate>` makes the class reactive. The predicate runs to
836
- // the next ` .`/` #` token or the end of the header.
837
- const whenMatch = rest.match(/^when\s+(.+?)(?=\s+[.#]|$)/);
838
- if (whenMatch) {
839
- rest = rest.slice(whenMatch[0].length).trim();
840
- const compiled = compileWhen(whenMatch[1].trim(), ctx);
841
- if (compiled.static) { if (compiled.value) extraClass.push(cls); }
842
- else if (compiled.item) eachClasses.push([cls, compiled.body]);
843
- else stateClasses.push([cls, compiled.body]);
844
- } else {
845
- extraClass.push(cls);
846
- }
847
- }
848
- const explicitId = Boolean(id);
849
- if (!id) id = `wd-s${++ctx.comp.sectionCounter}`;
850
-
851
- ctx.sections.push(id);
852
- let inner;
853
- try {
854
- inner = compileBody(bodyLines, ctx);
855
- } finally {
856
- ctx.sections.pop();
857
- }
858
- const idAttr = explicitId ? ` id="${escapeHtml(id)}"` : "";
859
- const classAttr = extraClass.length ? ` class="${escapeHtml(extraClass.join(" "))}"` : "";
860
- let classBind = "";
861
- if (eachClasses.length) { ctx.comp.assets.runtime = true; classBind += ` data-wd-each-class="${escapeHtml(JSON.stringify(eachClasses))}"`; }
862
- if (stateClasses.length) { ctx.comp.assets.runtime = true; classBind += ` data-wd-class="${escapeHtml(JSON.stringify(stateClasses))}"`; }
863
- return `<${tag}${idAttr}${classAttr}${classBind}>\n${inner}\n</${tag}>`;
864
- }
865
-
866
- /**
867
- * @param {string} line
868
- * @param {Ctx} ctx
869
- * @returns {string}
870
- */
871
- function handleState(line, ctx) {
872
- const match = line.match(/^:state\s+([A-Za-z_$][\w$]*)\s*=\s*(.+?)(\s+persist)?$/);
873
- if (!match) throw new Error(`Malformed :state in ${ctx.file}: ${line}`);
874
- const value = parseStateValue(match[2]);
875
- const key = declareState(match[1], value, ctx);
876
- const persistAttr = match[3] ? ` data-wd-persist="${key}"` : "";
877
- return `<script type="application/json" data-wd-state${persistAttr}>${safeScriptJson({ [key]: value })}</script>`;
878
- }
879
-
880
- /**
881
- * Register a state key in the current section scope, enabling the runtime.
882
- * @param {string} name
883
- * @param {unknown} value
884
- * @param {Ctx} ctx
885
- * @returns {string} The fully-qualified state key.
886
- */
887
- function declareState(name, value, ctx) {
888
- if (ctx.loopItem) throw new Error(`State cannot be declared inside a reactive @loop body (${ctx.file})`);
889
- if (ctx.comp.stores.has(name)) throw new Error(`State "${name}" collides with a :store of the same name in ${ctx.file}. Use: :store name = value for the global, or rename one.`);
890
- const key = ctx.sections.length ? `${ctx.sections.at(-1)}:${name}` : name;
891
- if (ctx.comp.state.has(key)) throw new Error(`State "${name}" is declared twice in the same scope (${ctx.file})`);
892
- ctx.comp.state.set(key, value);
893
- ctx.comp.assets.runtime = true;
894
- return key;
895
- }
896
-
897
- /**
898
- * @param {string} line
899
- * @param {Ctx} ctx
900
- * @returns {string}
901
- */
902
- function handleStore(line, ctx) {
903
- const match = line.match(/^:store\s+([A-Za-z_$][\w$]*)\s*=\s*(.+?)(\s+ephemeral)?$/);
904
- if (!match) throw new Error(`Malformed :store in ${ctx.file}: ${line}. Use: :store name = value [ephemeral]`);
905
- const value = parseStateValue(match[2]);
906
- const name = declareStore(match[1], value, ctx);
907
- const ephemeral = match[3] ? " data-wd-store-ephemeral" : "";
908
- return `<script type="application/json" data-wd-store="${name}"${ephemeral}>${safeScriptJson(value)}</script>`;
909
- }
910
-
911
- /**
912
- * Register a page-global store. The bare name is added to `comp.state` so every
913
- * resolver (interpolation, :if, @loop, :computed, actions) sees it, and tracked
914
- * in `comp.stores` for collision checks. Never section-scoped.
915
- * @param {string} name
916
- * @param {unknown} value
917
- * @param {Ctx} ctx
918
- * @returns {string} The store name (also its bare state key).
919
- */
920
- function declareStore(name, value, ctx) {
921
- if (ctx.comp.stores.has(name)) throw new Error(`Store "${name}" is declared twice in ${ctx.file}. Use: :store name = value`);
922
- if (ctx.comp.state.has(name)) throw new Error(`Store "${name}" collides with a :state of the same name in ${ctx.file}. Use: :store name = value for the global, or rename one.`);
923
- ctx.comp.stores.add(name);
924
- ctx.comp.state.set(name, value);
925
- ctx.comp.assets.runtime = true;
926
- return name;
927
- }
928
-
929
- /**
930
- * Seed a `<name>_error` state key (null) if absent. Shared by :fetch and the
931
- * round-trip :form so error fallbacks have a key to bind.
932
- * @param {string} key
933
- * @param {Ctx} ctx
934
- * @returns {void}
935
- */
936
- function declareErrorState(key, ctx) {
937
- const errorKey = `${key}_error`;
938
- if (!ctx.comp.state.has(errorKey)) ctx.comp.state.set(errorKey, null);
939
- }
940
-
941
- const FETCH_USE =
942
- 'Use: :fetch name from "url" [method=…] [timeout=ms] [retry=N] [when=visible] [headers=key] [body=key] [refresh=url]';
943
-
944
- /**
945
- * Parse a keyword-arg `:fetch` directive into a lifecycle-aware marker.
946
- * Auto-declares four state keys (value/error/loading/empty), seeds them, and
947
- * emits `data-wd-fetch-*` attributes (url/method/when/timeout/retry/headers/
948
- * body/deps) consumed by the runtime's `startFetch`.
949
- * @param {string} line
950
- * @param {Ctx} ctx
951
- * @returns {string}
952
- */
953
- function handleFetch(line, ctx) {
954
- const head = line.match(/^:fetch\s+([A-Za-z_$][\w$]*)\s+from\s+("[^"]+"|\S+)\s*(.*)$/);
955
- if (!head) throw new Error(`Malformed :fetch in ${ctx.file}: ${line}. ${FETCH_USE}`);
956
- const name = head[1];
957
- const url = validateFetchUrl(stripQuotes(head[2]), ctx);
958
- /** @type {Record<string, string>} */
959
- const opts = {};
960
- for (const part of head[3].trim().split(/\s+/).filter(Boolean)) {
961
- const kv = part.match(/^([A-Za-z]+)=(.+)$/);
962
- if (!kv) throw new Error(`Unknown :fetch option "${part}" in ${ctx.file}. ${FETCH_USE}`);
963
- const optName = kv[1];
964
- if (!["method", "when", "timeout", "retry", "headers", "body", "refresh"].includes(optName)) {
965
- throw new Error(`Unknown :fetch option "${optName}" in ${ctx.file}. ${FETCH_USE}`);
966
- }
967
- opts[optName] = stripQuotes(kv[2]);
968
- }
969
-
970
- if (opts.method && !["GET", "POST", "PUT", "PATCH", "DELETE"].includes(opts.method.toUpperCase())) {
971
- throw new Error(`:fetch method "${opts.method}" is not allowed in ${ctx.file}. ${FETCH_USE}`);
972
- }
973
- if (opts.when && !["load", "visible"].includes(opts.when)) {
974
- throw new Error(`:fetch when "${opts.when}" is not allowed in ${ctx.file}. ${FETCH_USE}`);
975
- }
976
- for (const n of ["timeout", "retry"]) {
977
- if (opts[n] !== undefined && !/^\d+$/.test(opts[n])) {
978
- throw new Error(`:fetch ${n} must be a non-negative integer in ${ctx.file}. ${FETCH_USE}`);
979
- }
980
- }
981
- if (opts.refresh !== undefined) {
982
- // Layer 2: a 401 triggers a token-refresh POST to this URL, then one retry.
983
- // The new token is written back into the `headers=` state, so it is required.
984
- if (!opts.headers) {
985
- throw new Error(`:fetch refresh= needs headers= (the state key holding the token to renew) in ${ctx.file}. ${FETCH_USE}`);
986
- }
987
- opts.refresh = validateFetchUrl(opts.refresh, ctx, ":fetch refresh");
988
- }
989
-
990
- // Extract `{ path }` dependency keys from the URL (validated against poison
991
- // segments). The runtime fills them from state on each (re)fetch.
992
- /** @type {string[]} */
993
- const deps = [];
994
- for (const dep of url.matchAll(/\{\s*([A-Za-z_$][\w$.]*)\s*\}/g)) {
995
- validatePath(dep[1], ctx, FETCH_USE);
996
- const headKey = dep[1].split(".")[0];
997
- if (!deps.includes(headKey)) deps.push(headKey);
998
- }
999
-
1000
- // Auto-declare the four lifecycle keys. `name` is declared via declareState
1001
- // (collision-checked); the derived keys are seeded directly.
1002
- const key = declareState(name, null, ctx);
1003
- /** @type {Record<string, unknown>} */
1004
- const seeds = { [key]: null };
1005
- for (const [suffix, seed] of [["_error", null], ["_loading", false], ["_empty", false]]) {
1006
- const k = `${key}${suffix}`;
1007
- if (!ctx.comp.state.has(k)) ctx.comp.state.set(k, seed);
1008
- seeds[k] = seed;
1009
- }
1010
-
1011
- /** @param {string} n @param {string | null | false | undefined} v */
1012
- const attr = (n, v) => (v != null && v !== false && v !== "" ? ` data-wd-fetch-${n}="${escapeHtml(v)}"` : "");
1013
- const marker =
1014
- `<span data-wd-fetch data-wd-fetch-key="${key}" data-wd-fetch-url="${escapeHtml(url)}"` +
1015
- attr("method", opts.method && opts.method.toUpperCase()) +
1016
- attr("when", opts.when === "visible" ? "visible" : "") +
1017
- attr("timeout", opts.timeout) +
1018
- attr("retry", opts.retry) +
1019
- attr("headers", opts.headers && resolveStateKey(opts.headers, ctx)) +
1020
- attr("body", opts.body && resolveStateKey(opts.body, ctx)) +
1021
- attr("refresh", opts.refresh) +
1022
- attr("deps", deps.join(",")) +
1023
- `></span>`;
1024
- return `<script type="application/json" data-wd-state>${safeScriptJson(seeds)}</script>${marker}`;
1025
- }
1026
-
1027
- /**
1028
- * Validate a `:fetch` (or `refresh=`) URL's scheme at compile time. Mirrors the
1029
- * `:try` href guard: relative paths (`/`, `./`, `../`, bare), an `http(s)://`
1030
- * URL, or a leading `{ state }` interpolation are allowed; a protocol-relative
1031
- * `//host` or any non-http(s) scheme (`file:`, `data:`, `javascript:`, …) is
1032
- * rejected. Interpolated values are percent-encoded by the runtime, so a scheme
1033
- * cannot be injected through state at request time.
1034
- * @param {string} url
1035
- * @param {Ctx} ctx
1036
- * @param {string} [what] Option name for the error message.
1037
- * @returns {string}
1038
- */
1039
- function validateFetchUrl(url, ctx, what = ":fetch") {
1040
- const value = url.trim();
1041
- if (value !== url || value === "" || /[\u0000-\u001F\u007F]/.test(value)) {
1042
- throw new Error(`Unsafe ${what} URL "${escapeHtml(url)}" in ${ctx.file}. Use a relative path (/, ./, ../), an http(s):// URL, or a { state } interpolation.`);
1043
- }
1044
- if (value.startsWith("//")) {
1045
- throw new Error(`Unsafe ${what} URL "${escapeHtml(url)}" in ${ctx.file}. Protocol-relative URLs are not allowed; use http:// or https:// explicitly.`);
1046
- }
1047
- if (value.startsWith("{")) return value; // interpolation-first; the runtime percent-encodes state values
1048
- const scheme = value.match(/^([A-Za-z][A-Za-z0-9+.-]*):/);
1049
- if (scheme && !["http", "https"].includes(scheme[1].toLowerCase())) {
1050
- throw new Error(`Unsafe ${what} URL "${escapeHtml(url)}" in ${ctx.file}. The "${scheme[1]}:" scheme is not allowed; use http://, https://, or a relative path.`);
1051
- }
1052
- return value;
1053
- }
1054
-
1055
- /**
1056
- * @param {string} line
1057
- * @param {Ctx} ctx
1058
- * @returns {string}
1059
- */
1060
- function handleComputed(line, ctx) {
1061
- const match = line.match(/^:computed\s+([A-Za-z_$][\w$]*)\s*=\s*(.+)$/);
1062
- if (!match) throw new Error(`Malformed :computed in ${ctx.file}: ${line}. Use: :computed total = items.length * 4`);
1063
- const expr = compileComputedExpr(match[2].trim(), ctx);
1064
- /** @type {unknown} */
1065
- let initial;
1066
- try {
1067
- /** @param {string} key @param {string} [path] */
1068
- const read = (key, path) => getPath(ctx.comp.state.get(key), path ? path.split(".") : []);
1069
- initial = new Function("S", `return (${expr});`)(read);
1070
- } catch {
1071
- console.warn(`:computed "${match[2].trim()}" in ${ctx.file} could not be evaluated at build time; falling back to null. Check the expression.`);
1072
- initial = null;
1073
- }
1074
- const key = declareState(match[1], initial ?? null, ctx);
1075
- return `<span data-wd-computed data-wd-computed-key="${key}" data-wd-computed-expr="${escapeHtml(expr)}"></span><script type="application/json" data-wd-state>${safeScriptJson({ [key]: initial ?? null })}</script>`;
1076
- }
1077
-
1078
- /**
1079
- * Compile a `:computed` expression into safe JS over the `S(key, path)` reader.
1080
- * @param {string} raw
1081
- * @param {Ctx} ctx
1082
- * @returns {string}
1083
- */
1084
- function compileComputedExpr(raw, ctx) {
1085
- /** @type {string[]} */
1086
- const strings = [];
1087
- let expr = raw.replace(/"[^"\\]*"|'[^'\\]*'/g, (literal) => {
1088
- // JSON.stringify fully escapes embedded ", \, etc. so the re-inserted literal
1089
- // (line below) is an inert JS string and cannot terminate early to smuggle in
1090
- // live code. Mirrors the SAFE @loop where path (compileOperand).
1091
- strings.push(JSON.stringify(literal.slice(1, -1)));
1092
- return `__WDSTR${strings.length - 1}__`;
1093
- });
1094
- if (/["'\\`]/.test(expr)) {
1095
- throw new Error(`Unsupported string syntax in :computed expression "${raw}" (${ctx.file})`);
1096
- }
1097
- if (!/^[\w$.\s+\-*/%()<>=!&|]*$/.test(expr)) {
1098
- throw new Error(
1099
- `Unsupported syntax in :computed expression "${raw}" (${ctx.file}). Allowed: state names, numbers, strings, + - * / % ( ), comparisons, && || !.`
1100
- );
1101
- }
1102
- if (/(^|[^=!<>])=(?!=)/.test(expr)) {
1103
- throw new Error(`Assignment is not allowed in :computed expressions ("${raw}" in ${ctx.file})`);
1104
- }
1105
- expr = expr.replace(/[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/g, (ref) => {
1106
- if (/^__WDSTR\d+__$/.test(ref)) return ref;
1107
- if (["true", "false", "null"].includes(ref)) return ref;
1108
- const segs = ref.split(".");
1109
- if (segs.some((seg) => ["constructor", "prototype", "__proto__"].includes(seg))) {
1110
- throw new Error(`Path segment "${ref}" is not allowed in :computed expressions (${ctx.file})`);
1111
- }
1112
- const key = resolveStateKey(segs[0], ctx);
1113
- if (!key) {
1114
- throw new Error(`:computed references unknown state "${segs[0]}" in ${ctx.file}. Declare it with :state or :fetch first.`);
1115
- }
1116
- const rest = segs.slice(1).join(".");
1117
- return `S(${JSON.stringify(key)}${rest ? `,${JSON.stringify(rest)}` : ""})`;
1118
- });
1119
- return expr.replace(/__WDSTR(\d+)__/g, (_, index) => strings[Number(index)]);
1120
- }
1121
-
1122
- /**
1123
- * @param {string} line
1124
- * @param {string[]} bodyLines
1125
- * @param {Ctx} ctx
1126
- * @returns {string}
1127
- */
1128
- function handleForm(line, bodyLines, ctx) {
1129
- let rest = line.slice(":form".length).trim();
1130
- const rawAction = rest.match(/action="([^"]+)"/)?.[1];
1131
- const method = rest.match(/method="([^"]+)"/)?.[1] || "post";
1132
- const into = rest.match(/(?:^|\s)into\s+([A-Za-z_$][\w$]*)/)?.[1];
1133
- const leftover = rest
1134
- .replace(/action="[^"]+"/, "")
1135
- .replace(/method="[^"]+"/, "")
1136
- .replace(/(?:^|\s)into\s+[A-Za-z_$][\w$]*/, "")
1137
- .trim();
1138
- if ((!rawAction && !into) || leftover) {
1139
- throw new Error(
1140
- `Malformed :form in ${ctx.file}: ${line}. Use ':form into name' (client state), ':form action="/url"' (native post), or both (fetch round-trip into state).`
1141
- );
1142
- }
1143
- const action = rawAction ? validateFetchUrl(rawAction, ctx, ":form action") : undefined;
1144
- const inner = compileBody(bodyLines, ctx).trim();
1145
- if (!into) {
1146
- return `<form action="${escapeHtml(action)}" method="${escapeHtml(method)}">${inner}</form>`;
1147
- }
1148
- const key = declareState(into, null, ctx);
1149
- declareErrorState(key, ctx);
1150
- const actionAttrs = action ? ` action="${escapeHtml(action)}" method="${escapeHtml(method)}"` : "";
1151
- return `<script type="application/json" data-wd-state>${safeScriptJson({ [key]: null })}</script><form data-wd-form="${key}"${actionAttrs}>${inner}</form>`;
1152
- }
1153
-
1154
- /**
1155
- * @param {string} line
1156
- * @param {Ctx} ctx
1157
- * @returns {string}
1158
- */
1159
- function handleInput(line, ctx) {
1160
- const match = line.match(/^:input\s+([A-Za-z_][\w-]*)\s*(.*)$/);
1161
- if (!match) throw new Error(`Malformed :input in ${ctx.file}: ${line}`);
1162
- const attrs = [`name="${escapeHtml(match[1])}"`];
1163
- let type = "text";
1164
- let placeholder;
1165
- let hasAria = false;
1166
- const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
1167
- for (const token of (match[2] || "").matchAll(re)) {
1168
- if (token[3]) {
1169
- if (!["required", "autofocus", "disabled", "readonly"].includes(token[3])) {
1170
- throw new Error(`Unknown :input flag "${token[3]}" in ${ctx.file}`);
1171
- }
1172
- attrs.push(token[3]);
1173
- continue;
1174
- }
1175
- const value = stripQuotes(token[2]);
1176
- if (token[1] === "type") {
1177
- type = value;
1178
- continue;
1179
- }
1180
- if (!["placeholder", "value", "min", "max", "step", "pattern", "autocomplete", "aria-label", "aria-describedby"].includes(token[1])) {
1181
- throw new Error(`Unknown :input attribute "${token[1]}" in ${ctx.file}`);
1182
- }
1183
- if (token[1] === "placeholder") placeholder = value;
1184
- if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
1185
- attrs.push(`${token[1]}="${escapeHtml(value)}"`);
1186
- }
1187
- // Accessible name: if the author supplied neither aria-label nor aria-describedby,
1188
- // derive a non-visual aria-label from the placeholder, else from the field name.
1189
- // Never overrides an author-supplied aria attribute (zero layout impact).
1190
- if (!hasAria) {
1191
- attrs.push(`aria-label="${escapeHtml(placeholder || humanizeName(match[1]))}"`);
1192
- }
1193
- return `<input type="${escapeHtml(type)}" ${attrs.join(" ")}>`;
1194
- }
1195
-
1196
- // :bind <state> [placeholder="…"] [type=…] — a live two-way input bound to a
1197
- // declared :state. Updates state on every keystroke; reflects state back when
1198
- // not focused. The state must be declared first (with :state).
1199
- /**
1200
- * @param {string} line
1201
- * @param {Ctx} ctx
1202
- * @returns {string}
1203
- */
1204
- function handleBind(line, ctx) {
1205
- const match = line.match(/^:bind\s+([A-Za-z_$][\w$]*)\s*(.*)$/);
1206
- if (!match) throw new Error(`Malformed :bind in ${ctx.file}: ${line}. Use: :bind query placeholder="Search"`);
1207
- const key = resolveStateKey(match[1], ctx);
1208
- if (!key) {
1209
- throw new Error(`:bind ${match[1]} in ${ctx.file} has no matching state. Declare it first: :state ${match[1]} = ""`);
1210
- }
1211
- ctx.comp.assets.runtime = true;
1212
- let type = "text";
1213
- let placeholder;
1214
- let hasAria = false;
1215
- const attrs = [];
1216
- const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
1217
- for (const token of (match[2] || "").matchAll(re)) {
1218
- if (token[3]) {
1219
- if (!["required", "autofocus"].includes(token[3])) throw new Error(`Unknown :bind flag "${token[3]}" in ${ctx.file}`);
1220
- attrs.push(token[3]);
1221
- continue;
1222
- }
1223
- const value = stripQuotes(token[2]);
1224
- if (token[1] === "type") { type = value; continue; }
1225
- if (!["placeholder", "autocomplete", "aria-label", "aria-describedby"].includes(token[1])) {
1226
- throw new Error(`Unknown :bind attribute "${token[1]}" in ${ctx.file}`);
1227
- }
1228
- if (token[1] === "placeholder") placeholder = value;
1229
- if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
1230
- attrs.push(`${token[1]}="${escapeHtml(value)}"`);
1231
- }
1232
- // Accessible name (see handleInput): default a non-visual aria-label from the
1233
- // placeholder, else a humanized version of the bound state key. The author's own
1234
- // aria-label/aria-describedby always wins.
1235
- if (!hasAria) {
1236
- attrs.push(`aria-label="${escapeHtml(placeholder || humanizeName(match[1]))}"`);
1237
- }
1238
- const initial = ctx.comp.state.get(key);
1239
- const valueAttr = initial === undefined || initial === null ? "" : ` value="${escapeHtml(String(initial))}"`;
1240
- return `<input type="${escapeHtml(type)}" data-wd-bind-input="${key}"${valueAttr} ${attrs.join(" ")}>`;
1241
- }
1242
-
1243
- /**
1244
- * @param {string} line
1245
- * @param {Ctx} ctx
1246
- * @returns {string}
1247
- */
1248
- function handleSubmit(line, ctx) {
1249
- const match = line.match(/^:submit\s+"([^"]+)"\s*$/);
1250
- if (!match) throw new Error(`Malformed :submit in ${ctx.file}: ${line}. Use: :submit "Label"`);
1251
- return `<button type="submit">${escapeHtml(match[1])}</button>`;
1252
- }
1253
-
1254
- /**
1255
- * `:textarea name [placeholder="…"] [rows=N] [required]` → a `<textarea>`. Like
1256
- * `:input`, it derives a non-visual aria-label from the placeholder (else the
1257
- * humanized name) when the author supplies none. Captured by the runtime's
1258
- * FormData exactly like `:input` — no runtime change needed.
1259
- * @param {string} line
1260
- * @param {Ctx} ctx
1261
- * @returns {string}
1262
- */
1263
- function handleTextarea(line, ctx) {
1264
- const match = line.match(/^:textarea\s+([A-Za-z_][\w-]*)\s*(.*)$/);
1265
- if (!match) throw new Error(`Malformed :textarea in ${ctx.file}: ${line}. Use: :textarea name [placeholder="…"] [rows=N] [required]`);
1266
- const attrs = [`name="${escapeHtml(match[1])}"`];
1267
- let placeholder;
1268
- let hasAria = false;
1269
- const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
1270
- for (const token of (match[2] || "").matchAll(re)) {
1271
- if (token[3]) {
1272
- if (!["required", "autofocus", "disabled", "readonly"].includes(token[3])) {
1273
- throw new Error(`Unknown :textarea flag "${token[3]}" in ${ctx.file}`);
1274
- }
1275
- attrs.push(token[3]);
1276
- continue;
1277
- }
1278
- const value = stripQuotes(token[2]);
1279
- if (!["placeholder", "rows", "cols", "minlength", "maxlength", "autocomplete", "aria-label", "aria-describedby"].includes(token[1])) {
1280
- throw new Error(`Unknown :textarea attribute "${token[1]}" in ${ctx.file}`);
1281
- }
1282
- if (token[1] === "placeholder") placeholder = value;
1283
- if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
1284
- attrs.push(`${token[1]}="${escapeHtml(value)}"`);
1285
- }
1286
- if (!hasAria) {
1287
- attrs.push(`aria-label="${escapeHtml(placeholder || humanizeName(match[1]))}"`);
1288
- }
1289
- return `<textarea ${attrs.join(" ")}></textarea>`;
1290
- }
1291
-
1292
- /**
1293
- * `:select name [required]` followed by `- Label` list lines → a `<select>` with
1294
- * one `<option>` per label (value === label). Derives an aria-label from the
1295
- * humanized name when none is given. Captured by FormData like the other fields.
1296
- * @param {string} line
1297
- * @param {string[]} optionLines The following `- Label` lines consumed by dispatch.
1298
- * @param {Ctx} ctx
1299
- * @returns {string}
1300
- */
1301
- function handleSelect(line, optionLines, ctx) {
1302
- const match = line.match(/^:select\s+([A-Za-z_][\w-]*)\s*(.*)$/);
1303
- if (!match) throw new Error(`Malformed :select in ${ctx.file}: ${line}. Use: :select name [required] then "- Label" lines`);
1304
- const attrs = [`name="${escapeHtml(match[1])}"`];
1305
- let hasAria = false;
1306
- const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
1307
- for (const token of (match[2] || "").matchAll(re)) {
1308
- if (token[3]) {
1309
- if (!["required", "disabled", "autofocus"].includes(token[3])) {
1310
- throw new Error(`Unknown :select flag "${token[3]}" in ${ctx.file}`);
1311
- }
1312
- attrs.push(token[3]);
1313
- continue;
1314
- }
1315
- const value = stripQuotes(token[2]);
1316
- if (!["autocomplete", "aria-label", "aria-describedby"].includes(token[1])) {
1317
- throw new Error(`Unknown :select attribute "${token[1]}" in ${ctx.file}`);
1318
- }
1319
- if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
1320
- attrs.push(`${token[1]}="${escapeHtml(value)}"`);
1321
- }
1322
- if (!hasAria) {
1323
- attrs.push(`aria-label="${escapeHtml(humanizeName(match[1]))}"`);
1324
- }
1325
- const options = optionLines.map((l) => l.replace(/^\s*-\s+/, "").trim()).filter(Boolean);
1326
- if (!options.length) {
1327
- throw new Error(`:select "${match[1]}" in ${ctx.file} has no options. Add "- Label" lines beneath it.`);
1328
- }
1329
- const opts = options.map((o) => `<option value="${escapeHtml(o)}">${escapeHtml(o)}</option>`).join("");
1330
- return `<select ${attrs.join(" ")}>${opts}</select>`;
1331
- }
1332
-
1333
- /**
1334
- * `:checkbox name [required]` / `:radio name [required]` followed by `- Label`
1335
- * lines → a labelled group of `<input type=checkbox|radio>`, each sharing `name`
1336
- * with value === label and wrapped in its own `<label>`. The group is a
1337
- * `role="group"` / `role="radiogroup"` container with an aria-label (explicit or
1338
- * humanized from the name). Checkbox groups are marked `data-wd-multi="name"` so
1339
- * the runtime captures every checked value as an array (`FormData.getAll`); radio
1340
- * groups capture a single value like `:input`. Flags: `required` (radio → the
1341
- * group; not emitted on checkboxes, where "at least one" has no native HTML form),
1342
- * `disabled` (whole group), `autofocus` (first control).
1343
- * @param {string} line
1344
- * @param {string[]} optionLines The following `- Label` lines consumed by dispatch.
1345
- * @param {Ctx} ctx
1346
- * @param {"checkbox" | "radio"} kind
1347
- * @returns {string}
1348
- */
1349
- function handleChoiceGroup(line, optionLines, ctx, kind) {
1350
- const directive = `:${kind}`;
1351
- const match = line.match(kind === "checkbox" ? /^:checkbox\s+([A-Za-z_][\w-]*)\s*(.*)$/ : /^:radio\s+([A-Za-z_][\w-]*)\s*(.*)$/);
1352
- if (!match) throw new Error(`Malformed ${directive} in ${ctx.file}: ${line}. Use: ${directive} name [required] then "- Label" lines`);
1353
- const name = match[1];
1354
- const flags = [];
1355
- let ariaLabel = null;
1356
- let ariaDescribedby = null;
1357
- const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
1358
- for (const token of (match[2] || "").matchAll(re)) {
1359
- if (token[3]) {
1360
- if (!["required", "disabled", "autofocus"].includes(token[3])) {
1361
- throw new Error(`Unknown ${directive} flag "${token[3]}" in ${ctx.file}`);
1362
- }
1363
- flags.push(token[3]);
1364
- continue;
1365
- }
1366
- const value = stripQuotes(token[2]);
1367
- if (token[1] === "aria-label") ariaLabel = value;
1368
- else if (token[1] === "aria-describedby") ariaDescribedby = value;
1369
- else throw new Error(`Unknown ${directive} attribute "${token[1]}" in ${ctx.file}`);
1370
- }
1371
- const options = optionLines.map((l) => l.replace(/^\s*-\s+/, "").trim()).filter(Boolean);
1372
- if (!options.length) {
1373
- throw new Error(`${directive} "${name}" in ${ctx.file} has no options. Add "- Label" lines beneath it.`);
1374
- }
1375
- const isCheckbox = kind === "checkbox";
1376
- const groupAttrs = [`class="wd-${isCheckbox ? "checkboxes" : "radios"}"`, `role="${isCheckbox ? "group" : "radiogroup"}"`];
1377
- if (isCheckbox) groupAttrs.push(`data-wd-multi="${escapeHtml(name)}"`);
1378
- groupAttrs.push(`aria-label="${escapeHtml(ariaLabel || humanizeName(name))}"`);
1379
- if (ariaDescribedby) groupAttrs.push(`aria-describedby="${escapeHtml(ariaDescribedby)}"`);
1380
- const disabled = flags.includes("disabled");
1381
- const required = flags.includes("required");
1382
- const autofocus = flags.includes("autofocus");
1383
- const controls = options.map((opt, idx) => {
1384
- const a = [`type="${kind}"`, `name="${escapeHtml(name)}"`, `value="${escapeHtml(opt)}"`];
1385
- if (disabled) a.push("disabled");
1386
- if (required && !isCheckbox) a.push("required");
1387
- if (autofocus && idx === 0) a.push("autofocus");
1388
- return `<label><input ${a.join(" ")}> ${escapeHtml(opt)}</label>`;
1389
- }).join("");
1390
- return `<div ${groupAttrs.join(" ")}>${controls}</div>`;
1391
- }
1392
-
1393
- /**
1394
- * @param {string} line
1395
- * @param {Ctx} ctx
1396
- * @returns {string}
1397
- */
1398
- function handleButton(line, ctx) {
1399
- const match = line.match(/^:button\s+"([^"]+)"\s*->\s*(.+)$/);
1400
- if (!match) throw new Error(`Malformed :button in ${ctx.file}: ${line}`);
1401
- ctx.comp.assets.runtime = true;
1402
- const action = parseAction(match[2], ctx);
1403
- if (Array.isArray(action)) {
1404
- return `<button type="button" data-wd-actions="${escapeHtml(JSON.stringify(action))}">${escapeHtml(match[1])}</button>`;
1405
- }
1406
- const valueAttr = action.value === undefined ? "" : ` data-wd-value="${escapeHtml(JSON.stringify(action.value))}"`;
1407
- return `<button type="button" data-wd-action="${action.op}" data-wd-target="${action.target}"${valueAttr}>${escapeHtml(match[1])}</button>`;
1408
- }
1409
-
1410
- const EFFECT_USE = "Use: :effect watchedState -> action[; action…] (actions use the :button vocabulary).";
1411
-
1412
- /**
1413
- * Parse `:effect <watched> -> <actions>` into a zero-output marker the runtime
1414
- * watches: when `<watched>` state changes, it runs `<actions>` (the same `:button`
1415
- * action vocabulary, `;`-chained). For arbitrary side effects beyond `:computed`
1416
- * (derive state) and fetch deps (auto-refetch).
1417
- * @param {string} line
1418
- * @param {Ctx} ctx
1419
- * @returns {string}
1420
- */
1421
- function handleEffect(line, ctx) {
1422
- const match = line.match(/^:effect\s+([A-Za-z_$][\w$.]*)\s*->\s*(.+)$/);
1423
- if (!match) throw new Error(`Malformed :effect in ${ctx.file}: ${line}. ${EFFECT_USE}`);
1424
- const segs = validatePath(match[1], ctx, EFFECT_USE);
1425
- const key = resolveStateKey(segs[0], ctx);
1426
- if (!key) throw new Error(`:effect watches unknown state "${segs[0]}" in ${ctx.file}. Declare it first with :state ${segs[0]} = ...`);
1427
- ctx.comp.assets.runtime = true;
1428
- const watch = [key, ...segs.slice(1)].join(".");
1429
- const action = parseAction(match[2], ctx);
1430
- const actions = Array.isArray(action) ? action : [action];
1431
- return `<script type="application/json" data-wd-effect>${safeScriptJson({ watch, actions })}</script>`;
1432
- }
1433
-
1434
- /**
1435
- * @param {string} line
1436
- * @param {string[]} truthyLines
1437
- * @param {string[]} falsyLines
1438
- * @param {Ctx} ctx
1439
- * @returns {string}
1440
- */
1441
- function handleIf(line, truthyLines, falsyLines, ctx) {
1442
- const condition = line.replace(/^:if\s+/, "").trim();
1443
- // Fast path: a bare truthy dotted path (`:if open`, `:if item.done`). Keeps the
1444
- // existing markup/behavior identical. Anything with operators (`>`, `==`, `and`,
1445
- // `not`, …) falls through to the predicate path below.
1446
- const match = condition.match(/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)$/);
1447
- if (match) {
1448
- const segs = match[1].split(".");
1449
- const head = segs[0];
1450
-
1451
- // Per-row meta vars in :if — only valid inside a loop.
1452
- if (LOOP_META[head]) {
1453
- if (!ctx.loopMeta) throw new Error(`":if ${match[1]}" uses the loop meta variable "${head}" outside a @loop in ${ctx.file}. Use it inside a loop body.`);
1454
- if (ctx.loopItem) {
1455
- const truthy = compileBody(truthyLines, ctx).trim();
1456
- const falsy = compileBody(falsyLines, ctx).trim();
1457
- return `<span data-wd-each-if data-wd-meta="${LOOP_META[head]}"><template data-wd-if-true>${truthy}</template><template data-wd-if-false>${falsy}</template><span data-wd-each-if-out></span></span>`;
1458
- }
1459
- // static: the meta boolean is in scope — fall through to the static branch below.
1460
- }
1461
-
1462
- const staticValue = lookupVar(ctx.scope, head);
1463
- if (staticValue.found) {
1464
- const active = Boolean(getPath(staticValue.value, segs.slice(1)));
1465
- return compileBody(active ? truthyLines : falsyLines, ctx);
1466
- }
1467
-
1468
- if (ctx.loopItem && head === ctx.loopItem) {
1469
- const truthy = compileBody(truthyLines, ctx).trim();
1470
- const falsy = compileBody(falsyLines, ctx).trim();
1471
- const rest = segs.slice(1).join(".");
1472
- const pathAttr = ` data-wd-path="${escapeHtml(rest)}"`;
1473
- return `<span data-wd-each-if${pathAttr}><template data-wd-if-true>${truthy}</template><template data-wd-if-false>${falsy}</template><span data-wd-each-if-out></span></span>`;
1474
- }
1475
-
1476
- const key = resolveStateKey(head, ctx);
1477
- if (!key) {
1478
- throw new Error(`:if ${match[1]} in ${ctx.file} does not match a :state or in-scope value. Declare it first.`);
1479
- }
1480
- ctx.comp.assets.runtime = true;
1481
- const truthy = compileBody(truthyLines, ctx).trim();
1482
- const falsy = compileBody(falsyLines, ctx).trim();
1483
- const restPath = segs.slice(1).join(".");
1484
- const pathAttr = restPath ? ` data-wd-path="${escapeHtml(restPath)}"` : "";
1485
- const initialTruthy = Boolean(getPath(ctx.comp.state.get(key), segs.slice(1)));
1486
- const active = initialTruthy ? truthy : falsy;
1487
- return `<div data-wd-if="${key}"${pathAttr} data-wd-if-active="${initialTruthy}"><template data-wd-true>${truthy}</template><template data-wd-false>${falsy}</template><div data-wd-if-out>${active}</div></div>`;
1488
- }
1489
-
1490
- // Predicate path: a comparison / logical condition. Compiles through the same
1491
- // whitelist as `@loop … where` / `.class when` (with `not`), so it folds at
1492
- // build when static, drives a per-row each-if when it reads the loop item, and
1493
- // a global if-region (evaluated each render) when it reads state. No raw eval.
1494
- if (!condition) throw new Error(`Malformed :if in ${ctx.file}: ${line}. Use ":if name" or ":if a <op> b [and|or|not …]".`);
1495
- const compiled = compileWhen(condition, ctx, '":if"');
1496
- if (compiled.static) return compileBody(compiled.value ? truthyLines : falsyLines, ctx);
1497
- ctx.comp.assets.runtime = true;
1498
- const truthy = compileBody(truthyLines, ctx).trim();
1499
- const falsy = compileBody(falsyLines, ctx).trim();
1500
- const exprAttr = ` data-wd-if-expr="${escapeHtml(compiled.body)}"`;
1501
- if (compiled.item) {
1502
- return `<span data-wd-each-if${exprAttr}><template data-wd-if-true>${truthy}</template><template data-wd-if-false>${falsy}</template><span data-wd-each-if-out></span></span>`;
1503
- }
1504
- const initialTruthy = evalPredicate(compiled.body, undefined, ctx);
1505
- const active = initialTruthy ? truthy : falsy;
1506
- return `<div data-wd-if=""${exprAttr} data-wd-if-active="${initialTruthy}"><template data-wd-true>${truthy}</template><template data-wd-false>${falsy}</template><div data-wd-if-out>${active}</div></div>`;
1507
- }
1508
-
1509
- // The fixed corrective suggestion shown for any malformed @loop header.
1510
- const LOOP_USAGE = "Use: @loop src into item [where …] [sort by …] [reverse] [offset N] [limit N]";
1511
-
1512
- // Reserved per-row meta variables, mapped to their runtime marker token.
1513
- /** @type {Record<string, string>} */
1514
- const LOOP_META = { $index: "index", $number: "number", $first: "first", $last: "last", $count: "count" };
1515
-
1516
- /**
1517
- * Parse the optional clause tail of a `@loop` header in FIXED order:
1518
- * `[where P] [sort by key [asc|desc]] [reverse] [offset N] [limit N]`.
1519
- * @param {string} tail Everything after `@loop src into item`.
1520
- * @param {string} itemName
1521
- * @param {Ctx} ctx
1522
- * @returns {{ where: string|null, sort: {key:string,dir:string}|null, reverse: boolean, offset: NumArg|null, limit: NumArg|null, refsState: boolean }}
1523
- */
1524
- function parseLoopClauses(tail, itemName, ctx) {
1525
- // Peel clauses off the END in reverse fixed-order (limit, offset, reverse,
1526
- // sort by). Parsing from the tail avoids mistaking a state operand named
1527
- // `limit`/`offset` inside the `where` predicate for a clause keyword. Whatever
1528
- // remains must be `where …` (or empty); a clause keyword surviving in the
1529
- // remainder means the author wrote the clauses out of order.
1530
- let s = tail.trim();
1531
- /** @type {{key:string,dir:string}|null} */ let sort = null;
1532
- let reverse = false;
1533
- /** @type {NumArg|null} */ let offset = null;
1534
- /** @type {NumArg|null} */ let limit = null;
1535
- let refsState = false;
1536
- /** @returns {never} */
1537
- const bad = () => { throw new Error(`Malformed @loop clause in ${ctx.file}: "${tail.trim()}". ${LOOP_USAGE}`); };
1538
-
1539
- let m = s.match(/(^|\s)limit\s+(\d+|[A-Za-z_$][\w$]*)$/);
1540
- if (m) { limit = parseNumArg(m[2], ctx); refsState = refsState || limit.kind === "key"; s = s.slice(0, s.length - m[0].length + m[1].length).trim(); }
1541
-
1542
- m = s.match(/(^|\s)offset\s+(\d+|[A-Za-z_$][\w$]*)$/);
1543
- if (m) { offset = parseNumArg(m[2], ctx); refsState = refsState || offset.kind === "key"; s = s.slice(0, s.length - m[0].length + m[1].length).trim(); }
1544
-
1545
- m = s.match(/(^|\s)reverse$/);
1546
- if (m) { reverse = true; s = s.slice(0, s.length - m[0].length + m[1].length).trim(); }
1547
-
1548
- m = s.match(/(^|\s)sort\s+by\s+([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)(?:\s+(asc|desc))?$/);
1549
- if (m) {
1550
- const segs = m[2].split(".");
1551
- if (segs[0] !== itemName) throw new Error(`@loop sort key "${m[2]}" must start with the loop item "${itemName}" in ${ctx.file}. ${LOOP_USAGE}`);
1552
- const rest = segs.slice(1);
1553
- if (rest.some((seg) => ["constructor", "prototype", "__proto__"].includes(seg))) {
1554
- throw new Error(`Sort key "${m[2]}" is not allowed in @loop (${ctx.file})`);
1555
- }
1556
- sort = { key: rest.join("."), dir: m[3] || "asc" };
1557
- s = s.slice(0, s.length - m[0].length + m[1].length).trim();
1558
- }
1559
-
1560
- /** @type {string|null} */ let where = null;
1561
- if (s.length) {
1562
- m = s.match(/^where\s+(.+)$/);
1563
- if (!m) return bad(); // leftover non-where text → clauses written out of order
1564
- where = m[1].trim();
1565
- // `sort by`/`reverse` are never valid where operands; their presence in the
1566
- // predicate means a clause was written before `where` finished (wrong order).
1567
- if (/(^|\s)(sort\s+by\s|reverse(\s|$))/.test(where)) bad();
1568
- }
1569
- return { where, sort, reverse, offset, limit, refsState };
1570
- }
1571
-
1572
- /**
1573
- * A loop offset/limit argument: a non-negative integer literal or a state key.
1574
- * @typedef {{ kind: "literal", value: number } | { kind: "key", value: string }} NumArg
1575
- */
1576
-
1577
- /**
1578
- * @param {string} tok
1579
- * @param {Ctx} ctx
1580
- * @returns {NumArg}
1581
- */
1582
- function parseNumArg(tok, ctx) {
1583
- if (/^\d+$/.test(tok)) return { kind: "literal", value: Number(tok) };
1584
- if (/^[A-Za-z_$][\w$]*$/.test(tok)) {
1585
- const key = resolveStateKey(tok, ctx);
1586
- if (!key) throw new Error(`@loop offset/limit "${tok}" in ${ctx.file} is neither a non-negative integer nor a declared :state. ${LOOP_USAGE}`);
1587
- return { kind: "key", value: key };
1588
- }
1589
- throw new Error(`@loop offset/limit "${tok}" in ${ctx.file} is invalid. ${LOOP_USAGE}`);
1590
- }
1591
-
1592
- /** @param {NumArg} arg @returns {string} */
1593
- function numArgAttr(arg) {
1594
- return arg.kind === "literal" ? String(arg.value) : `key:${arg.value}`;
1595
- }
1596
-
1597
- /**
1598
- * @param {string} line
1599
- * @param {string[]} bodyLines
1600
- * @param {string[] | null} emptyLines
1601
- * @param {Ctx} ctx
1602
- * @returns {string}
1603
- */
1604
- function handleLoop(line, bodyLines, emptyLines, ctx) {
1605
- const match = line.match(/^@loop\s+(.+?)\s+into\s+([A-Za-z_$][\w$]*)(\s+.+?)?\s*$/);
1606
- if (!match) throw new Error(`Malformed @loop in ${ctx.file}: ${line}. ${LOOP_USAGE}`);
1607
- const source = stripQuotes(match[1].trim());
1608
- const itemName = match[2];
1609
- const clauses = match[3] ? parseLoopClauses(match[3], itemName, ctx) : { where: null, sort: null, reverse: false, offset: null, limit: null, refsState: false };
1610
- const where = clauses.where ? compilePredicate(clauses.where, itemName, ctx) : null;
1611
- /** @type {LoopOpts} */
1612
- const opts = { where, sort: clauses.sort, reverse: clauses.reverse, offset: clauses.offset, limit: clauses.limit, empty: emptyLines, clauseRefsState: clauses.refsState };
1613
-
1614
- if (source.startsWith("/") || source.startsWith("./") || source.startsWith("../") || source.endsWith(".json")) {
1615
- const dataFile = resolveInclude(source, ctx.file, ctx.context, true);
1616
- const rows = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1617
- if (!Array.isArray(rows)) throw new Error(`@loop data must be a JSON array: ${dataFile}`);
1618
- return loopOverData(rows, itemName, bodyLines, ctx, opts);
1619
- }
1620
-
1621
- const resolved = lookupPath(source, ctx);
1622
- if (resolved.found) {
1623
- if (!Array.isArray(resolved.value)) {
1624
- throw new Error(`@loop ${source} in ${ctx.file} found an in-scope value, but it is not a list`);
1625
- }
1626
- return loopOverData(resolved.value, itemName, bodyLines, ctx, opts);
1627
- }
1628
-
1629
- // A bare name OR a dotted path resolving to declared :state (e.g. team.members).
1630
- const segs = source.split(".");
1631
- if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(source)) {
1632
- if (segs.some((seg) => ["constructor", "prototype", "__proto__"].includes(seg))) {
1633
- throw new Error(`@loop source "${source}" is not allowed in ${ctx.file}`);
1634
- }
1635
- const key = resolveStateKey(segs[0], ctx);
1636
- if (key) {
1637
- const fullKey = segs.length > 1 ? `${key}.${segs.slice(1).join(".")}` : key;
1638
- return reactiveLoop(fullKey, itemName, bodyLines, ctx, opts);
1639
- }
1640
- }
1641
-
1642
- throw new Error(
1643
- `@loop source "${source}" in ${ctx.file} was not found. Loop over a JSON file (@loop /data.json into row), an in-scope value, or a :state list.`
1644
- );
1645
- }
1646
-
1647
- // A static source (JSON file / in-scope value). No `where`, or a `where` that
1648
- // only reads the loop item → filter at build time and stay zero-JS. A `where`
1649
- // that reads :state → becomes a reactive filtered loop with the rows baked in.
1650
- /**
1651
- * A compiled `@loop … where` predicate.
1652
- * @typedef {object} Predicate
1653
- * @property {string} body Safe JS boolean expression over `I()`/`S()`/`C()`.
1654
- * @property {boolean} refsState Whether the predicate reads declared state.
1655
- */
1656
-
1657
- /**
1658
- * Loop clause configuration shared by the static and reactive paths.
1659
- * @typedef {object} LoopOpts
1660
- * @property {Predicate | null} where
1661
- * @property {{ key: string, dir: string } | null} sort
1662
- * @property {boolean} reverse
1663
- * @property {NumArg | null} offset
1664
- * @property {NumArg | null} limit
1665
- * @property {string[] | null} empty Empty-branch body lines, if any.
1666
- * @property {boolean} clauseRefsState Whether offset/limit reference state.
1667
- */
1668
-
1669
- /**
1670
- * Build-time pipeline over already-resolved rows: filter → sort → reverse →
1671
- * offset → limit. Used when source + every clause arg are static.
1672
- * @param {unknown[]} rows
1673
- * @param {Predicate | null} where
1674
- * @param {LoopOpts} opts
1675
- * @param {Ctx} ctx
1676
- * @returns {unknown[]}
1677
- */
1678
- function pipelineRows(rows, where, opts, ctx) {
1679
- let list = where ? rows.filter((row) => evalPredicate(where.body, row, ctx)) : rows.slice();
1680
- if (opts.sort) {
1681
- const k = opts.sort.key;
1682
- const dir = opts.sort.dir === "desc" ? -1 : 1;
1683
- list = list.map((value, index) => ({ value, index })).sort((a, b) => {
1684
- const av = getPath(a.value, k ? k.split(".") : []);
1685
- const bv = getPath(b.value, k ? k.split(".") : []);
1686
- let c = typeof av === "number" && typeof bv === "number" ? av - bv : String(av).localeCompare(String(bv));
1687
- return (c || a.index - b.index) * dir;
1688
- }).map((w) => w.value);
1689
- }
1690
- if (opts.reverse) list.reverse();
1691
- const off = opts.offset && opts.offset.kind === "literal" ? opts.offset.value : 0;
1692
- if (off) list = list.slice(off);
1693
- if (opts.limit && opts.limit.kind === "literal") list = list.slice(0, opts.limit.value);
1694
- return list;
1695
- }
1696
-
1697
- /**
1698
- * @param {unknown[]} rows
1699
- * @param {string} itemName
1700
- * @param {string[]} bodyLines
1701
- * @param {Ctx} ctx
1702
- * @param {LoopOpts} opts
1703
- * @returns {string}
1704
- */
1705
- function loopOverData(rows, itemName, bodyLines, ctx, opts) {
1706
- // Reactive when the where reads state OR an offset/limit references a state key.
1707
- const reactive = (opts.where && opts.where.refsState) || opts.clauseRefsState;
1708
- if (reactive) return reactiveLoop(null, itemName, bodyLines, ctx, { ...opts, data: rows });
1709
- return staticUnroll(pipelineRows(rows, opts.where, opts, ctx), itemName, bodyLines, ctx, opts.empty);
1710
- }
1711
-
1712
- // Compile a `where` predicate to a safe JS boolean expression over I()/S()/C().
1713
- // Conditions (operand <op> operand) join with `and`/`or`; operands are loop-item
1714
- // paths, declared :state, numbers, or strings. No identifiers survive un-mapped.
1715
- /**
1716
- * @param {string} raw
1717
- * @param {string} itemName
1718
- * @param {Ctx} ctx
1719
- * @returns {Predicate}
1720
- */
1721
- function compilePredicate(raw, itemName, ctx) {
1722
- const parts = raw.split(/\s+(and|or)\s+/i);
1723
- /** @type {string[]} */
1724
- const pieces = [];
1725
- let refsState = false;
1726
- for (let i = 0; i < parts.length; i++) {
1727
- if (i % 2 === 1) { pieces.push(parts[i].toLowerCase() === "and" ? "&&" : "||"); continue; }
1728
- const cond = compileCondition(parts[i].trim(), itemName, ctx);
1729
- refsState = refsState || cond.usesState;
1730
- pieces.push(`(${cond.expr})`);
1731
- }
1732
- return { body: pieces.join(" "), refsState };
1733
- }
1734
-
1735
- /**
1736
- * @param {string} cond
1737
- * @param {string} itemName
1738
- * @param {Ctx} ctx
1739
- * @returns {{ expr: string, usesState: boolean }}
1740
- */
1741
- function compileCondition(cond, itemName, ctx) {
1742
- const m = cond.match(/^(.+?)\s+(contains|==|!=|>=|<=|>|<)\s+(.+)$/i);
1743
- if (!m) throw new Error(`Malformed where-condition "${cond}" in ${ctx.file}. Use: ${itemName}.field contains state, or ${itemName}.field <op> value.`);
1744
- const left = compileOperand(m[1].trim(), itemName, ctx);
1745
- const right = compileOperand(m[3].trim(), itemName, ctx);
1746
- const usesState = left.usesState || right.usesState;
1747
- const op = m[2].toLowerCase();
1748
- if (op === "contains") return { expr: `C(${left.code}, ${right.code})`, usesState };
1749
- return { expr: `${left.code} ${op} ${right.code}`, usesState };
1750
- }
1751
-
1752
- /**
1753
- * @param {string} tok
1754
- * @param {string} itemName
1755
- * @param {Ctx} ctx
1756
- * @returns {{ code: string, usesState: boolean }}
1757
- */
1758
- function compileOperand(tok, itemName, ctx) {
1759
- if (/^"[^"]*"$/.test(tok) || /^'[^']*'$/.test(tok)) return { code: JSON.stringify(tok.slice(1, -1)), usesState: false };
1760
- if (/^-?\d+(?:\.\d+)?$/.test(tok)) return { code: tok, usesState: false };
1761
- if (["true", "false", "null"].includes(tok)) return { code: tok, usesState: false };
1762
- if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(tok)) {
1763
- throw new Error(`Unsupported operand "${tok}" in @loop where (${ctx.file}). Use ${itemName}.field, a :state name, a number, or a "string".`);
1764
- }
1765
- const segs = tok.split(".");
1766
- if (segs.some((seg) => ["constructor", "prototype", "__proto__"].includes(seg))) {
1767
- throw new Error(`Path "${tok}" is not allowed in @loop where (${ctx.file})`);
1768
- }
1769
- if (segs[0] === itemName) return { code: `I(${JSON.stringify(segs.slice(1).join("."))})`, usesState: false };
1770
- const key = resolveStateKey(segs[0], ctx);
1771
- if (!key) {
1772
- throw new Error(`@loop where references unknown name "${segs[0]}" in ${ctx.file}. Use the loop item (${itemName}.field) or a declared :state.`);
1773
- }
1774
- const rest = segs.slice(1).join(".");
1775
- return { code: `S(${JSON.stringify(key)}${rest ? `, ${JSON.stringify(rest)}` : ""})`, usesState: true };
1776
- }
1777
-
1778
- /** @param {unknown} a @param {unknown} b @returns {boolean} */
1779
- const containsHelper = (a, b) => String(a ?? "").toLowerCase().includes(String(b ?? "").toLowerCase());
1780
-
1781
- /**
1782
- * Evaluate a compiled predicate against a row at build time.
1783
- * @param {string} body
1784
- * @param {unknown} item
1785
- * @param {Ctx} ctx
1786
- * @returns {boolean}
1787
- */
1788
- function evalPredicate(body, item, ctx) {
1789
- try {
1790
- /** @param {string} [p] */
1791
- const I = (p) => getPath(item, p ? p.split(".") : []);
1792
- /** @param {string} k @param {string} [r] */
1793
- const S = (k, r) => getPath(ctx.comp.state.get(k), r ? r.split(".") : []);
1794
- return Boolean(new Function("I", "S", "C", `return (${body});`)(I, S, containsHelper));
1795
- } catch {
1796
- console.warn(`@loop where predicate "${body}" in ${ctx.file} could not be evaluated at build time; treating the row as excluded. Check the condition.`);
1797
- return false;
1798
- }
1799
- }
1800
-
1801
- /**
1802
- * Compile one operand of a `::: … .class when <predicate>` expression. Like the
1803
- * `@loop where` operand, but also folds a static-scope value (a loop-unrolled
1804
- * item field or include arg) to its build-time literal, so a fully-static
1805
- * predicate can be evaluated at compile time. Mirrors `:if`'s scope→item→state
1806
- * resolution order.
1807
- * @param {string} tok
1808
- * @param {Ctx} ctx
1809
- * @param {string} what Directive label for error messages.
1810
- * @returns {{ code: string, state: boolean, item: boolean }}
1811
- */
1812
- function compileWhenOperand(tok, ctx, what) {
1813
- if (/^"[^"]*"$/.test(tok) || /^'[^']*'$/.test(tok)) return { code: JSON.stringify(tok.slice(1, -1)), state: false, item: false };
1814
- if (/^-?\d+(?:\.\d+)?$/.test(tok)) return { code: tok, state: false, item: false };
1815
- if (["true", "false", "null"].includes(tok)) return { code: tok, state: false, item: false };
1816
- if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(tok)) {
1817
- throw new Error(`Unsupported operand "${tok}" in ${what} (${ctx.file}). Use item.field, a :state name, a number, or a "string".`);
1818
- }
1819
- const segs = tok.split(".");
1820
- if (segs.some((seg) => ["constructor", "prototype", "__proto__"].includes(seg))) {
1821
- throw new Error(`Path "${tok}" is not allowed in ${what} (${ctx.file})`);
1822
- }
1823
- const scoped = lookupVar(ctx.scope, segs[0]);
1824
- if (scoped.found) return { code: JSON.stringify(getPath(scoped.value, segs.slice(1)) ?? null), state: false, item: false };
1825
- if (ctx.loopItem && segs[0] === ctx.loopItem) return { code: `I(${JSON.stringify(segs.slice(1).join("."))})`, state: false, item: true };
1826
- const key = resolveStateKey(segs[0], ctx);
1827
- if (!key) throw new Error(`${what} references unknown name "${segs[0]}" in ${ctx.file}. Use a loop item field, a declared :state, a number, or a "string".`);
1828
- const rest = segs.slice(1).join(".");
1829
- return { code: `S(${JSON.stringify(key)}${rest ? `, ${JSON.stringify(rest)}` : ""})`, state: true, item: false };
1830
- }
1831
-
1832
- /**
1833
- * Compile a `::: … .class when <predicate>`. Allows `:if`-style bare truthy
1834
- * paths and `where`-style `left <op> right` conditions joined by `and`/`or`.
1835
- * Folds to a static verdict when every operand is build-known, else returns a
1836
- * runtime body over I()/S()/C() plus whether it reads the reactive loop item
1837
- * (which decides data-wd-each-class vs the global data-wd-class).
1838
- * @param {string} raw
1839
- * @param {Ctx} ctx
1840
- * @param {string} [what] Directive label for error messages.
1841
- * @returns {{ static: true, value: boolean } | { static: false, body: string, item: boolean }}
1842
- */
1843
- function compileWhen(raw, ctx, what = '"::: … when"') {
1844
- const parts = raw.split(/\s+(and|or)\s+/i);
1845
- /** @type {string[]} */
1846
- const pieces = [];
1847
- let usesState = false;
1848
- let usesItem = false;
1849
- for (let i = 0; i < parts.length; i++) {
1850
- if (i % 2 === 1) { pieces.push(parts[i].toLowerCase() === "and" ? "&&" : "||"); continue; }
1851
- let seg = parts[i].trim();
1852
- // Optional leading `not` negates the whole sub-condition.
1853
- let negate = false;
1854
- if (/^not\s+/i.test(seg)) { negate = true; seg = seg.replace(/^not\s+/i, "").trim(); }
1855
- const opMatch = seg.match(/^(.+?)\s+(contains|==|!=|>=|<=|>|<)\s+(.+)$/i);
1856
- let expr;
1857
- if (opMatch) {
1858
- const left = compileWhenOperand(opMatch[1].trim(), ctx, what);
1859
- const right = compileWhenOperand(opMatch[3].trim(), ctx, what);
1860
- usesState = usesState || left.state || right.state;
1861
- usesItem = usesItem || left.item || right.item;
1862
- const op = opMatch[2].toLowerCase();
1863
- expr = op === "contains" ? `C(${left.code}, ${right.code})` : `${left.code} ${op} ${right.code}`;
1864
- } else {
1865
- const only = compileWhenOperand(seg, ctx, what);
1866
- usesState = usesState || only.state;
1867
- usesItem = usesItem || only.item;
1868
- expr = only.code;
1869
- }
1870
- pieces.push(negate ? `(!(${expr}))` : `(${expr})`);
1871
- }
1872
- const body = pieces.join(" ");
1873
- if (!usesState && !usesItem) return { static: true, value: evalPredicate(body, undefined, ctx) };
1874
- return { static: false, body, item: usesItem };
1875
- }
1876
-
1877
- /**
1878
- * @param {unknown[]} rows
1879
- * @param {string} itemName
1880
- * @param {string[]} bodyLines
1881
- * @param {Ctx} ctx
1882
- * @param {string[] | null} [empty] Empty-branch body, rendered when 0 rows.
1883
- * @returns {string}
1884
- */
1885
- function staticUnroll(rows, itemName, bodyLines, ctx, empty = null) {
1886
- if (rows.length === 0 && empty) return compileBody(empty, { ...ctx, loopMeta: true });
1887
- const out = [];
1888
- const count = rows.length;
1889
- for (let i = 0; i < count; i++) {
1890
- const meta = { $index: i, $number: i + 1, $first: i === 0, $last: i === count - 1, $count: count };
1891
- const rowCtx = { ...ctx, loopMeta: true, scope: createScope(ctx.scope, { [itemName]: rows[i], ...meta }) };
1892
- out.push(compileBody(bodyLines, rowCtx));
1893
- }
1894
- return out.join("\n");
1895
- }
1896
-
1897
- /**
1898
- * Emit a reactive loop region (template + initial rows + clause config) for the
1899
- * runtime. `key` may be a dotted path (e.g. `team.members`); the runtime reads
1900
- * it via getPath. `opts` carries where/sort/reverse/offset/limit/empty.
1901
- * @param {string | null} key State key/path of the list, or null for baked data.
1902
- * @param {string} itemName
1903
- * @param {string[]} bodyLines
1904
- * @param {Ctx} ctx
1905
- * @param {Partial<LoopOpts> & { data?: unknown[] } | null} [opts]
1906
- * @returns {string}
1907
- */
1908
- function reactiveLoop(key, itemName, bodyLines, ctx, opts = null) {
1909
- ctx.comp.assets.runtime = true;
1910
- /** @type {Ctx} */
1911
- const templateCtx = { ...ctx, loopItem: itemName, loopKey: key ?? undefined, loopMeta: true, scope: createScope(ctx.scope) };
1912
- const templateHtml = compileBody(bodyLines, templateCtx).trim();
1913
-
1914
- let wrapperTag = "div";
1915
- let itemTemplate = templateHtml;
1916
- const listMatch = templateHtml.match(/^<(ul|ol)>\s*([\s\S]*?)\s*<\/\1>$/);
1917
- if (listMatch && (listMatch[2].match(/<li>/g) || []).length === 1) {
1918
- wrapperTag = listMatch[1];
1919
- itemTemplate = listMatch[2].trim();
1920
- } else {
1921
- itemTemplate = `<div data-wd-loop-piece>${templateHtml}</div>`;
1922
- }
1923
-
1924
- const where = opts?.where || null;
1925
- const sort = opts?.sort || null;
1926
- const reverse = opts?.reverse || false;
1927
- const offset = opts?.offset || null;
1928
- const limit = opts?.limit || null;
1929
- const emptyLines = opts?.empty || null;
1930
- const baked = opts?.data || null; // rows for a static source filtered by state
1931
- // Resolve the (possibly dotted) source for the initial paint.
1932
- const segs = key ? key.split(".") : [];
1933
- const stateRows = key ? getPath(ctx.comp.state.get(segs[0]), segs.slice(1)) : null;
1934
- /** @type {unknown[]} */
1935
- const allRows = key ? (Array.isArray(stateRows) ? stateRows : []) : (baked || []);
1936
- // Initial paint runs the same pipeline the runtime will, reading state-key
1937
- // offset/limit from their current declared values.
1938
- /** @param {NumArg|null} a */
1939
- const num = (a) => a ? (a.kind === "literal" ? a.value : Number(ctx.comp.state.get(a.value) ?? 0)) : null;
1940
- const rows = pipelineRows(allRows, where, { where, sort, reverse, offset: offset && offset.kind === "key" ? { kind: "literal", value: num(offset) || 0 } : offset, limit: limit && limit.kind === "key" ? { kind: "literal", value: num(limit) ?? allRows.length } : limit, empty: null, clauseRefsState: false }, ctx);
1941
- /** @type {Map<string, number>} */
1942
- const counts = new Map();
1943
- const count = rows.length;
1944
- const initial = rows
1945
- .map((/** @type {unknown} */ item, i) => {
1946
- const itemKey = loopKeyOf(item, counts);
1947
- const meta = { index: i, number: i + 1, first: i === 0, last: i === count - 1, count };
1948
- return fillTemplateString(withLoopKey(itemTemplate, itemKey), item, meta);
1949
- })
1950
- .join("");
1951
-
1952
- const emptyTemplate = emptyLines ? `<template data-wd-loop-empty>${compileBody(emptyLines, { ...ctx, loopMeta: true }).trim()}</template>` : "";
1953
- const initialOut = count === 0 && emptyLines ? compileBody(emptyLines, { ...ctx, loopMeta: true }).trim() : initial;
1954
-
1955
- const attrs =
1956
- (where ? ` data-wd-loop-where="${escapeHtml(where.body)}"` : "") +
1957
- (sort ? ` data-wd-loop-sort="${escapeHtml(sort.key)}" data-wd-loop-sort-dir="${sort.dir}"` : "") +
1958
- (reverse ? ` data-wd-loop-reverse` : "") +
1959
- (offset ? ` data-wd-loop-offset="${numArgAttr(offset)}"` : "") +
1960
- (limit ? ` data-wd-loop-limit="${numArgAttr(limit)}"` : "") +
1961
- (baked ? ` data-wd-loop-data="${escapeHtml(JSON.stringify(baked))}"` : "");
1962
- return `<div data-wd-loop="${escapeHtml(key || "")}"${attrs}><template data-wd-loop-template>${itemTemplate}</template>${emptyTemplate}<${wrapperTag} data-wd-loop-out>${initialOut}</${wrapperTag}></div>`;
1963
- }
1964
-
1965
- /**
1966
- * @param {string} template
1967
- * @param {string} itemKey
1968
- * @returns {string}
1969
- */
1970
- function withLoopKey(template, itemKey) {
1971
- return template.replace(/^<([a-zA-Z][a-zA-Z0-9-]*)/, `<$1 data-wd-loop-key="${escapeHtml(itemKey)}"`);
1972
- }
1973
-
1974
- /**
1975
- * @param {string} template
1976
- * @param {unknown} item
1977
- * @param {Record<string, unknown>} [meta] Per-row meta values for the initial paint.
1978
- * @returns {string}
1979
- */
1980
- function fillTemplateString(template, item, meta = {}) {
1981
- // Resolve per-item :if regions first (recursively, so nested conditionals are
1982
- // pre-rendered for the initial paint), then fill text binds and meta markers.
1983
- return fillEachMeta(fillEachText(fillEachIfRegions(template, item, meta), item), meta);
1984
- }
1985
-
1986
- /**
1987
- * Fill `<span data-wd-each-meta="…">` markers with their per-row value.
1988
- * @param {string} str
1989
- * @param {Record<string, unknown>} meta
1990
- * @returns {string}
1991
- */
1992
- function fillEachMeta(str, meta) {
1993
- return str.replace(/<span data-wd-each-meta="([a-z]+)"><\/span>/g, (_, name) => {
1994
- const value = name in meta ? meta[name] : "";
1995
- return `<span data-wd-each-meta="${name}">${escapeHtml(value ?? "")}</span>`;
1996
- });
1997
- }
1998
-
1999
- // Walk the string resolving only the OUTERMOST data-wd-each-if regions; each
2000
- // chosen branch is recursed so nested conditionals resolve too. The <template>
2001
- // markup is left pristine so the runtime can keep toggling branches.
2002
- /**
2003
- * @param {string} str
2004
- * @param {unknown} item
2005
- * @param {Record<string, unknown>} [meta]
2006
- * @returns {string}
2007
- */
2008
- function fillEachIfRegions(str, item, meta = {}) {
2009
- const marker = '<span data-wd-each-if ';
2010
- let result = "";
2011
- let i = 0;
2012
- for (;;) {
2013
- const start = str.indexOf(marker, i);
2014
- if (start === -1) return result + str.slice(i);
2015
- result += str.slice(i, start);
2016
- const end = matchElement(str, start, "span");
2017
- result += fillOneEachIf(str.slice(start, end), item, meta);
2018
- i = end;
2019
- }
2020
- }
2021
-
2022
- /**
2023
- * @param {string} region
2024
- * @param {unknown} item
2025
- * @param {Record<string, unknown>} meta
2026
- * @returns {string}
2027
- */
2028
- function fillOneEachIf(region, item, meta) {
2029
- const metaMatch = region.match(/^<span data-wd-each-if data-wd-meta="([a-z]+)">/);
2030
- const path = (region.match(/^<span data-wd-each-if data-wd-path="([^"]*)">/) || ["", ""])[1];
2031
- const trueStart = region.indexOf("<template data-wd-if-true>");
2032
- const trueEnd = matchElement(region, trueStart, "template");
2033
- const falseStart = region.indexOf("<template data-wd-if-false>", trueEnd);
2034
- const falseEnd = matchElement(region, falseStart, "template");
2035
- const open = "<template data-wd-if-true>".length;
2036
- const close = "</template>".length;
2037
- const truthy = region.slice(trueStart + open, trueEnd - close);
2038
- const falsy = region.slice(falseStart + "<template data-wd-if-false>".length, falseEnd - close);
2039
- const test = metaMatch ? Boolean(meta[metaMatch[1]]) : Boolean(getPath(item, path ? path.split(".") : []));
2040
- const branch = test ? truthy : falsy;
2041
- const head = region.slice(0, falseEnd);
2042
- return `${head}<span data-wd-each-if-out>${fillEachIfRegions(branch, item, meta)}</span></span>`;
2043
- }
2044
-
2045
- /**
2046
- * @param {string} str
2047
- * @param {unknown} item
2048
- * @returns {string}
2049
- */
2050
- function fillEachText(str, item) {
2051
- return str.replace(/<span data-wd-each(?: data-wd-path="([^"]*)")?><\/span>/g, (_, p) => {
2052
- const value = p ? getPath(item, p.split(".")) : item;
2053
- const pathAttr = p ? ` data-wd-path="${p}"` : "";
2054
- return `<span data-wd-each${pathAttr}>${escapeHtml(value ?? "")}</span>`;
2055
- });
2056
- }
2057
-
2058
- // Return the index just past the balanced close of the element of `tag` that
2059
- // begins at `start`. Counts nested same-tag opens/closes so regions that embed
2060
- // their own spans/templates (nested :if) match correctly.
2061
- /**
2062
- * @param {string} str
2063
- * @param {number} start
2064
- * @param {string} tag
2065
- * @returns {number}
2066
- */
2067
- function matchElement(str, start, tag) {
2068
- const openPrefix = `<${tag}`;
2069
- const closeTag = `</${tag}>`;
2070
- let depth = 0;
2071
- let i = start;
2072
- while (i < str.length) {
2073
- if (str.startsWith(openPrefix, i) && (str[i + openPrefix.length] === " " || str[i + openPrefix.length] === ">")) {
2074
- depth++;
2075
- const gt = str.indexOf(">", i);
2076
- i = gt === -1 ? str.length : gt + 1;
2077
- } else if (str.startsWith(closeTag, i)) {
2078
- depth--;
2079
- i += closeTag.length;
2080
- if (depth === 0) return i;
2081
- } else {
2082
- i++;
2083
- }
2084
- }
2085
- return str.length;
2086
- }
2087
-
2088
- /**
2089
- * Stable per-render key for a loop row, disambiguating duplicates with `#n`.
2090
- * @param {unknown} item
2091
- * @param {Map<string, number>} counts Mutable seen-count accumulator.
2092
- * @returns {string}
2093
- */
2094
- export function loopKeyOf(item, counts) {
2095
- const base =
2096
- item && typeof item === "object"
2097
- ? String(/** @type {Record<string, unknown>} */ (item).id ?? /** @type {Record<string, unknown>} */ (item).key ?? JSON.stringify(item))
2098
- : String(item);
2099
- const seen = counts.get(base) || 0;
2100
- counts.set(base, seen + 1);
2101
- return seen ? `${base}#${seen}` : base;
2102
- }
2103
-
2104
- /**
2105
- * Render the documentation-demo directives (`:try`, `:note`, `:sprint`).
2106
- * @param {string} line
2107
- * @param {Ctx} ctx
2108
- * @returns {string}
2109
- */
2110
- function renderDemoDirective(line, ctx) {
2111
- const tryMatch = line.match(/^:try\s+"([^"]+)"\s+href="([^"]+)"$/);
2112
- if (tryMatch) {
2113
- const href = validateDemoHref(tryMatch[2], ctx);
2114
- return `<a class="try-card" href="${escapeHtml(href)}"><span>Try</span>${escapeHtml(tryMatch[1])}</a>`;
2115
- }
2116
- const note = line.match(/^:note\s+"([^"]+)"$/);
2117
- if (note) return `<aside class="note">${escapeHtml(note[1])}</aside>`;
2118
- const sprint = line.match(/^:sprint\s+min=(\d+)\s+max=(\d+)\s+roles="([^"]+)"$/);
2119
- if (sprint) {
2120
- const roles = sprint[3].split(",").map((role) => role.trim()).filter(Boolean);
2121
- return `<section class="sprint-board" data-min="${sprint[1]}" data-max="${sprint[2]}">${roles.map((role) => `<article><strong>${escapeHtml(role)}</strong><span>active lane</span></article>`).join("")}</section>`;
2122
- }
2123
- return "";
2124
- }
2125
-
2126
- /**
2127
- * Validate demo-card links without adding arbitrary URL passthrough.
2128
- * @param {string} href
2129
- * @param {Ctx} ctx
2130
- * @returns {string}
2131
- */
2132
- function validateDemoHref(href, ctx) {
2133
- const value = href.trim();
2134
- if (value !== href || /[\u0000-\u001F\u007F]/.test(value)) {
2135
- throw new Error(`Unsafe :try href "${escapeHtml(href)}" in ${ctx.file}. Use a relative URL starting with /, ./, ../, or #, or an http:, https:, or mailto: URL.`);
2136
- }
2137
- if (value.startsWith("//")) {
2138
- throw new Error(`Unsafe :try href "${escapeHtml(href)}" in ${ctx.file}. Protocol-relative URLs are not allowed; use http: or https: explicitly.`);
2139
- }
2140
- if (value.startsWith("/") || value.startsWith("./") || value.startsWith("../") || value.startsWith("#")) {
2141
- return value;
2142
- }
2143
- const scheme = value.match(/^([A-Za-z][A-Za-z0-9+.-]*):/);
2144
- if (scheme && ["http", "https", "mailto"].includes(scheme[1].toLowerCase())) {
2145
- return value;
2146
- }
2147
- throw new Error(`Unsafe :try href "${escapeHtml(href)}" in ${ctx.file}. Use a relative URL starting with /, ./, ../, or #, or an http:, https:, or mailto: URL.`);
2148
- }
2149
-
2150
- // ---------------------------------------------------------------------------
2151
- // Interpolation: one syntax, { name } / { name.path }
2152
- // ---------------------------------------------------------------------------
2153
-
2154
- /**
2155
- * @param {string} text
2156
- * @param {Ctx} ctx
2157
- * @returns {string}
2158
- */
2159
- function renderProse(text, ctx) {
2160
- text = resolveDestinationBindings(text, ctx);
2161
- return (ctx.md ?? md).render(text, { resolveBinding: (/** @type {string} */ expr) => resolveBindingHtml(expr, ctx) });
2162
- }
2163
-
2164
- /**
2165
- * Pre-resolve `{ expr }` interpolations sitting in a markdown link/image
2166
- * destination — the `](…)` slot — so a build-time `@loop` (or any static scope)
2167
- * can drive an href/src. A markdown destination cannot contain the spaces inside
2168
- * `{ … }`, so markdown-it would otherwise never form the link; substituting the
2169
- * static value here lets the normal link/image parser run. Only build-time
2170
- * (static-scope) values are substituted — reactive `:state`/reactive-loop
2171
- * bindings resolve to `null` and are left untouched (they cannot live in a
2172
- * destination). Issue #19.
2173
- * @param {string} text
2174
- * @param {Ctx} ctx
2175
- * @returns {string}
2176
- */
2177
- function resolveDestinationBindings(text, ctx) {
2178
- return text.replace(
2179
- /(\]\(\s*)\{\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\}/g,
2180
- (whole, prefix, expr) => {
2181
- const raw = resolveBindingRaw(expr, ctx);
2182
- return raw == null ? whole : prefix + raw;
2183
- }
2184
- );
2185
- }
2186
-
2187
- /**
2188
- * Resolve `{ expr }` to its raw static value (a plain string) for use in a
2189
- * destination, or `null` when the binding is reactive or not in build-time
2190
- * scope. Mirrors the static branch of {@link resolveBindingHtml} but returns the
2191
- * unescaped value (markdown-it normalizes the URL).
2192
- * @param {string} expr
2193
- * @param {Ctx} ctx
2194
- * @returns {string | null}
2195
- */
2196
- function resolveBindingRaw(expr, ctx) {
2197
- const segs = expr.split(".");
2198
- const found = lookupVar(ctx.scope, segs[0]);
2199
- if (!found.found) return null;
2200
- const resolved = getPath(found.value, segs.slice(1));
2201
- const leaf = interpolateLeaf(resolved, expr, ctx);
2202
- return leaf == null ? null : String(leaf);
2203
- }
2204
-
2205
- /**
2206
- * markdown-it plugin: turns `{ name.path }` into an inline `html_inline` token
2207
- * whose content comes from the env's `resolveBinding` callback.
2208
- * @param {MarkdownIt} mdInstance
2209
- * @returns {void}
2210
- */
2211
- function bindingPlugin(mdInstance) {
2212
- mdInstance.inline.ruler.push("wd_binding", (state, silent) => {
2213
- if (state.src.charCodeAt(state.pos) !== 0x7b /* { */) return false;
2214
- const match = /^\{\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\}/.exec(state.src.slice(state.pos));
2215
- if (!match) return false;
2216
- const resolve = state.env?.resolveBinding;
2217
- const html = resolve ? resolve(match[1]) : null;
2218
- if (typeof html !== "string") return false;
2219
- if (!silent) {
2220
- const token = state.push("html_inline", "", 0);
2221
- token.content = html;
2222
- }
2223
- state.pos += match[0].length;
2224
- return true;
2225
- });
2226
- }
2227
-
2228
- /**
2229
- * markdown-it plugin (core rule): a `{.class .class #id}` block immediately
2230
- * following an inline element (link, image, em/strong, code) attaches those
2231
- * classes / id to that element. Lets a link be styled as a button without a
2232
- * wrapper container. The block must directly follow the element (no space), and
2233
- * `{ … }` interpolation is unaffected (its content starts with a name, not `.`/`#`).
2234
- * Issue #18.
2235
- * @param {MarkdownIt} mdInstance
2236
- * @returns {void}
2237
- */
2238
- function attrsPlugin(mdInstance) {
2239
- mdInstance.core.ruler.push("wd_attrs", (state) => {
2240
- for (const block of state.tokens) {
2241
- if (block.type !== "inline" || !block.children) continue;
2242
- const children = block.children;
2243
- for (let i = 0; i < children.length; i++) {
2244
- const tok = children[i];
2245
- if (tok.type !== "text") continue;
2246
- const m = /^\{([.#][^}]*)\}/.exec(tok.content);
2247
- if (!m) continue;
2248
- const target = attrTarget(children, i);
2249
- if (!target) continue;
2250
- for (const part of m[1].split(/\s+/).filter(Boolean)) {
2251
- if (part[0] === ".") target.attrJoin("class", part.slice(1));
2252
- else if (part[0] === "#") target.attrSet("id", part.slice(1));
2253
- }
2254
- tok.content = tok.content.slice(m[0].length);
2255
- }
2256
- }
2257
- return false;
2258
- });
2259
- }
2260
-
2261
- /**
2262
- * The inline token an attr block attaches to: the immediately-preceding image
2263
- * (self-closing) or the open token matching the immediately-preceding close
2264
- * (link/em/strong/…). Returns null when nothing valid precedes.
2265
- * @param {any[]} children markdown-it inline child tokens
2266
- * @param {number} i Index of the attr-block text token.
2267
- * @returns {any} the matching markdown-it Token, or null
2268
- */
2269
- function attrTarget(children, i) {
2270
- const prev = children[i - 1];
2271
- if (!prev) return null;
2272
- if (prev.type === "image") return prev;
2273
- if (prev.nesting === -1) {
2274
- const openType = prev.type.replace(/_close$/, "_open");
2275
- let depth = 0;
2276
- for (let j = i - 1; j >= 0; j--) {
2277
- const t = children[j];
2278
- if (t.type === prev.type) depth++;
2279
- else if (t.type === openType) { depth--; if (depth === 0) return t; }
2280
- }
2281
- }
2282
- return null;
2283
- }
2284
-
2285
- /**
2286
- * Resolve a `{ name.path }` binding to HTML: loop item span, static value, or
2287
- * a reactive bind span. Returns null when nothing in scope matches.
2288
- * @param {string} expr
2289
- * @param {Ctx} ctx
2290
- * @returns {string | null}
2291
- */
2292
- function resolveBindingHtml(expr, ctx) {
2293
- const segs = expr.split(".");
2294
- const head = segs[0];
2295
-
2296
- // Per-row meta vars ($index/$number/$first/$last/$count) — only inside a loop.
2297
- if (LOOP_META[head]) {
2298
- if (!ctx.loopMeta) throw new Error(`"{ ${expr} }" uses the loop meta variable "${head}" outside a @loop in ${ctx.file}. Move it into a loop body, or rename your value.`);
2299
- if (ctx.loopItem) return `<span data-wd-each-meta="${LOOP_META[head]}"></span>`; // reactive: filled per row
2300
- // static: the value is in scope (injected by staticUnroll); fall through.
2301
- }
2302
-
2303
- if (ctx.loopItem && head === ctx.loopItem) {
2304
- const rest = segs.slice(1).join(".");
2305
- return `<span data-wd-each${rest ? ` data-wd-path="${escapeHtml(rest)}"` : ""}></span>`;
2306
- }
2307
-
2308
- const staticValue = lookupVar(ctx.scope, head);
2309
- if (staticValue.found) {
2310
- const resolved = getPath(staticValue.value, segs.slice(1));
2311
- return escapeHtml(interpolateLeaf(resolved, expr, ctx));
2312
- }
2313
-
2314
- const key = resolveStateKey(head, ctx);
2315
- if (key) {
2316
- ctx.comp.assets.runtime = true;
2317
- const initial = getPath(ctx.comp.state.get(key), segs.slice(1));
2318
- const rest = segs.slice(1).join(".");
2319
- const pathAttr = rest ? ` data-wd-path="${escapeHtml(rest)}"` : "";
2320
- return `<span data-wd-bind="${key}"${pathAttr}>${escapeHtml(interpolateLeaf(initial, expr, ctx))}</span>`;
2321
- }
2322
-
2323
- return null;
2324
- }
2325
-
2326
- /**
2327
- * Render an interpolated value as text. Arrays join with ", " (matching the
2328
- * documented `{ meta.tags }` behavior); a bare object is a mistake — fail
2329
- * loudly with a fix rather than emitting "[object Object]".
2330
- * @param {unknown} value
2331
- * @param {string} expr
2332
- * @param {Ctx} ctx
2333
- * @returns {string}
2334
- */
2335
- function interpolateLeaf(value, expr, ctx) {
2336
- if (value === null || value === undefined) return "";
2337
- if (Array.isArray(value)) return value.join(", ");
2338
- if (typeof value === "object") {
2339
- throw new Error(`Cannot interpolate the object value "{ ${expr} }" in ${ctx.file}. Interpolate a field instead — e.g. { ${expr}.title } — or iterate it with @loop ${expr} into item.`);
2340
- }
2341
- return String(value);
2342
- }
2343
-
2344
- /**
2345
- * Walk the scope chain for a top-level variable.
2346
- * @param {Scope} scope
2347
- * @param {string} name
2348
- * @returns {{ found: true, value: unknown } | { found: false }}
2349
- */
2350
- function lookupVar(scope, name) {
2351
- /** @type {Scope | null} */
2352
- let current = scope;
2353
- for (; current; current = current.parent) {
2354
- if (name in current.vars) return { found: true, value: current.vars[name] };
2355
- }
2356
- return { found: false };
2357
- }
2358
-
2359
- /**
2360
- * Resolve a dotted path against the static scope chain.
2361
- * @param {string} expr
2362
- * @param {Ctx} ctx
2363
- * @returns {{ found: true, value: unknown } | { found: false }}
2364
- */
2365
- function lookupPath(expr, ctx) {
2366
- const segs = expr.split(".");
2367
- const head = lookupVar(ctx.scope, segs[0]);
2368
- if (!head.found) return { found: false };
2369
- return { found: true, value: getPath(head.value, segs.slice(1)) };
2370
- }
2371
-
2372
- /**
2373
- * Safely read a dotted path off a value, rejecting prototype-pollution segments.
2374
- * @param {unknown} value
2375
- * @param {string[]} segments
2376
- * @returns {unknown}
2377
- */
2378
- function getPath(value, segments) {
2379
- /** @type {any} */
2380
- let current = value;
2381
- for (const segment of segments) {
2382
- if (current == null) return undefined;
2383
- if (["constructor", "prototype", "__proto__"].includes(segment)) return undefined;
2384
- current = current[segment];
2385
- }
2386
- return current;
2387
- }
2388
-
2389
- /**
2390
- * Validate a dotted path shape, rejecting prototype-pollution segments at every
2391
- * level. Shared by actions/loops/fetch. Throws with a corrective `Use:` hint.
2392
- * @param {string} path Dotted path, e.g. `cart.items`.
2393
- * @param {Ctx} ctx
2394
- * @param {string} use Corrective suggestion for the error message.
2395
- * @returns {string[]} The validated segments.
2396
- */
2397
- function validatePath(path, ctx, use) {
2398
- const segs = path.split(".");
2399
- if (segs.some((seg) => ["constructor", "prototype", "__proto__"].includes(seg))) {
2400
- throw new Error(`Path segment in "${path}" is not allowed in ${ctx.file}. Use: ${use}`);
2401
- }
2402
- return segs;
2403
- }
2404
-
2405
- /**
2406
- * Resolve a bare state name to its fully-qualified key, walking section scopes.
2407
- * @param {string} name
2408
- * @param {Ctx} ctx
2409
- * @returns {string | null}
2410
- */
2411
- function resolveStateKey(name, ctx) {
2412
- for (let i = ctx.sections.length - 1; i >= 0; i--) {
2413
- const key = `${ctx.sections[i]}:${name}`;
2414
- if (ctx.comp.state.has(key)) return key;
2415
- }
2416
- return ctx.comp.state.has(name) ? name : null;
2417
- }
2418
-
2419
- // ---------------------------------------------------------------------------
2420
- // Actions
2421
- // ---------------------------------------------------------------------------
2422
-
2423
- /**
2424
- * A parsed `:button` action.
2425
- * @typedef {object} Action
2426
- * @property {string} op Runtime operation (inc/dec/add/sub/append/prepend/set/toggle/member-toggle/remove/remove-value/clear/merge/delete/reset/append-row).
2427
- * @property {string} target State key (possibly dotted) the action mutates.
2428
- * @property {unknown} [value] Literal value for value-carrying ops.
2429
- */
2430
-
2431
- const ACTION_USE =
2432
- 'Use: name++, name--, n += k, n -= k, name = v, flag toggle, list append/prepend v, list toggle v, list remove v, x clear, obj merge other, obj delete key, name reset — chain with ";".';
2433
-
2434
- /**
2435
- * Parse a `:button` action expression into a validated `{ op, target, value }`,
2436
- * or — when `;`-separated — an ordered array of them applied in sequence.
2437
- * @param {string} raw
2438
- * @param {Ctx} ctx
2439
- * @returns {Action | Action[]}
2440
- */
2441
- function parseAction(raw, ctx) {
2442
- const parts = raw.split(";").map((p) => p.trim()).filter(Boolean);
2443
- if (parts.length > 1) return parts.map((part) => parseSingleAction(part, raw, ctx));
2444
- return parseSingleAction(raw.trim(), raw, ctx);
2445
- }
2446
-
2447
- /**
2448
- * Parse one (non-`;`) action expression into a validated `{ op, target, value }`.
2449
- * Targets may be dotted paths (`cart.count`); a bare name is a 1-segment path.
2450
- * @param {string} expression
2451
- * @param {string} raw The full original action source (for error context).
2452
- * @param {Ctx} ctx
2453
- * @returns {Action}
2454
- */
2455
- function parseSingleAction(expression, raw, ctx) {
2456
- const PATH = "[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*";
2457
- /** @param {string} name @returns {string} */
2458
- const resolveTarget = (name) => {
2459
- const segs = validatePath(name, ctx, ACTION_USE);
2460
- const key = resolveStateKey(segs[0], ctx);
2461
- if (!key) {
2462
- throw new Error(`Button action targets unknown state "${segs[0]}" in ${ctx.file}. Declare it first with :state ${segs[0]} = ...`);
2463
- }
2464
- return [key, ...segs.slice(1)].join(".");
2465
- };
2466
-
2467
- const increment = expression.match(new RegExp(`^(${PATH})\\+\\+$`));
2468
- if (increment) return { op: "inc", target: resolveTarget(increment[1]) };
2469
- const decrement = expression.match(new RegExp(`^(${PATH})--$`));
2470
- if (decrement) return { op: "dec", target: resolveTarget(decrement[1]) };
2471
- const sub = expression.match(new RegExp(`^(${PATH})\\s*-=\\s*(.+)$`));
2472
- if (sub) return { op: "sub", target: resolveTarget(sub[1]), value: parseActionLiteral(sub[2]) };
2473
- // Per-row: carry the current loop item into another list — `cart += product`.
2474
- // Only inside a reactive @loop; the runtime resolves the row from the DOM.
2475
- const add = expression.match(new RegExp(`^(${PATH})\\s*\\+=\\s*(.+)$`));
2476
- if (add) {
2477
- const rhs = add[2].trim();
2478
- if (ctx.loopItem && rhs === ctx.loopItem) {
2479
- const target = resolveTarget(add[1]);
2480
- if (!Array.isArray(ctx.comp.state.get(target))) {
2481
- throw new Error(`Button action "${raw}" needs ${add[1]} to be a :state list (declare it "${add[1]} = []") in ${ctx.file}.`);
2482
- }
2483
- return { op: "append-row", target };
2484
- }
2485
- const target = resolveTarget(add[1]);
2486
- const value = parseActionLiteral(rhs);
2487
- if (Array.isArray(ctx.comp.state.get(target))) return { op: "append", target, value };
2488
- if (typeof value === "number") return { op: "add", target, value };
2489
- throw new Error(`Unsupported button action "${raw}" in ${ctx.file}. += with non-number values requires a list state target — declare it "${add[1]} = []".`);
2490
- }
2491
- // `flag toggle` (no operand) → boolean flip; `list toggle v` → member-toggle.
2492
- const toggle = expression.match(new RegExp(`^(${PATH})\\s+toggle(?:\\s+(.+))?$`));
2493
- if (toggle) {
2494
- const target = resolveTarget(toggle[1]);
2495
- if (toggle[2] === undefined) return { op: "toggle", target };
2496
- return { op: "member-toggle", target, value: parseActionLiteral(toggle[2]) };
2497
- }
2498
- const prepend = expression.match(new RegExp(`^(${PATH})\\s+(?:append|prepend)\\s+(.+)$`));
2499
- if (prepend) {
2500
- const op = expression.includes(" prepend ") ? "prepend" : "append";
2501
- return { op, target: resolveTarget(prepend[1]), value: parseActionLiteral(prepend[2]) };
2502
- }
2503
- // Per-row: remove the current row from the list being looped — `todos remove todo`.
2504
- // Disambiguation: operand IS the loop item name → `remove` (current row);
2505
- // otherwise the operand is a value → `remove-value`.
2506
- const remove = expression.match(new RegExp(`^(${PATH})\\s+remove\\s+(.+)$`));
2507
- if (remove) {
2508
- const operand = remove[2].trim();
2509
- if (ctx.loopItem && operand === ctx.loopItem) {
2510
- if (!ctx.loopKey || resolveStateKey(remove[1], ctx) !== ctx.loopKey) {
2511
- throw new Error(`Button action "${raw}" must target the :state list being looped (@loop ${remove[1]} into ${ctx.loopItem}) in ${ctx.file}.`);
2512
- }
2513
- return { op: "remove", target: ctx.loopKey };
2514
- }
2515
- return { op: "remove-value", target: resolveTarget(remove[1]), value: parseActionLiteral(operand) };
2516
- }
2517
- const clear = expression.match(new RegExp(`^(${PATH})\\s+clear$`));
2518
- if (clear) return { op: "clear", target: resolveTarget(clear[1]) };
2519
- const merge = expression.match(new RegExp(`^(${PATH})\\s+merge\\s+(.+)$`));
2520
- if (merge) return { op: "merge", target: resolveTarget(merge[1]), value: parseMergeOperand(merge[2], ctx) };
2521
- const del = expression.match(new RegExp(`^(${PATH})\\s+delete\\s+(.+)$`));
2522
- if (del) return { op: "delete", target: resolveTarget(del[1]), value: parseActionLiteral(del[2]) };
2523
- const reset = expression.match(new RegExp(`^(${PATH})\\s+reset$`));
2524
- if (reset) return { op: "reset", target: resolveTarget(reset[1]) };
2525
- // `name refetch` re-invokes the matching :fetch node. The target is the fetch
2526
- // key (bare name); the runtime finds the [data-wd-fetch-key] node and re-runs.
2527
- const refetch = expression.match(new RegExp(`^(${PATH})\\s+refetch$`));
2528
- if (refetch) return { op: "refetch", target: resolveTarget(refetch[1]) };
2529
- const assign = expression.match(new RegExp(`^(${PATH})\\s*=\\s*(.+)$`));
2530
- if (assign) return { op: "set", target: resolveTarget(assign[1]), value: parseActionLiteral(assign[2]) };
2531
- throw new Error(`Unsupported button action "${raw}" in ${ctx.file}. ${ACTION_USE}`);
2532
- }
2533
-
2534
- /**
2535
- * `merge` operand: either an inline JSON object literal, or a state/store key
2536
- * name (emitted as a string the runtime resolves via getPath).
2537
- * @param {string} raw
2538
- * @param {Ctx} ctx
2539
- * @returns {unknown}
2540
- */
2541
- function parseMergeOperand(raw, ctx) {
2542
- const value = raw.trim();
2543
- if (/^[A-Za-z_$][\w$]*$/.test(value)) {
2544
- const key = resolveStateKey(value, ctx);
2545
- if (!key) throw new Error(`Button action merge targets unknown state "${value}" in ${ctx.file}. Declare it first with :state ${value} = ...`);
2546
- return key;
2547
- }
2548
- const parsed = parseActionLiteral(value);
2549
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
2550
- throw new Error(`Unsupported merge operand "${raw}" in ${ctx.file}. Use: obj merge other (a state key or an inline {…} object).`);
2551
- }
2552
-
2553
- /**
2554
- * @param {string} raw
2555
- * @returns {unknown}
2556
- */
2557
- function parseActionLiteral(raw) {
2558
- const value = raw.trim();
2559
- if (/^["'].*["']$/.test(value)) return stripQuotes(value);
2560
- if (value === "true") return true;
2561
- if (value === "false") return false;
2562
- if (value === "null") return null;
2563
- if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
2564
- if (/^[\[{]/.test(value)) {
2565
- try {
2566
- return JSON.parse(value);
2567
- } catch {
2568
- throw new Error(`Unsupported action literal "${raw}". Use: a quoted string, number, boolean, null, or valid JSON.`);
2569
- }
2570
- }
2571
- throw new Error(`Unsupported action literal "${raw}". Use: a quoted string, number, boolean, null, or valid JSON.`);
2572
- }
2573
-
2574
- // ---------------------------------------------------------------------------
2575
- // Includes / assets
2576
- // ---------------------------------------------------------------------------
2577
-
2578
- /**
2579
- * Register a page's colocated `.skin`/`.js` siblings as emitted assets.
2580
- * @param {string} file
2581
- * @param {Paths} context
2582
- * @param {Assets} assets
2583
- * @returns {void}
2584
- */
2585
- function collectColocatedAssets(file, context, assets) {
2586
- const ext = path.extname(file);
2587
- const stem = file.slice(0, -ext.length);
2588
- for (const [assetExt, folder] of [[".skin", "styles"], [".js", "scripts"]]) {
2589
- const candidate = `${stem}${assetExt}`;
2590
- if (!fs.existsSync(candidate)) continue;
2591
- const rel = path.relative(context.cwd, candidate).replaceAll(path.sep, "/");
2592
- const outputExt = assetExt === ".skin" ? ".css" : ".js";
2593
- const publicPath = `/__wd/${folder}/${rel.slice(0, -assetExt.length).replace(/[/.]/g, "_")}${outputExt}`;
2594
- assets.files.set(candidate, publicPath);
2595
- if (assetExt === ".skin") assets.skins.add(publicPath);
2596
- if (assetExt === ".js") assets.scripts.add(publicPath);
2597
- }
2598
- }
2599
-
2600
- /**
2601
- * Resolve an include spec to an absolute path inside `site/pages` or `site/_`.
2602
- * @param {string} spec Include target (may be quoted).
2603
- * @param {string} fromFile File requesting the include.
2604
- * @param {Paths} context
2605
- * @param {boolean} [allowAny] Allow non-page extensions (e.g. JSON for `@loop`).
2606
- * @returns {string}
2607
- */
2608
- function resolveInclude(spec, fromFile, context, allowAny = false) {
2609
- const clean = stripQuotes(spec);
2610
- const candidates = [];
2611
- if (clean.startsWith("/")) {
2612
- candidates.push(path.join(context.shelfRoot, clean.slice(1)));
2613
- } else {
2614
- candidates.push(path.resolve(path.dirname(fromFile), clean));
2615
- candidates.push(path.join(context.shelfRoot, clean));
2616
- }
2617
- for (const candidate of candidates) {
2618
- const resolved = path.resolve(candidate);
2619
- if (!isAllowedInclude(resolved, context)) {
2620
- throw new Error(`Include "${spec}" from ${fromFile} resolves outside site/pages or site/_`);
2621
- }
2622
- if (!fs.existsSync(resolved)) continue;
2623
- if (!allowAny && !pageIncludeExtensions.includes(path.extname(resolved))) continue;
2624
- return resolved;
2625
- }
2626
- throw new Error(`Could not resolve include "${spec}" from ${fromFile}`);
2627
- }
2628
-
2629
- /**
2630
- * @param {string} file
2631
- * @param {Paths} context
2632
- * @returns {boolean}
2633
- */
2634
- function isAllowedInclude(file, context) {
2635
- const roots = [context.routesRoot, context.shelfRoot].map((root) => path.resolve(root));
2636
- return roots.some((root) => file === root || file.startsWith(`${root}${path.sep}`));
2637
- }
2638
-
2639
- // ---------------------------------------------------------------------------
2640
- // Plain .md hints
2641
- // ---------------------------------------------------------------------------
2642
-
2643
- /**
2644
- * Warn when a plain `.md` file contains `.wd`-only syntax that stays inert.
2645
- * @param {string} body
2646
- * @param {string} file
2647
- * @param {Compilation} comp
2648
- * @returns {void}
2649
- */
2650
- function scanMarkdownHints(body, file, comp) {
2651
- let fence = null;
2652
- for (const line of body.split("\n")) {
2653
- const fenceMatch = line.match(/^(```+|~~~+)/);
2654
- if (fence) {
2655
- if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) fence = null;
2656
- continue;
2657
- }
2658
- if (fenceMatch) {
2659
- fence = fenceMatch[1];
2660
- continue;
2661
- }
2662
- const hit = line.match(/^(@include|@loop|@repeat|:state|:button|:if|:for|:try|:note|:sprint|:::)(\s|$)/);
2663
- if (hit) {
2664
- comp.warnings.push(
2665
- `${file}: "${hit[1]}" is .wd syntax and stays plain text in .md — rename the file to .wd to activate it.`
2666
- );
2667
- return;
2668
- }
2669
- }
2670
- }
2671
-
2672
- // ---------------------------------------------------------------------------
2673
- // Literals
2674
- // ---------------------------------------------------------------------------
2675
-
2676
- /**
2677
- * JSON-encode a value for an inline `<script>`, escaping `<` to stay HTML-safe.
2678
- * @param {unknown} value
2679
- * @returns {string}
2680
- */
2681
- function safeScriptJson(value) {
2682
- return JSON.stringify(value).replaceAll("<", "\\u003c");
2683
- }
2684
-
2685
- /**
2686
- * @param {string} raw
2687
- * @returns {unknown}
2688
- */
2689
- function parseStateValue(raw) {
2690
- const value = raw.trim();
2691
- if (/^["'].*["']$/.test(value)) return stripQuotes(value);
2692
- if (value === "true") return true;
2693
- if (value === "false") return false;
2694
- if (value === "null") return null;
2695
- if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
2696
- try {
2697
- return JSON.parse(value);
2698
- } catch {
2699
- return value;
2700
- }
2701
- }
2702
-
2703
- /**
2704
- * @param {string} raw
2705
- * @returns {string | number | boolean}
2706
- */
2707
- function parseScalar(raw) {
2708
- const trimmed = raw.trim();
2709
- if (/^["']/.test(trimmed)) return stripQuotes(trimmed);
2710
- if (trimmed === "true") return true;
2711
- if (trimmed === "false") return false;
2712
- if (/^-?\d+(?:\.\d+)?$/.test(trimmed)) return Number(trimmed);
2713
- return trimmed;
2714
- }
2715
-
2716
- /**
2717
- * @param {string} [value]
2718
- * @returns {string}
2719
- */
2720
- function stripQuotes(value) {
2721
- return value?.replace(/^["']|["']$/g, "") ?? "";
2722
- }
2723
-
2724
- /**
2725
- * Turn a field name / state key into a human-readable accessible name, e.g.
2726
- * `quest` → "Quest", `user-name` → "User name", `firstName` → "First name".
2727
- * Hyphens, underscores, and camelCase boundaries become spaces; the first letter
2728
- * is capitalized. Used to auto-derive aria-label on generated form inputs.
2729
- * @param {string} name
2730
- * @returns {string}
2731
- */
2732
- function humanizeName(name) {
2733
- const words = name
2734
- .replace(/([a-z0-9])([A-Z])/g, "$1 $2") // split camelCase
2735
- .replace(/[-_]+/g, " ") // hyphens/underscores → spaces
2736
- .trim()
2737
- .toLowerCase();
2738
- return words ? words.charAt(0).toUpperCase() + words.slice(1) : name;
2739
- }
2740
-
2741
- /**
2742
- * Escape a value for safe inclusion in HTML text and attribute contexts.
2743
- * @param {unknown} value
2744
- * @returns {string}
2745
- */
2746
- export function escapeHtml(value) {
2747
- return String(value)
2748
- .replaceAll("&", "&amp;")
2749
- .replaceAll("<", "&lt;")
2750
- .replaceAll(">", "&gt;")
2751
- .replaceAll('"', "&quot;")
2752
- .replaceAll("'", "&#39;");
2753
- }
1
+ // Darkmown's compiler, split into cohesive modules under `src/compiler/`. This
2
+ // file is a thin barrel: it re-exports the public API from `src/compiler/index.js`
3
+ // so every existing `import … from "./compiler.js"` (builder, tests) keeps
4
+ // working unchanged. See `src/compiler/index.js` for the module map.
5
+
6
+ // Re-export the public typedefs so existing `import("./compiler.js").Type`
7
+ // references (e.g. `Assets` in src/builder.js) keep resolving after the split.
8
+ /**
9
+ * @typedef {import("./compiler/context.js").Meta} Meta
10
+ * @typedef {import("./compiler/context.js").FrontmatterValue} FrontmatterValue
11
+ * @typedef {import("./compiler/context.js").Assets} Assets
12
+ * @typedef {import("./compiler/context.js").Compilation} Compilation
13
+ * @typedef {import("./compiler/context.js").Scope} Scope
14
+ * @typedef {import("./compiler/context.js").Ctx} Ctx
15
+ * @typedef {import("./compiler/context.js").CompiledDocument} CompiledDocument
16
+ * @typedef {import("./compiler/context.js").CompiledPage} CompiledPage
17
+ */
18
+
19
+ export {
20
+ compileDocument,
21
+ compilePage,
22
+ enhanceImages,
23
+ escapeHtml,
24
+ loopKeyOf,
25
+ parseFrontmatter
26
+ } from "./compiler/index.js";