@zvndev/darkmown 0.19.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +115 -5
  4. package/docs/spec-alignment.md +16 -3
  5. package/package.json +22 -4
  6. package/site/_/base.skin +372 -0
  7. package/site/_/base.wd +4 -0
  8. package/site/_/footer.wd +14 -0
  9. package/site/_/metrics.json +13 -0
  10. package/site/_/nav.skin +35 -12
  11. package/site/_/nav.wd +8 -10
  12. package/site/_/products.json +10 -0
  13. package/site/pages/app.wd +1 -1
  14. package/site/pages/carousel/index.js +82 -0
  15. package/site/pages/carousel/index.skin +185 -0
  16. package/site/pages/carousel/index.wd +109 -0
  17. package/site/pages/carousel/slide-1.jpg +0 -0
  18. package/site/pages/carousel/slide-2.jpg +0 -0
  19. package/site/pages/carousel/slide-3.jpg +0 -0
  20. package/site/pages/carousel/slide-4.jpg +0 -0
  21. package/site/pages/carousel/slide-5.jpg +0 -0
  22. package/site/pages/compass/index.skin +247 -0
  23. package/site/pages/compass/index.wd +194 -0
  24. package/site/pages/docs/index.skin +48 -28
  25. package/site/pages/docs/index.wd +71 -5
  26. package/site/pages/folio/-style.skin +375 -0
  27. package/site/pages/folio/-style.wd +6 -0
  28. package/site/pages/folio/cart.skin +309 -0
  29. package/site/pages/folio/cart.wd +201 -0
  30. package/site/pages/folio/index.skin +24 -0
  31. package/site/pages/folio/index.wd +167 -0
  32. package/site/pages/forge/index.skin +676 -0
  33. package/site/pages/forge/index.wd +330 -0
  34. package/site/pages/index.skin +135 -144
  35. package/site/pages/index.wd +17 -5
  36. package/site/pages/ledger/index.skin +257 -0
  37. package/site/pages/ledger/index.wd +174 -0
  38. package/site/pages/media/clip-poster.jpg +0 -0
  39. package/site/pages/media/clip.mp4 +0 -0
  40. package/site/pages/media/index.skin +82 -0
  41. package/site/pages/media/index.wd +84 -0
  42. package/site/pages/media/tone.mp3 +0 -0
  43. package/site/pages/pulse/index.skin +434 -0
  44. package/site/pages/pulse/index.wd +178 -0
  45. package/site/pages/showcase/index.skin +130 -0
  46. package/site/pages/showcase/index.wd +168 -0
  47. package/src/builder.js +20 -14
  48. package/src/cli.js +216 -77
  49. package/src/compiler/body.js +457 -0
  50. package/src/compiler/context.js +160 -0
  51. package/src/compiler/directives.js +1345 -0
  52. package/src/compiler/format.js +244 -0
  53. package/src/compiler/frontmatter.js +117 -0
  54. package/src/compiler/includes.js +116 -0
  55. package/src/compiler/index.js +22 -0
  56. package/src/compiler/interpolation.js +223 -0
  57. package/src/compiler/loops.js +715 -0
  58. package/src/compiler/markdown.js +242 -0
  59. package/src/compiler/page.js +267 -0
  60. package/src/compiler/predicates.js +314 -0
  61. package/src/compiler.js +26 -2932
  62. package/src/dev.js +3 -1
  63. package/src/headers.js +8 -4
  64. package/src/index.js +22 -0
  65. package/src/router.js +3 -1
  66. package/src/runtime.js +168 -14
  67. package/src/scaffold.js +158 -131
  68. package/src/skin.js +11 -2
  69. package/site/_/og.png +0 -0
@@ -0,0 +1,1345 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Directive handlers: the `handle*` family dispatched per line by the body
3
+ // parser (state/store/fetch/computed/effect/form/input/bind/submit/textarea/
4
+ // select/checkbox/radio/button/if/include/container) plus the `:button` action
5
+ // parser and the documentation-demo directives (`:try`/`:note`/`:sprint`).
6
+ //
7
+ // Every handler receives the 0-based line `index` so its malformed/invalid
8
+ // errors report `file:line` (via `at`) — matching the unclosed-block errors —
9
+ // while keeping the message text and `Use:` hints intact.
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import { compileBody } from "./body.js";
13
+ import { at, createScope, LOOP_META } from "./context.js";
14
+ import { FORMATTERS } from "./format.js";
15
+ import { resolveInclude } from "./includes.js";
16
+ import {
17
+ escapeHtml,
18
+ getPath,
19
+ humanizeName,
20
+ lookupPath,
21
+ lookupVar,
22
+ parseScalar,
23
+ parseStateValue,
24
+ resolveStateKey,
25
+ safeScriptJson,
26
+ stripQuotes,
27
+ validatePath
28
+ } from "./interpolation.js";
29
+ import { compileFile } from "./page.js";
30
+ import { compileComputedExpr, compileWhen, evalPredicate } from "./predicates.js";
31
+
32
+ /**
33
+ * @typedef {import("./context.js").Ctx} Ctx
34
+ * @typedef {import("./context.js").Action} Action
35
+ */
36
+
37
+ /**
38
+ * @param {string} line
39
+ * @param {Ctx} ctx
40
+ * @param {number} index 0-based line index for `file:line` errors.
41
+ * @returns {string}
42
+ */
43
+ export function handleInclude(line, ctx, index) {
44
+ const match = line.match(/^@include\s+(\S+)(?:\s+with\s+(.+))?$/);
45
+ if (!match) throw new Error(`Malformed @include in ${at(ctx.file, index)}: ${line}`);
46
+ const target = resolveInclude(match[1], ctx.file, ctx.context);
47
+ const args = parseIncludeArgs(match[2] || "", ctx);
48
+ const scope = createScope(ctx.scope, args);
49
+ const child = compileFile(
50
+ target,
51
+ ctx.context,
52
+ ctx.stack,
53
+ scope,
54
+ ctx.comp,
55
+ ctx.sections,
56
+ ctx.loopItem
57
+ );
58
+ return child.html;
59
+ }
60
+
61
+ /**
62
+ * @param {string} raw
63
+ * @param {Ctx} ctx
64
+ * @returns {Record<string, unknown>}
65
+ */
66
+ function parseIncludeArgs(raw, ctx) {
67
+ /** @type {Record<string, unknown>} */
68
+ const args = {};
69
+ const re = /([A-Za-z0-9_-]+)=("[^"]*"|'[^']*'|\{[^}]*\}|\S+)/g;
70
+ for (const match of raw.matchAll(re)) {
71
+ const value = match[2];
72
+ if (value.startsWith("{")) {
73
+ const expr = value.slice(1, -1).trim();
74
+ const resolved = lookupPath(expr, ctx);
75
+ if (!resolved.found) {
76
+ throw new Error(
77
+ `@include argument ${match[1]}={ ${expr} } in ${ctx.file} does not match any value in scope`
78
+ );
79
+ }
80
+ args[match[1]] = resolved.value;
81
+ } else {
82
+ args[match[1]] = parseScalar(value);
83
+ }
84
+ }
85
+ return args;
86
+ }
87
+
88
+ /**
89
+ * @param {string} header
90
+ * @param {string[]} bodyLines
91
+ * @param {Ctx} ctx
92
+ * @param {number} index 0-based line index for `file:line` errors.
93
+ * @returns {string}
94
+ */
95
+ export function handleContainer(header, bodyLines, ctx, index) {
96
+ let rest = header.trim();
97
+ let tag = "section";
98
+ /** @type {string[]} Static classes baked into class="". */
99
+ const extraClass = [];
100
+ /** @type {[string, string][]} Reactive loop-item class bindings (data-wd-each-class). */
101
+ const eachClasses = [];
102
+ /** @type {[string, string][]} Global state-driven class bindings (data-wd-class). */
103
+ const stateClasses = [];
104
+ let id = "";
105
+ // Leading tag/name token (anything not starting with . or #). "section" keeps
106
+ // the <section> tag; any other name becomes a <div> and also a class.
107
+ const lead = rest.match(/^([^\s.#]\S*)/);
108
+ let nameToken = "section";
109
+ if (lead) {
110
+ nameToken = lead[1];
111
+ rest = rest.slice(lead[0].length).trim();
112
+ }
113
+ if (nameToken !== "section") {
114
+ tag = "div";
115
+ extraClass.push(nameToken);
116
+ }
117
+ while (rest.length) {
118
+ if (rest.startsWith("#")) {
119
+ const m = rest.match(/^#(\S+)/);
120
+ id = m ? m[1] : "";
121
+ rest = rest.slice((m ? m[0] : rest).length).trim();
122
+ continue;
123
+ }
124
+ const cm = rest.match(/^\.([A-Za-z_][\w-]*)/);
125
+ if (!cm)
126
+ throw new Error(
127
+ `Unexpected token "${rest.split(/\s+/)[0]}" in container "::: ${header}" in ${at(ctx.file, index)}`
128
+ );
129
+ const cls = cm[1];
130
+ rest = rest.slice(cm[0].length).trim();
131
+ // Optional `when <predicate>` makes the class reactive. The predicate runs to
132
+ // the next ` .`/` #` token or the end of the header.
133
+ const whenMatch = rest.match(/^when\s+(.+?)(?=\s+[.#]|$)/);
134
+ if (whenMatch) {
135
+ rest = rest.slice(whenMatch[0].length).trim();
136
+ const compiled = compileWhen(whenMatch[1].trim(), ctx);
137
+ if (compiled.static) {
138
+ if (compiled.value) extraClass.push(cls);
139
+ } else if (compiled.item) eachClasses.push([cls, compiled.body]);
140
+ else stateClasses.push([cls, compiled.body]);
141
+ } else {
142
+ extraClass.push(cls);
143
+ }
144
+ }
145
+ const explicitId = Boolean(id);
146
+ if (!id) id = `wd-s${++ctx.comp.sectionCounter}`;
147
+
148
+ ctx.sections.push(id);
149
+ let inner;
150
+ try {
151
+ inner = compileBody(bodyLines, ctx);
152
+ } finally {
153
+ ctx.sections.pop();
154
+ }
155
+ const idAttr = explicitId ? ` id="${escapeHtml(id)}"` : "";
156
+ const classAttr = extraClass.length ? ` class="${escapeHtml(extraClass.join(" "))}"` : "";
157
+ let classBind = "";
158
+ if (eachClasses.length) {
159
+ ctx.comp.assets.runtime = true;
160
+ classBind += ` data-wd-each-class="${escapeHtml(JSON.stringify(eachClasses))}"`;
161
+ }
162
+ if (stateClasses.length) {
163
+ ctx.comp.assets.runtime = true;
164
+ classBind += ` data-wd-class="${escapeHtml(JSON.stringify(stateClasses))}"`;
165
+ }
166
+ return `<${tag}${idAttr}${classAttr}${classBind}>\n${inner}\n</${tag}>`;
167
+ }
168
+
169
+ /**
170
+ * @param {string} line
171
+ * @param {Ctx} ctx
172
+ * @param {number} index 0-based line index for `file:line` errors.
173
+ * @returns {string}
174
+ */
175
+ export function handleState(line, ctx, index) {
176
+ const match = line.match(/^:state\s+([A-Za-z_$][\w$]*)\s*=\s*(.+?)(\s+persist)?$/);
177
+ if (!match) throw new Error(`Malformed :state in ${at(ctx.file, index)}: ${line}`);
178
+ const value = parseStateValue(match[2], at(ctx.file, index));
179
+ const key = declareState(match[1], value, ctx);
180
+ const persistAttr = match[3] ? ` data-wd-persist="${key}"` : "";
181
+ return `<script type="application/json" data-wd-state${persistAttr}>${safeScriptJson({ [key]: value })}</script>`;
182
+ }
183
+
184
+ /**
185
+ * Register a state key in the current section scope, enabling the runtime.
186
+ * @param {string} name
187
+ * @param {unknown} value
188
+ * @param {Ctx} ctx
189
+ * @returns {string} The fully-qualified state key.
190
+ */
191
+ function declareState(name, value, ctx) {
192
+ if (ctx.loopItem)
193
+ throw new Error(`State cannot be declared inside a reactive @loop body (${ctx.file})`);
194
+ if (ctx.comp.stores.has(name))
195
+ throw new Error(
196
+ `State "${name}" collides with a :store of the same name in ${ctx.file}. Use: :store name = value for the global, or rename one.`
197
+ );
198
+ const key = ctx.sections.length ? `${ctx.sections.at(-1)}:${name}` : name;
199
+ if (ctx.comp.state.has(key))
200
+ throw new Error(`State "${name}" is declared twice in the same scope (${ctx.file})`);
201
+ ctx.comp.state.set(key, value);
202
+ ctx.comp.assets.runtime = true;
203
+ return key;
204
+ }
205
+
206
+ /**
207
+ * @param {string} line
208
+ * @param {Ctx} ctx
209
+ * @param {number} index 0-based line index for `file:line` errors.
210
+ * @returns {string}
211
+ */
212
+ export function handleStore(line, ctx, index) {
213
+ const match = line.match(/^:store\s+([A-Za-z_$][\w$]*)\s*=\s*(.+?)(\s+ephemeral)?$/);
214
+ if (!match)
215
+ throw new Error(
216
+ `Malformed :store in ${at(ctx.file, index)}: ${line}. Use: :store name = value [ephemeral]`
217
+ );
218
+ const value = parseStateValue(match[2], at(ctx.file, index));
219
+ const name = declareStore(match[1], value, ctx);
220
+ const ephemeral = match[3] ? " data-wd-store-ephemeral" : "";
221
+ return `<script type="application/json" data-wd-store="${name}"${ephemeral}>${safeScriptJson(value)}</script>`;
222
+ }
223
+
224
+ /**
225
+ * Register a page-global store. The bare name is added to `comp.state` so every
226
+ * resolver (interpolation, :if, @loop, :computed, actions) sees it, and tracked
227
+ * in `comp.stores` for collision checks. Never section-scoped.
228
+ * @param {string} name
229
+ * @param {unknown} value
230
+ * @param {Ctx} ctx
231
+ * @returns {string} The store name (also its bare state key).
232
+ */
233
+ function declareStore(name, value, ctx) {
234
+ if (ctx.comp.stores.has(name))
235
+ throw new Error(`Store "${name}" is declared twice in ${ctx.file}. Use: :store name = value`);
236
+ if (ctx.comp.state.has(name))
237
+ throw new Error(
238
+ `Store "${name}" collides with a :state of the same name in ${ctx.file}. Use: :store name = value for the global, or rename one.`
239
+ );
240
+ ctx.comp.stores.add(name);
241
+ ctx.comp.state.set(name, value);
242
+ ctx.comp.assets.runtime = true;
243
+ return name;
244
+ }
245
+
246
+ /**
247
+ * Seed a `<name>_error` state key (null) if absent. Shared by :fetch and the
248
+ * round-trip :form so error fallbacks have a key to bind.
249
+ * @param {string} key
250
+ * @param {Ctx} ctx
251
+ * @returns {void}
252
+ */
253
+ function declareErrorState(key, ctx) {
254
+ const errorKey = `${key}_error`;
255
+ if (!ctx.comp.state.has(errorKey)) ctx.comp.state.set(errorKey, null);
256
+ }
257
+
258
+ const FETCH_USE =
259
+ 'Use: :fetch name from "url" [method=…] [timeout=ms] [retry=N] [when=visible] [headers=key] [body=key] [refresh=url]';
260
+
261
+ /**
262
+ * Parse a keyword-arg `:fetch` directive into a lifecycle-aware marker.
263
+ * Auto-declares four state keys (value/error/loading/empty), seeds them, and
264
+ * emits `data-wd-fetch-*` attributes (url/method/when/timeout/retry/headers/
265
+ * body/deps) consumed by the runtime's `startFetch`.
266
+ * @param {string} line
267
+ * @param {Ctx} ctx
268
+ * @param {number} index 0-based line index for `file:line` errors.
269
+ * @returns {string}
270
+ */
271
+ export function handleFetch(line, ctx, index) {
272
+ const head = line.match(/^:fetch\s+([A-Za-z_$][\w$]*)\s+from\s+("[^"]+"|\S+)\s*(.*)$/);
273
+ if (!head) throw new Error(`Malformed :fetch in ${at(ctx.file, index)}: ${line}. ${FETCH_USE}`);
274
+ const name = head[1];
275
+ const url = validateFetchUrl(stripQuotes(head[2]), ctx);
276
+ /** @type {Record<string, string>} */
277
+ const opts = {};
278
+ for (const part of head[3].trim().split(/\s+/).filter(Boolean)) {
279
+ const kv = part.match(/^([A-Za-z]+)=(.+)$/);
280
+ if (!kv)
281
+ throw new Error(`Unknown :fetch option "${part}" in ${at(ctx.file, index)}. ${FETCH_USE}`);
282
+ const optName = kv[1];
283
+ if (!["method", "when", "timeout", "retry", "headers", "body", "refresh"].includes(optName)) {
284
+ throw new Error(`Unknown :fetch option "${optName}" in ${at(ctx.file, index)}. ${FETCH_USE}`);
285
+ }
286
+ opts[optName] = stripQuotes(kv[2]);
287
+ }
288
+
289
+ if (
290
+ opts.method &&
291
+ !["GET", "POST", "PUT", "PATCH", "DELETE"].includes(opts.method.toUpperCase())
292
+ ) {
293
+ throw new Error(
294
+ `:fetch method "${opts.method}" is not allowed in ${at(ctx.file, index)}. ${FETCH_USE}`
295
+ );
296
+ }
297
+ if (opts.when && !["load", "visible"].includes(opts.when)) {
298
+ throw new Error(
299
+ `:fetch when "${opts.when}" is not allowed in ${at(ctx.file, index)}. ${FETCH_USE}`
300
+ );
301
+ }
302
+ for (const n of ["timeout", "retry"]) {
303
+ if (opts[n] !== undefined && !/^\d+$/.test(opts[n])) {
304
+ throw new Error(
305
+ `:fetch ${n} must be a non-negative integer in ${at(ctx.file, index)}. ${FETCH_USE}`
306
+ );
307
+ }
308
+ }
309
+ if (opts.refresh !== undefined) {
310
+ // Layer 2: a 401 triggers a token-refresh POST to this URL, then one retry.
311
+ // The new token is written back into the `headers=` state, so it is required.
312
+ if (!opts.headers) {
313
+ throw new Error(
314
+ `:fetch refresh= needs headers= (the state key holding the token to renew) in ${at(ctx.file, index)}. ${FETCH_USE}`
315
+ );
316
+ }
317
+ opts.refresh = validateFetchUrl(opts.refresh, ctx, ":fetch refresh");
318
+ }
319
+
320
+ // Extract `{ path }` dependency keys from the URL (validated against poison
321
+ // segments). The runtime fills them from state on each (re)fetch.
322
+ /** @type {string[]} */
323
+ const deps = [];
324
+ for (const dep of url.matchAll(/\{\s*([A-Za-z_$][\w$.]*)\s*\}/g)) {
325
+ validatePath(dep[1], ctx, FETCH_USE);
326
+ const headKey = dep[1].split(".")[0];
327
+ if (!deps.includes(headKey)) deps.push(headKey);
328
+ }
329
+
330
+ // Auto-declare the four lifecycle keys. `name` is declared via declareState
331
+ // (collision-checked); the derived keys are seeded directly.
332
+ const key = declareState(name, null, ctx);
333
+ /** @type {Record<string, unknown>} */
334
+ const seeds = { [key]: null };
335
+ for (const [suffix, seed] of [
336
+ ["_error", null],
337
+ ["_loading", false],
338
+ ["_empty", false]
339
+ ]) {
340
+ const k = `${key}${suffix}`;
341
+ if (!ctx.comp.state.has(k)) ctx.comp.state.set(k, seed);
342
+ seeds[k] = seed;
343
+ }
344
+
345
+ /** @param {string} n @param {string | null | false | undefined} v */
346
+ const attr = (n, v) =>
347
+ v != null && v !== false && v !== "" ? ` data-wd-fetch-${n}="${escapeHtml(v)}"` : "";
348
+ const marker =
349
+ `<span data-wd-fetch data-wd-fetch-key="${key}" data-wd-fetch-url="${escapeHtml(url)}"` +
350
+ attr("method", opts.method && opts.method.toUpperCase()) +
351
+ attr("when", opts.when === "visible" ? "visible" : "") +
352
+ attr("timeout", opts.timeout) +
353
+ attr("retry", opts.retry) +
354
+ attr("headers", opts.headers && resolveStateKey(opts.headers, ctx)) +
355
+ attr("body", opts.body && resolveStateKey(opts.body, ctx)) +
356
+ attr("refresh", opts.refresh) +
357
+ attr("deps", deps.join(",")) +
358
+ `></span>`;
359
+ return `<script type="application/json" data-wd-state>${safeScriptJson(seeds)}</script>${marker}`;
360
+ }
361
+
362
+ /**
363
+ * Validate a `:fetch` (or `refresh=`) URL's scheme at compile time. Mirrors the
364
+ * `:try` href guard: relative paths (`/`, `./`, `../`, bare), an `http(s)://`
365
+ * URL, or a leading `{ state }` interpolation are allowed; a protocol-relative
366
+ * `//host` or any non-http(s) scheme (`file:`, `data:`, `javascript:`, …) is
367
+ * rejected. Interpolated values are percent-encoded by the runtime, so a scheme
368
+ * cannot be injected through state at request time.
369
+ * @param {string} url
370
+ * @param {Ctx} ctx
371
+ * @param {string} [what] Option name for the error message.
372
+ * @returns {string}
373
+ */
374
+ function validateFetchUrl(url, ctx, what = ":fetch") {
375
+ const value = url.trim();
376
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional — rejects control characters in URLs/hrefs.
377
+ if (value !== url || value === "" || /[\u0000-\u001F\u007F]/.test(value)) {
378
+ throw new Error(
379
+ `Unsafe ${what} URL "${escapeHtml(url)}" in ${ctx.file}. Use a relative path (/, ./, ../), an http(s):// URL, or a { state } interpolation.`
380
+ );
381
+ }
382
+ if (value.startsWith("//")) {
383
+ throw new Error(
384
+ `Unsafe ${what} URL "${escapeHtml(url)}" in ${ctx.file}. Protocol-relative URLs are not allowed; use http:// or https:// explicitly.`
385
+ );
386
+ }
387
+ if (value.startsWith("{")) return value; // interpolation-first; the runtime percent-encodes state values
388
+ const scheme = value.match(/^([A-Za-z][A-Za-z0-9+.-]*):/);
389
+ if (scheme && !["http", "https"].includes(scheme[1].toLowerCase())) {
390
+ throw new Error(
391
+ `Unsafe ${what} URL "${escapeHtml(url)}" in ${ctx.file}. The "${scheme[1]}:" scheme is not allowed; use http://, https://, or a relative path.`
392
+ );
393
+ }
394
+ return value;
395
+ }
396
+
397
+ /**
398
+ * @param {string} line
399
+ * @param {Ctx} ctx
400
+ * @param {number} index 0-based line index for `file:line` errors.
401
+ * @returns {string}
402
+ */
403
+ export function handleComputed(line, ctx, index) {
404
+ const match = line.match(/^:computed\s+([A-Za-z_$][\w$]*)\s*=\s*(.+)$/);
405
+ if (!match)
406
+ throw new Error(
407
+ `Malformed :computed in ${at(ctx.file, index)}: ${line}. Use: :computed total = items.length * 4`
408
+ );
409
+ const expr = compileComputedExpr(match[2].trim(), ctx);
410
+ /** @type {unknown} */
411
+ let initial;
412
+ try {
413
+ /** @param {string} key @param {string} [path] */
414
+ const read = (key, path) => getPath(ctx.comp.state.get(key), path ? path.split(".") : []);
415
+ // Build-time mirror of the runtime's AGG helper, so a `:computed total = sum(...)`
416
+ // has the same initial value the runtime will recompute to.
417
+ const agg = (
418
+ /** @type {string} */ name,
419
+ /** @type {any} */ list,
420
+ /** @type {string} */ field
421
+ ) => (FORMATTERS[name] ? FORMATTERS[name](list, field == null ? [] : [field]) : undefined);
422
+ initial = new Function("S", "A", `return (${expr});`)(read, agg);
423
+ } catch {
424
+ console.warn(
425
+ `:computed "${match[2].trim()}" in ${ctx.file} could not be evaluated at build time; falling back to null. Check the expression.`
426
+ );
427
+ initial = null;
428
+ }
429
+ const key = declareState(match[1], initial ?? null, ctx);
430
+ 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>`;
431
+ }
432
+
433
+ /**
434
+ * @param {string} line
435
+ * @param {string[]} bodyLines
436
+ * @param {Ctx} ctx
437
+ * @param {number} index 0-based line index for `file:line` errors.
438
+ * @returns {string}
439
+ */
440
+ export function handleForm(line, bodyLines, ctx, index) {
441
+ const rest = line.slice(":form".length).trim();
442
+ const rawAction = rest.match(/action="([^"]+)"/)?.[1];
443
+ const method = rest.match(/method="([^"]+)"/)?.[1] || "post";
444
+ const into = rest.match(/(?:^|\s)into\s+([A-Za-z_$][\w$]*)/)?.[1];
445
+ const leftover = rest
446
+ .replace(/action="[^"]+"/, "")
447
+ .replace(/method="[^"]+"/, "")
448
+ .replace(/(?:^|\s)into\s+[A-Za-z_$][\w$]*/, "")
449
+ .trim();
450
+ if ((!rawAction && !into) || leftover) {
451
+ throw new Error(
452
+ `Malformed :form in ${at(ctx.file, index)}: ${line}. Use ':form into name' (client state), ':form action="/url"' (native post), or both (fetch round-trip into state).`
453
+ );
454
+ }
455
+ const action = rawAction ? validateFetchUrl(rawAction, ctx, ":form action") : undefined;
456
+ const inner = compileBody(bodyLines, ctx).trim();
457
+ if (!into) {
458
+ return `<form action="${escapeHtml(action)}" method="${escapeHtml(method)}">${inner}</form>`;
459
+ }
460
+ const key = declareState(into, null, ctx);
461
+ declareErrorState(key, ctx);
462
+ const actionAttrs = action
463
+ ? ` action="${escapeHtml(action)}" method="${escapeHtml(method)}"`
464
+ : "";
465
+ return `<script type="application/json" data-wd-state>${safeScriptJson({ [key]: null })}</script><form data-wd-form="${key}"${actionAttrs}>${inner}</form>`;
466
+ }
467
+
468
+ /**
469
+ * @param {string} line
470
+ * @param {Ctx} ctx
471
+ * @param {number} index 0-based line index for `file:line` errors.
472
+ * @returns {string}
473
+ */
474
+ export function handleInput(line, ctx, index) {
475
+ const match = line.match(/^:input\s+([A-Za-z_][\w-]*)\s*(.*)$/);
476
+ if (!match) throw new Error(`Malformed :input in ${at(ctx.file, index)}: ${line}`);
477
+ const attrs = [`name="${escapeHtml(match[1])}"`];
478
+ let type = "text";
479
+ let placeholder;
480
+ let hasAria = false;
481
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
482
+ for (const token of (match[2] || "").matchAll(re)) {
483
+ if (token[3]) {
484
+ if (!["required", "autofocus", "disabled", "readonly"].includes(token[3])) {
485
+ throw new Error(`Unknown :input flag "${token[3]}" in ${at(ctx.file, index)}`);
486
+ }
487
+ attrs.push(token[3]);
488
+ continue;
489
+ }
490
+ const value = stripQuotes(token[2]);
491
+ if (token[1] === "type") {
492
+ type = value;
493
+ continue;
494
+ }
495
+ if (
496
+ ![
497
+ "placeholder",
498
+ "value",
499
+ "min",
500
+ "max",
501
+ "step",
502
+ "pattern",
503
+ "autocomplete",
504
+ "aria-label",
505
+ "aria-describedby"
506
+ ].includes(token[1])
507
+ ) {
508
+ throw new Error(`Unknown :input attribute "${token[1]}" in ${at(ctx.file, index)}`);
509
+ }
510
+ if (token[1] === "placeholder") placeholder = value;
511
+ if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
512
+ attrs.push(`${token[1]}="${escapeHtml(value)}"`);
513
+ }
514
+ // Accessible name: if the author supplied neither aria-label nor aria-describedby,
515
+ // derive a non-visual aria-label from the placeholder, else from the field name.
516
+ // Never overrides an author-supplied aria attribute (zero layout impact).
517
+ if (!hasAria) {
518
+ attrs.push(`aria-label="${escapeHtml(placeholder || humanizeName(match[1]))}"`);
519
+ }
520
+ return `<input type="${escapeHtml(type)}" ${attrs.join(" ")}>`;
521
+ }
522
+
523
+ // :bind <state> [placeholder="…"] [type=…] — a live two-way input bound to a
524
+ // declared :state. Updates state on every keystroke; reflects state back when
525
+ // not focused. The state must be declared first (with :state).
526
+ /**
527
+ * @param {string} line
528
+ * @param {Ctx} ctx
529
+ * @param {number} index 0-based line index for `file:line` errors.
530
+ * @returns {string}
531
+ */
532
+ export function handleBind(line, ctx, index) {
533
+ const match = line.match(/^:bind\s+([A-Za-z_$][\w$]*)\s*(.*)$/);
534
+ if (!match)
535
+ throw new Error(
536
+ `Malformed :bind in ${at(ctx.file, index)}: ${line}. Use: :bind query placeholder="Search"`
537
+ );
538
+ const key = resolveStateKey(match[1], ctx);
539
+ if (!key) {
540
+ throw new Error(
541
+ `:bind ${match[1]} in ${ctx.file} has no matching state. Declare it first: :state ${match[1]} = ""`
542
+ );
543
+ }
544
+ ctx.comp.assets.runtime = true;
545
+ let type = "text";
546
+ let placeholder;
547
+ let hasAria = false;
548
+ const attrs = [];
549
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
550
+ for (const token of (match[2] || "").matchAll(re)) {
551
+ if (token[3]) {
552
+ if (!["required", "autofocus"].includes(token[3]))
553
+ throw new Error(`Unknown :bind flag "${token[3]}" in ${at(ctx.file, index)}`);
554
+ attrs.push(token[3]);
555
+ continue;
556
+ }
557
+ const value = stripQuotes(token[2]);
558
+ if (token[1] === "type") {
559
+ type = value;
560
+ continue;
561
+ }
562
+ if (!["placeholder", "autocomplete", "aria-label", "aria-describedby"].includes(token[1])) {
563
+ throw new Error(`Unknown :bind attribute "${token[1]}" in ${at(ctx.file, index)}`);
564
+ }
565
+ if (token[1] === "placeholder") placeholder = value;
566
+ if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
567
+ attrs.push(`${token[1]}="${escapeHtml(value)}"`);
568
+ }
569
+ // Accessible name (see handleInput): default a non-visual aria-label from the
570
+ // placeholder, else a humanized version of the bound state key. The author's own
571
+ // aria-label/aria-describedby always wins.
572
+ if (!hasAria) {
573
+ attrs.push(`aria-label="${escapeHtml(placeholder || humanizeName(match[1]))}"`);
574
+ }
575
+ const initial = ctx.comp.state.get(key);
576
+ const valueAttr =
577
+ initial === undefined || initial === null ? "" : ` value="${escapeHtml(String(initial))}"`;
578
+ return `<input type="${escapeHtml(type)}" data-wd-bind-input="${key}"${valueAttr} ${attrs.join(" ")}>`;
579
+ }
580
+
581
+ /**
582
+ * @param {string} line
583
+ * @param {Ctx} ctx
584
+ * @param {number} index 0-based line index for `file:line` errors.
585
+ * @returns {string}
586
+ */
587
+ export function handleSubmit(line, ctx, index) {
588
+ const match = line.match(/^:submit\s+"([^"]+)"\s*$/);
589
+ if (!match)
590
+ throw new Error(`Malformed :submit in ${at(ctx.file, index)}: ${line}. Use: :submit "Label"`);
591
+ return `<button type="submit">${escapeHtml(match[1])}</button>`;
592
+ }
593
+
594
+ /**
595
+ * `:textarea name [placeholder="…"] [rows=N] [required]` → a `<textarea>`. Like
596
+ * `:input`, it derives a non-visual aria-label from the placeholder (else the
597
+ * humanized name) when the author supplies none. Captured by the runtime's
598
+ * FormData exactly like `:input` — no runtime change needed.
599
+ * @param {string} line
600
+ * @param {Ctx} ctx
601
+ * @param {number} index 0-based line index for `file:line` errors.
602
+ * @returns {string}
603
+ */
604
+ export function handleTextarea(line, ctx, index) {
605
+ const match = line.match(/^:textarea\s+([A-Za-z_][\w-]*)\s*(.*)$/);
606
+ if (!match)
607
+ throw new Error(
608
+ `Malformed :textarea in ${at(ctx.file, index)}: ${line}. Use: :textarea name [placeholder="…"] [rows=N] [required]`
609
+ );
610
+ const attrs = [`name="${escapeHtml(match[1])}"`];
611
+ let placeholder;
612
+ let hasAria = false;
613
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
614
+ for (const token of (match[2] || "").matchAll(re)) {
615
+ if (token[3]) {
616
+ if (!["required", "autofocus", "disabled", "readonly"].includes(token[3])) {
617
+ throw new Error(`Unknown :textarea flag "${token[3]}" in ${at(ctx.file, index)}`);
618
+ }
619
+ attrs.push(token[3]);
620
+ continue;
621
+ }
622
+ const value = stripQuotes(token[2]);
623
+ if (
624
+ ![
625
+ "placeholder",
626
+ "rows",
627
+ "cols",
628
+ "minlength",
629
+ "maxlength",
630
+ "autocomplete",
631
+ "aria-label",
632
+ "aria-describedby"
633
+ ].includes(token[1])
634
+ ) {
635
+ throw new Error(`Unknown :textarea attribute "${token[1]}" in ${at(ctx.file, index)}`);
636
+ }
637
+ if (token[1] === "placeholder") placeholder = value;
638
+ if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
639
+ attrs.push(`${token[1]}="${escapeHtml(value)}"`);
640
+ }
641
+ if (!hasAria) {
642
+ attrs.push(`aria-label="${escapeHtml(placeholder || humanizeName(match[1]))}"`);
643
+ }
644
+ return `<textarea ${attrs.join(" ")}></textarea>`;
645
+ }
646
+
647
+ /**
648
+ * `:select name [required]` followed by `- Label` list lines → a `<select>` with
649
+ * one `<option>` per label (value === label). Derives an aria-label from the
650
+ * humanized name when none is given. Captured by FormData like the other fields.
651
+ * @param {string} line
652
+ * @param {string[]} optionLines The following `- Label` lines consumed by dispatch.
653
+ * @param {Ctx} ctx
654
+ * @param {number} index 0-based line index for `file:line` errors.
655
+ * @returns {string}
656
+ */
657
+ export function handleSelect(line, optionLines, ctx, index) {
658
+ const match = line.match(/^:select\s+([A-Za-z_][\w-]*)\s*(.*)$/);
659
+ if (!match)
660
+ throw new Error(
661
+ `Malformed :select in ${at(ctx.file, index)}: ${line}. Use: :select name [required] then "- Label" lines`
662
+ );
663
+ const attrs = [`name="${escapeHtml(match[1])}"`];
664
+ let hasAria = false;
665
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
666
+ for (const token of (match[2] || "").matchAll(re)) {
667
+ if (token[3]) {
668
+ if (!["required", "disabled", "autofocus"].includes(token[3])) {
669
+ throw new Error(`Unknown :select flag "${token[3]}" in ${at(ctx.file, index)}`);
670
+ }
671
+ attrs.push(token[3]);
672
+ continue;
673
+ }
674
+ const value = stripQuotes(token[2]);
675
+ if (!["autocomplete", "aria-label", "aria-describedby"].includes(token[1])) {
676
+ throw new Error(`Unknown :select attribute "${token[1]}" in ${at(ctx.file, index)}`);
677
+ }
678
+ if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
679
+ attrs.push(`${token[1]}="${escapeHtml(value)}"`);
680
+ }
681
+ if (!hasAria) {
682
+ attrs.push(`aria-label="${escapeHtml(humanizeName(match[1]))}"`);
683
+ }
684
+ const options = optionLines.map((l) => l.replace(/^\s*-\s+/, "").trim()).filter(Boolean);
685
+ if (!options.length) {
686
+ throw new Error(
687
+ `:select "${match[1]}" in ${at(ctx.file, index)} has no options. Add "- Label" lines beneath it.`
688
+ );
689
+ }
690
+ const opts = options
691
+ .map((o) => `<option value="${escapeHtml(o)}">${escapeHtml(o)}</option>`)
692
+ .join("");
693
+ return `<select ${attrs.join(" ")}>${opts}</select>`;
694
+ }
695
+
696
+ /**
697
+ * `:checkbox name [required]` / `:radio name [required]` followed by `- Label`
698
+ * lines → a labelled group of `<input type=checkbox|radio>`, each sharing `name`
699
+ * with value === label and wrapped in its own `<label>`. The group is a
700
+ * `role="group"` / `role="radiogroup"` container with an aria-label (explicit or
701
+ * humanized from the name). Checkbox groups are marked `data-wd-multi="name"` so
702
+ * the runtime captures every checked value as an array (`FormData.getAll`); radio
703
+ * groups capture a single value like `:input`. Flags: `required` (radio → the
704
+ * group; not emitted on checkboxes, where "at least one" has no native HTML form),
705
+ * `disabled` (whole group), `autofocus` (first control).
706
+ * @param {string} line
707
+ * @param {string[]} optionLines The following `- Label` lines consumed by dispatch.
708
+ * @param {Ctx} ctx
709
+ * @param {"checkbox" | "radio"} kind
710
+ * @param {number} index 0-based line index for `file:line` errors.
711
+ * @returns {string}
712
+ */
713
+ export function handleChoiceGroup(line, optionLines, ctx, kind, index) {
714
+ const directive = `:${kind}`;
715
+ const match = line.match(
716
+ kind === "checkbox"
717
+ ? /^:checkbox\s+([A-Za-z_][\w-]*)\s*(.*)$/
718
+ : /^:radio\s+([A-Za-z_][\w-]*)\s*(.*)$/
719
+ );
720
+ if (!match)
721
+ throw new Error(
722
+ `Malformed ${directive} in ${at(ctx.file, index)}: ${line}. Use: ${directive} name [required] then "- Label" lines`
723
+ );
724
+ const name = match[1];
725
+ const flags = [];
726
+ let ariaLabel = null;
727
+ let ariaDescribedby = null;
728
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
729
+ for (const token of (match[2] || "").matchAll(re)) {
730
+ if (token[3]) {
731
+ if (!["required", "disabled", "autofocus"].includes(token[3])) {
732
+ throw new Error(`Unknown ${directive} flag "${token[3]}" in ${at(ctx.file, index)}`);
733
+ }
734
+ flags.push(token[3]);
735
+ continue;
736
+ }
737
+ const value = stripQuotes(token[2]);
738
+ if (token[1] === "aria-label") ariaLabel = value;
739
+ else if (token[1] === "aria-describedby") ariaDescribedby = value;
740
+ else throw new Error(`Unknown ${directive} attribute "${token[1]}" in ${at(ctx.file, index)}`);
741
+ }
742
+ const options = optionLines.map((l) => l.replace(/^\s*-\s+/, "").trim()).filter(Boolean);
743
+ if (!options.length) {
744
+ throw new Error(
745
+ `${directive} "${name}" in ${at(ctx.file, index)} has no options. Add "- Label" lines beneath it.`
746
+ );
747
+ }
748
+ const isCheckbox = kind === "checkbox";
749
+ const groupAttrs = [
750
+ `class="wd-${isCheckbox ? "checkboxes" : "radios"}"`,
751
+ `role="${isCheckbox ? "group" : "radiogroup"}"`
752
+ ];
753
+ if (isCheckbox) groupAttrs.push(`data-wd-multi="${escapeHtml(name)}"`);
754
+ groupAttrs.push(`aria-label="${escapeHtml(ariaLabel || humanizeName(name))}"`);
755
+ if (ariaDescribedby) groupAttrs.push(`aria-describedby="${escapeHtml(ariaDescribedby)}"`);
756
+ const disabled = flags.includes("disabled");
757
+ const required = flags.includes("required");
758
+ const autofocus = flags.includes("autofocus");
759
+ const controls = options
760
+ .map((opt, idx) => {
761
+ const a = [`type="${kind}"`, `name="${escapeHtml(name)}"`, `value="${escapeHtml(opt)}"`];
762
+ if (disabled) a.push("disabled");
763
+ if (required && !isCheckbox) a.push("required");
764
+ if (autofocus && idx === 0) a.push("autofocus");
765
+ return `<label><input ${a.join(" ")}> ${escapeHtml(opt)}</label>`;
766
+ })
767
+ .join("");
768
+ return `<div ${groupAttrs.join(" ")}>${controls}</div>`;
769
+ }
770
+
771
+ /**
772
+ * @param {string} line
773
+ * @param {Ctx} ctx
774
+ * @param {number} index 0-based line index for `file:line` errors.
775
+ * @returns {string}
776
+ */
777
+ export function handleButton(line, ctx, index) {
778
+ const match = line.match(/^:button\s+"([^"]+)"\s*->\s*(.+)$/);
779
+ if (!match) throw new Error(`Malformed :button in ${at(ctx.file, index)}: ${line}`);
780
+ ctx.comp.assets.runtime = true;
781
+ const action = parseAction(match[2], ctx);
782
+ if (Array.isArray(action)) {
783
+ return `<button type="button" data-wd-actions="${escapeHtml(JSON.stringify(action))}">${escapeHtml(match[1])}</button>`;
784
+ }
785
+ const valueAttr =
786
+ action.value === undefined
787
+ ? ""
788
+ : ` data-wd-value="${escapeHtml(JSON.stringify(action.value))}"`;
789
+ return `<button type="button" data-wd-action="${action.op}" data-wd-target="${action.target}"${valueAttr}>${escapeHtml(match[1])}</button>`;
790
+ }
791
+
792
+ const EFFECT_USE =
793
+ "Use: :effect watchedState -> action[; action…] (actions use the :button vocabulary).";
794
+
795
+ /**
796
+ * Parse `:effect <watched> -> <actions>` into a zero-output marker the runtime
797
+ * watches: when `<watched>` state changes, it runs `<actions>` (the same `:button`
798
+ * action vocabulary, `;`-chained). For arbitrary side effects beyond `:computed`
799
+ * (derive state) and fetch deps (auto-refetch).
800
+ * @param {string} line
801
+ * @param {Ctx} ctx
802
+ * @param {number} index 0-based line index for `file:line` errors.
803
+ * @returns {string}
804
+ */
805
+ export function handleEffect(line, ctx, index) {
806
+ const match = line.match(/^:effect\s+([A-Za-z_$][\w$.]*)\s*->\s*(.+)$/);
807
+ if (!match)
808
+ throw new Error(`Malformed :effect in ${at(ctx.file, index)}: ${line}. ${EFFECT_USE}`);
809
+ const segs = validatePath(match[1], ctx, EFFECT_USE);
810
+ const key = resolveStateKey(segs[0], ctx);
811
+ if (!key)
812
+ throw new Error(
813
+ `:effect watches unknown state "${segs[0]}" in ${ctx.file}. Declare it first with :state ${segs[0]} = ...`
814
+ );
815
+ ctx.comp.assets.runtime = true;
816
+ const watch = [key, ...segs.slice(1)].join(".");
817
+ const action = parseAction(match[2], ctx);
818
+ const actions = Array.isArray(action) ? action : [action];
819
+ return `<script type="application/json" data-wd-effect>${safeScriptJson({ watch, actions })}</script>`;
820
+ }
821
+
822
+ const EVERY_USE =
823
+ "Use: :every <duration> -> action[; action…] — duration like 5s, 500ms, or 2m (actions use the :button vocabulary).";
824
+
825
+ /**
826
+ * Parse a duration token into milliseconds: `<int>[ms|s|m]`, defaulting to ms.
827
+ * @param {string} raw
828
+ * @returns {number | null}
829
+ */
830
+ function parseDuration(raw) {
831
+ const match = raw.trim().match(/^(\d+)(ms|s|m)?$/);
832
+ if (!match) return null;
833
+ const n = Number(match[1]);
834
+ return match[2] === "s" ? n * 1000 : match[2] === "m" ? n * 60000 : n;
835
+ }
836
+
837
+ /**
838
+ * Parse `:every <duration> -> <actions>` into a marker the runtime drives on a
839
+ * timer: every `<duration>` it runs `<actions>` (the same `:button` vocabulary,
840
+ * `;`-chained), and the interval auto-pauses while the tab is hidden. The one time
841
+ * primitive — behind live polling (`:every 5s -> board refetch`), clocks and
842
+ * countdowns (`:every 1s -> seconds++`), and slideshow autoplay (`:every 4s -> slide++`).
843
+ * @param {string} line
844
+ * @param {Ctx} ctx
845
+ * @param {number} index 0-based line index for `file:line` errors.
846
+ * @returns {string}
847
+ */
848
+ export function handleEvery(line, ctx, index) {
849
+ const match = line.match(/^:every\s+(\S+)\s*->\s*(.+)$/);
850
+ if (!match) throw new Error(`Malformed :every in ${at(ctx.file, index)}: ${line}. ${EVERY_USE}`);
851
+ const ms = parseDuration(match[1]);
852
+ if (ms == null || ms <= 0) {
853
+ throw new Error(
854
+ `:every duration "${match[1]}" is not valid in ${at(ctx.file, index)}. ${EVERY_USE}`
855
+ );
856
+ }
857
+ ctx.comp.assets.runtime = true;
858
+ const action = parseAction(match[2], ctx);
859
+ const actions = Array.isArray(action) ? action : [action];
860
+ return `<script type="application/json" data-wd-every>${safeScriptJson({ ms, actions })}</script>`;
861
+ }
862
+
863
+ /**
864
+ * `:theme [name] [= "auto"]` declares a durable `:store` (default name `theme`,
865
+ * seed `"auto"`) and reflects its value onto `<html data-theme>`. This layers a
866
+ * manual light/dark switch over the OS preference: `"auto"` follows the skin's
867
+ * `tokens dark` media query, while `"light"`/`"dark"` force the matching
868
+ * `:root[data-theme]` scope. Wire a switch with ordinary store actions —
869
+ * `:button "Dark" -> theme = "dark"`. Durable, so the choice survives reloads.
870
+ * @param {string} line
871
+ * @param {Ctx} ctx
872
+ * @param {number} index 0-based line index for `file:line` errors.
873
+ * @returns {string}
874
+ */
875
+ export function handleTheme(line, ctx, index) {
876
+ const match = line.match(/^:theme(?:\s+([A-Za-z_$][\w$]*))?(?:\s*=\s*(.+))?$/);
877
+ if (!match) {
878
+ throw new Error(
879
+ `Malformed :theme in ${at(ctx.file, index)}: ${line}. Use: :theme (or :theme name = "auto")`
880
+ );
881
+ }
882
+ const name = match[1] || "theme";
883
+ const seed = match[2] != null ? parseStateValue(match[2], at(ctx.file, index)) : "auto";
884
+ const storeName = declareStore(name, seed, ctx);
885
+ return `<script type="application/json" data-wd-store="${storeName}">${safeScriptJson(seed)}</script><span data-wd-theme="${storeName}" hidden></span>`;
886
+ }
887
+
888
+ // ---------------------------------------------------------------------------
889
+ // Media — :video / :audio / :embed. Compile-time only (zero runtime): hardened
890
+ // HTML5 media and privacy-friendly, lazy iframe embeds. The extension stays the
891
+ // feature gate; these emit no `data-wd-*`, so a media-only page ships zero JS.
892
+ // ---------------------------------------------------------------------------
893
+
894
+ /** @type {Record<"video" | "audio", { flags: string[], attrs: string[] }>} */
895
+ const MEDIA_SPEC = {
896
+ video: {
897
+ flags: ["controls", "autoplay", "loop", "muted", "playsinline"],
898
+ attrs: ["poster", "width", "height", "preload"]
899
+ },
900
+ audio: { flags: ["controls", "autoplay", "loop", "muted"], attrs: ["preload"] }
901
+ };
902
+
903
+ /**
904
+ * `:video /clip.mp4 [poster=…] [width=…] [height=…] [preload=…] [controls] [autoplay]
905
+ * [loop] [muted] [playsinline]` and `:audio /track.mp3 [preload=…] [controls] …` →
906
+ * a hardened `<video>`/`<audio>`. Defaults: `preload="metadata"`, and `controls`
907
+ * unless the clip is an `autoplay` background (autoplay also implies `muted`, which
908
+ * browsers require). Author flags/attrs always win. URLs use the `:fetch` scheme
909
+ * guard (relative or http(s)).
910
+ * @param {string} line
911
+ * @param {"video" | "audio"} kind
912
+ * @param {Ctx} ctx
913
+ * @param {number} index 0-based line index for `file:line` errors.
914
+ * @returns {string}
915
+ */
916
+ export function handleMedia(line, kind, ctx, index) {
917
+ const match = line.match(new RegExp(`^:${kind}\\s+(\\S+)\\s*(.*)$`));
918
+ if (!match) {
919
+ throw new Error(
920
+ `Malformed :${kind} in ${at(ctx.file, index)}: ${line}. Use: :${kind} /clip [controls] [autoplay] [loop] [muted]`
921
+ );
922
+ }
923
+ const src = validateFetchUrl(stripQuotes(match[1]), ctx, `:${kind}`);
924
+ const spec = MEDIA_SPEC[kind];
925
+ /** @type {Set<string>} */
926
+ const flags = new Set();
927
+ /** @type {Map<string, string>} */
928
+ const attrs = new Map();
929
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
930
+ for (const token of (match[2] || "").matchAll(re)) {
931
+ if (token[3]) {
932
+ if (!spec.flags.includes(token[3]))
933
+ throw new Error(`Unknown :${kind} flag "${token[3]}" in ${at(ctx.file, index)}`);
934
+ flags.add(token[3]);
935
+ } else {
936
+ if (!spec.attrs.includes(token[1]))
937
+ throw new Error(`Unknown :${kind} attribute "${token[1]}" in ${at(ctx.file, index)}`);
938
+ attrs.set(token[1], stripQuotes(token[2]));
939
+ }
940
+ }
941
+ // Sensible defaults; author input always wins.
942
+ if (flags.has("autoplay")) flags.add("muted"); // browsers block unmuted autoplay
943
+ if (kind === "audio" || !flags.has("autoplay")) flags.add("controls");
944
+ const parts = [`src="${escapeHtml(src)}"`];
945
+ if (attrs.has("poster"))
946
+ parts.push(
947
+ `poster="${escapeHtml(validateFetchUrl(/** @type {string} */ (attrs.get("poster")), ctx, `:${kind} poster`))}"`
948
+ );
949
+ for (const name of ["width", "height"]) {
950
+ if (attrs.has(name))
951
+ parts.push(`${name}="${escapeHtml(/** @type {string} */ (attrs.get(name)))}"`);
952
+ }
953
+ parts.push(`preload="${escapeHtml(attrs.get("preload") || "metadata")}"`);
954
+ for (const flag of spec.flags) if (flags.has(flag)) parts.push(flag);
955
+ return `<${kind} ${parts.join(" ")}></${kind}>`;
956
+ }
957
+
958
+ /**
959
+ * `:embed <url> [title="…"]` → a lazy, privacy-friendly responsive iframe. A
960
+ * YouTube or Vimeo URL is rewritten to its no-cookie / player embed; any other
961
+ * http(s) URL becomes a generic 16:9 iframe. Inline styles keep the wrapper
962
+ * self-contained (no framework CSS), so an embed-only page stays zero-JS/zero-CSS.
963
+ * @param {string} line
964
+ * @param {Ctx} ctx
965
+ * @param {number} index 0-based line index for `file:line` errors.
966
+ * @returns {string}
967
+ */
968
+ export function handleEmbed(line, ctx, index) {
969
+ const match = line.match(/^:embed\s+(\S+)\s*(.*)$/);
970
+ if (!match) {
971
+ throw new Error(
972
+ `Malformed :embed in ${at(ctx.file, index)}: ${line}. Use: :embed https://youtu.be/ID [title="…"]`
973
+ );
974
+ }
975
+ const raw = stripQuotes(match[1]);
976
+ let title = "";
977
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)/g;
978
+ for (const token of (match[2] || "").matchAll(re)) {
979
+ if (token[1] !== "title")
980
+ throw new Error(`Unknown :embed attribute "${token[1]}" in ${at(ctx.file, index)}`);
981
+ title = stripQuotes(token[2]);
982
+ }
983
+ const { url, label } = resolveEmbed(raw, ctx);
984
+ const iframe =
985
+ `<iframe src="${escapeHtml(url)}" title="${escapeHtml(title || label)}" loading="lazy" ` +
986
+ `referrerpolicy="strict-origin-when-cross-origin" ` +
987
+ `allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" ` +
988
+ `allowfullscreen style="width:100%;height:100%;border:0"></iframe>`;
989
+ return `<div class="wd-embed" style="aspect-ratio:16/9">${iframe}</div>`;
990
+ }
991
+
992
+ /**
993
+ * Map a watch/share URL to its embeddable form. YouTube → no-cookie embed, Vimeo →
994
+ * player; anything else is validated as a generic http(s) iframe source.
995
+ * @param {string} raw
996
+ * @param {Ctx} ctx
997
+ * @returns {{ url: string, label: string }}
998
+ */
999
+ function resolveEmbed(raw, ctx) {
1000
+ const youtube = raw.match(
1001
+ /(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{6,})/
1002
+ );
1003
+ if (youtube)
1004
+ return { url: `https://www.youtube-nocookie.com/embed/${youtube[1]}`, label: "YouTube video" };
1005
+ const vimeo = raw.match(/vimeo\.com\/(?:video\/)?(\d+)/);
1006
+ if (vimeo) return { url: `https://player.vimeo.com/video/${vimeo[1]}`, label: "Vimeo video" };
1007
+ return { url: validateFetchUrl(raw, ctx, ":embed"), label: "Embedded content" };
1008
+ }
1009
+
1010
+ /**
1011
+ * @param {string} line
1012
+ * @param {string[]} truthyLines
1013
+ * @param {string[]} falsyLines
1014
+ * @param {Ctx} ctx
1015
+ * @param {number} index 0-based line index for `file:line` errors.
1016
+ * @returns {string}
1017
+ */
1018
+ export function handleIf(line, truthyLines, falsyLines, ctx, index) {
1019
+ const condition = line.replace(/^:if\s+/, "").trim();
1020
+ // Fast path: a bare truthy dotted path (`:if open`, `:if item.done`). Keeps the
1021
+ // existing markup/behavior identical. Anything with operators (`>`, `==`, `and`,
1022
+ // `not`, …) falls through to the predicate path below.
1023
+ const match = condition.match(/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)$/);
1024
+ if (match) {
1025
+ const segs = match[1].split(".");
1026
+ const head = segs[0];
1027
+
1028
+ // Per-row meta vars in :if — only valid inside a loop.
1029
+ if (LOOP_META[head]) {
1030
+ if (!ctx.loopMeta)
1031
+ throw new Error(
1032
+ `":if ${match[1]}" uses the loop meta variable "${head}" outside a @loop in ${ctx.file}. Use it inside a loop body.`
1033
+ );
1034
+ if (ctx.loopItem) {
1035
+ const truthy = compileBody(truthyLines, ctx).trim();
1036
+ const falsy = compileBody(falsyLines, ctx).trim();
1037
+ 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>`;
1038
+ }
1039
+ // static: the meta boolean is in scope — fall through to the static branch below.
1040
+ }
1041
+
1042
+ const staticValue = lookupVar(ctx.scope, head);
1043
+ if (staticValue.found) {
1044
+ const active = Boolean(getPath(staticValue.value, segs.slice(1)));
1045
+ return compileBody(active ? truthyLines : falsyLines, ctx);
1046
+ }
1047
+
1048
+ if (ctx.loopItem && head === ctx.loopItem) {
1049
+ const truthy = compileBody(truthyLines, ctx).trim();
1050
+ const falsy = compileBody(falsyLines, ctx).trim();
1051
+ const rest = segs.slice(1).join(".");
1052
+ const pathAttr = ` data-wd-path="${escapeHtml(rest)}"`;
1053
+ 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>`;
1054
+ }
1055
+
1056
+ const key = resolveStateKey(head, ctx);
1057
+ if (!key) {
1058
+ throw new Error(
1059
+ `:if ${match[1]} in ${ctx.file} does not match a :state or in-scope value. Declare it first.`
1060
+ );
1061
+ }
1062
+ ctx.comp.assets.runtime = true;
1063
+ const truthy = compileBody(truthyLines, ctx).trim();
1064
+ const falsy = compileBody(falsyLines, ctx).trim();
1065
+ const restPath = segs.slice(1).join(".");
1066
+ const pathAttr = restPath ? ` data-wd-path="${escapeHtml(restPath)}"` : "";
1067
+ const initialTruthy = Boolean(getPath(ctx.comp.state.get(key), segs.slice(1)));
1068
+ const active = initialTruthy ? truthy : falsy;
1069
+ 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>`;
1070
+ }
1071
+
1072
+ // Predicate path: a comparison / logical condition. Compiles through the same
1073
+ // whitelist as `@loop … where` / `.class when` (with `not`), so it folds at
1074
+ // build when static, drives a per-row each-if when it reads the loop item, and
1075
+ // a global if-region (evaluated each render) when it reads state. No raw eval.
1076
+ if (!condition)
1077
+ throw new Error(
1078
+ `Malformed :if in ${at(ctx.file, index)}: ${line}. Use ":if name" or ":if a <op> b [and|or|not …]".`
1079
+ );
1080
+ const compiled = compileWhen(condition, ctx, '":if"');
1081
+ if (compiled.static) return compileBody(compiled.value ? truthyLines : falsyLines, ctx);
1082
+ ctx.comp.assets.runtime = true;
1083
+ const truthy = compileBody(truthyLines, ctx).trim();
1084
+ const falsy = compileBody(falsyLines, ctx).trim();
1085
+ const exprAttr = ` data-wd-if-expr="${escapeHtml(compiled.body)}"`;
1086
+ if (compiled.item) {
1087
+ 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>`;
1088
+ }
1089
+ const initialTruthy = evalPredicate(compiled.body, undefined, ctx);
1090
+ const active = initialTruthy ? truthy : falsy;
1091
+ 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>`;
1092
+ }
1093
+
1094
+ /**
1095
+ * Render the documentation-demo directives (`:try`, `:note`, `:sprint`).
1096
+ * @param {string} line
1097
+ * @param {Ctx} ctx
1098
+ * @returns {string}
1099
+ */
1100
+ export function renderDemoDirective(line, ctx) {
1101
+ const tryMatch = line.match(/^:try\s+"([^"]+)"\s+href="([^"]+)"$/);
1102
+ if (tryMatch) {
1103
+ const href = validateDemoHref(tryMatch[2], ctx);
1104
+ return `<a class="try-card" href="${escapeHtml(href)}"><span>Try</span>${escapeHtml(tryMatch[1])}</a>`;
1105
+ }
1106
+ const note = line.match(/^:note\s+"([^"]+)"$/);
1107
+ if (note) return `<aside class="note">${escapeHtml(note[1])}</aside>`;
1108
+ const sprint = line.match(/^:sprint\s+min=(\d+)\s+max=(\d+)\s+roles="([^"]+)"$/);
1109
+ if (sprint) {
1110
+ const roles = sprint[3]
1111
+ .split(",")
1112
+ .map((role) => role.trim())
1113
+ .filter(Boolean);
1114
+ 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>`;
1115
+ }
1116
+ return "";
1117
+ }
1118
+
1119
+ /**
1120
+ * Validate demo-card links without adding arbitrary URL passthrough.
1121
+ * @param {string} href
1122
+ * @param {Ctx} ctx
1123
+ * @returns {string}
1124
+ */
1125
+ function validateDemoHref(href, ctx) {
1126
+ const value = href.trim();
1127
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional — rejects control characters in URLs/hrefs.
1128
+ if (value !== href || /[\u0000-\u001F\u007F]/.test(value)) {
1129
+ throw new Error(
1130
+ `Unsafe :try href "${escapeHtml(href)}" in ${ctx.file}. Use a relative URL starting with /, ./, ../, or #, or an http:, https:, or mailto: URL.`
1131
+ );
1132
+ }
1133
+ if (value.startsWith("//")) {
1134
+ throw new Error(
1135
+ `Unsafe :try href "${escapeHtml(href)}" in ${ctx.file}. Protocol-relative URLs are not allowed; use http: or https: explicitly.`
1136
+ );
1137
+ }
1138
+ if (
1139
+ value.startsWith("/") ||
1140
+ value.startsWith("./") ||
1141
+ value.startsWith("../") ||
1142
+ value.startsWith("#")
1143
+ ) {
1144
+ return value;
1145
+ }
1146
+ const scheme = value.match(/^([A-Za-z][A-Za-z0-9+.-]*):/);
1147
+ if (scheme && ["http", "https", "mailto"].includes(scheme[1].toLowerCase())) {
1148
+ return value;
1149
+ }
1150
+ throw new Error(
1151
+ `Unsafe :try href "${escapeHtml(href)}" in ${ctx.file}. Use a relative URL starting with /, ./, ../, or #, or an http:, https:, or mailto: URL.`
1152
+ );
1153
+ }
1154
+
1155
+ // ---------------------------------------------------------------------------
1156
+ // Actions
1157
+ // ---------------------------------------------------------------------------
1158
+
1159
+ const ACTION_USE =
1160
+ '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 ";".';
1161
+
1162
+ /**
1163
+ * Parse a `:button` action expression into a validated `{ op, target, value }`,
1164
+ * or — when `;`-separated — an ordered array of them applied in sequence.
1165
+ * @param {string} raw
1166
+ * @param {Ctx} ctx
1167
+ * @returns {Action | Action[]}
1168
+ */
1169
+ function parseAction(raw, ctx) {
1170
+ const parts = raw
1171
+ .split(";")
1172
+ .map((p) => p.trim())
1173
+ .filter(Boolean);
1174
+ if (parts.length > 1) return parts.map((part) => parseSingleAction(part, raw, ctx));
1175
+ return parseSingleAction(raw.trim(), raw, ctx);
1176
+ }
1177
+
1178
+ /**
1179
+ * Parse one (non-`;`) action expression into a validated `{ op, target, value }`.
1180
+ * Targets may be dotted paths (`cart.count`); a bare name is a 1-segment path.
1181
+ * @param {string} expression
1182
+ * @param {string} raw The full original action source (for error context).
1183
+ * @param {Ctx} ctx
1184
+ * @returns {Action}
1185
+ */
1186
+ function parseSingleAction(expression, raw, ctx) {
1187
+ const PATH = "[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*";
1188
+ /** @param {string} name @returns {string} */
1189
+ const resolveTarget = (name) => {
1190
+ const segs = validatePath(name, ctx, ACTION_USE);
1191
+ const key = resolveStateKey(segs[0], ctx);
1192
+ if (!key) {
1193
+ throw new Error(
1194
+ `Button action targets unknown state "${segs[0]}" in ${ctx.file}. Declare it first with :state ${segs[0]} = ...`
1195
+ );
1196
+ }
1197
+ return [key, ...segs.slice(1)].join(".");
1198
+ };
1199
+
1200
+ const increment = expression.match(new RegExp(`^(${PATH})\\+\\+$`));
1201
+ if (increment) return { op: "inc", target: resolveTarget(increment[1]) };
1202
+ const decrement = expression.match(new RegExp(`^(${PATH})--$`));
1203
+ if (decrement) return { op: "dec", target: resolveTarget(decrement[1]) };
1204
+ const sub = expression.match(new RegExp(`^(${PATH})\\s*-=\\s*(.+)$`));
1205
+ if (sub)
1206
+ return { op: "sub", target: resolveTarget(sub[1]), value: parseActionLiteral(sub[2], ctx) };
1207
+ // Per-row: carry the current loop item into another list — `cart += product`.
1208
+ // Only inside a reactive @loop; the runtime resolves the row from the DOM.
1209
+ const add = expression.match(new RegExp(`^(${PATH})\\s*\\+=\\s*(.+)$`));
1210
+ if (add) {
1211
+ const rhs = add[2].trim();
1212
+ if (ctx.loopItem && rhs === ctx.loopItem) {
1213
+ const target = resolveTarget(add[1]);
1214
+ if (!Array.isArray(ctx.comp.state.get(target))) {
1215
+ throw new Error(
1216
+ `Button action "${raw}" needs ${add[1]} to be a :state list (declare it "${add[1]} = []") in ${ctx.file}.`
1217
+ );
1218
+ }
1219
+ return { op: "append-row", target };
1220
+ }
1221
+ const target = resolveTarget(add[1]);
1222
+ const value = parseActionLiteral(rhs, ctx);
1223
+ if (Array.isArray(ctx.comp.state.get(target))) return { op: "append", target, value };
1224
+ if (typeof value === "number") return { op: "add", target, value };
1225
+ throw new Error(
1226
+ `Unsupported button action "${raw}" in ${ctx.file}. += with non-number values requires a list state target — declare it "${add[1]} = []".`
1227
+ );
1228
+ }
1229
+ // `flag toggle` (no operand) → boolean flip; `list toggle v` → member-toggle.
1230
+ const toggle = expression.match(new RegExp(`^(${PATH})\\s+toggle(?:\\s+(.+))?$`));
1231
+ if (toggle) {
1232
+ const target = resolveTarget(toggle[1]);
1233
+ if (toggle[2] === undefined) return { op: "toggle", target };
1234
+ return { op: "member-toggle", target, value: parseActionLiteral(toggle[2], ctx) };
1235
+ }
1236
+ const prepend = expression.match(new RegExp(`^(${PATH})\\s+(?:append|prepend)\\s+(.+)$`));
1237
+ if (prepend) {
1238
+ const op = expression.includes(" prepend ") ? "prepend" : "append";
1239
+ return { op, target: resolveTarget(prepend[1]), value: parseActionLiteral(prepend[2], ctx) };
1240
+ }
1241
+ // Per-row: remove the current row from the list being looped — `todos remove todo`.
1242
+ // Disambiguation: operand IS the loop item name → `remove` (current row);
1243
+ // otherwise the operand is a value → `remove-value`.
1244
+ const remove = expression.match(new RegExp(`^(${PATH})\\s+remove\\s+(.+)$`));
1245
+ if (remove) {
1246
+ const operand = remove[2].trim();
1247
+ if (ctx.loopItem && operand === ctx.loopItem) {
1248
+ // A nested (item-relative) loop has a loop item but no top-level state key —
1249
+ // its source is a path off the outer row, which the runtime's row-remove
1250
+ // can't target. Fail loud with the honest workaround.
1251
+ if (!ctx.loopKey) {
1252
+ throw new Error(
1253
+ `Button action "${raw}" can't delete a row of a nested (item-relative) loop in ${ctx.file}. Per-row "remove" needs a top-level :state/:store list; carry the row into one (cart += ${ctx.loopItem}) and remove it there.`
1254
+ );
1255
+ }
1256
+ if (resolveStateKey(remove[1], ctx) !== ctx.loopKey) {
1257
+ throw new Error(
1258
+ `Button action "${raw}" must target the :state list being looped (@loop ${remove[1]} into ${ctx.loopItem}) in ${ctx.file}.`
1259
+ );
1260
+ }
1261
+ return { op: "remove", target: ctx.loopKey };
1262
+ }
1263
+ return {
1264
+ op: "remove-value",
1265
+ target: resolveTarget(remove[1]),
1266
+ value: parseActionLiteral(operand, ctx)
1267
+ };
1268
+ }
1269
+ const clear = expression.match(new RegExp(`^(${PATH})\\s+clear$`));
1270
+ if (clear) return { op: "clear", target: resolveTarget(clear[1]) };
1271
+ const merge = expression.match(new RegExp(`^(${PATH})\\s+merge\\s+(.+)$`));
1272
+ if (merge)
1273
+ return {
1274
+ op: "merge",
1275
+ target: resolveTarget(merge[1]),
1276
+ value: parseMergeOperand(merge[2], ctx)
1277
+ };
1278
+ const del = expression.match(new RegExp(`^(${PATH})\\s+delete\\s+(.+)$`));
1279
+ if (del)
1280
+ return { op: "delete", target: resolveTarget(del[1]), value: parseActionLiteral(del[2], ctx) };
1281
+ const reset = expression.match(new RegExp(`^(${PATH})\\s+reset$`));
1282
+ if (reset) return { op: "reset", target: resolveTarget(reset[1]) };
1283
+ // `name refetch` re-invokes the matching :fetch node. The target is the fetch
1284
+ // key (bare name); the runtime finds the [data-wd-fetch-key] node and re-runs.
1285
+ const refetch = expression.match(new RegExp(`^(${PATH})\\s+refetch$`));
1286
+ if (refetch) return { op: "refetch", target: resolveTarget(refetch[1]) };
1287
+ const assign = expression.match(new RegExp(`^(${PATH})\\s*=\\s*(.+)$`));
1288
+ if (assign)
1289
+ return {
1290
+ op: "set",
1291
+ target: resolveTarget(assign[1]),
1292
+ value: parseActionLiteral(assign[2], ctx)
1293
+ };
1294
+ throw new Error(`Unsupported button action "${raw}" in ${ctx.file}. ${ACTION_USE}`);
1295
+ }
1296
+
1297
+ /**
1298
+ * `merge` operand: either an inline JSON object literal, or a state/store key
1299
+ * name (emitted as a string the runtime resolves via getPath).
1300
+ * @param {string} raw
1301
+ * @param {Ctx} ctx
1302
+ * @returns {unknown}
1303
+ */
1304
+ function parseMergeOperand(raw, ctx) {
1305
+ const value = raw.trim();
1306
+ if (/^[A-Za-z_$][\w$]*$/.test(value)) {
1307
+ const key = resolveStateKey(value, ctx);
1308
+ if (!key)
1309
+ throw new Error(
1310
+ `Button action merge targets unknown state "${value}" in ${ctx.file}. Declare it first with :state ${value} = ...`
1311
+ );
1312
+ return key;
1313
+ }
1314
+ const parsed = parseActionLiteral(value, ctx);
1315
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1316
+ throw new Error(
1317
+ `Unsupported merge operand "${raw}" in ${ctx.file}. Use: obj merge other (a state key or an inline {…} object).`
1318
+ );
1319
+ }
1320
+
1321
+ /**
1322
+ * @param {string} raw
1323
+ * @param {Ctx} ctx
1324
+ * @returns {unknown}
1325
+ */
1326
+ function parseActionLiteral(raw, ctx) {
1327
+ const value = raw.trim();
1328
+ if (/^["'].*["']$/.test(value)) return stripQuotes(value);
1329
+ if (value === "true") return true;
1330
+ if (value === "false") return false;
1331
+ if (value === "null") return null;
1332
+ if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
1333
+ if (/^[[{]/.test(value)) {
1334
+ try {
1335
+ return JSON.parse(value);
1336
+ } catch {
1337
+ throw new Error(
1338
+ `Unsupported action literal "${raw}" in ${ctx.file}. Use: a quoted string, number, boolean, null, or valid JSON.`
1339
+ );
1340
+ }
1341
+ }
1342
+ throw new Error(
1343
+ `Unsupported action literal "${raw}" in ${ctx.file}. Use: a quoted string, number, boolean, null, or valid JSON.`
1344
+ );
1345
+ }