@torpor/view 1.2.6 → 1.3.1
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/dist/{Effect-DazmAdyC.d.mts → Effect-99HYQdzZ.d.mts} +50 -33
- package/dist/Effect-99HYQdzZ.d.mts.map +1 -0
- package/dist/{Effect-Dewn7MLc.d.cts → Effect-Bf8fz_zC.d.cts} +50 -33
- package/dist/Effect-Bf8fz_zC.d.cts.map +1 -0
- package/dist/compile.cjs +1510 -122
- package/dist/compile.d.cts +268 -1
- package/dist/compile.d.cts.map +1 -1
- package/dist/compile.d.mts +268 -1
- package/dist/compile.d.mts.map +1 -1
- package/dist/compile.mjs +1507 -123
- package/dist/compile.mjs.map +1 -1
- package/dist/dev.d.cts +1 -1
- package/dist/dev.d.mts +1 -1
- package/dist/{fromWebSocket-DrN-IduP.cjs → fromWebSocket-Cdoghvmh.cjs} +15 -0
- package/dist/{fromWebSocket-CFGoMkV2.mjs → fromWebSocket-ERhd9KZR.mjs} +11 -2
- package/dist/fromWebSocket-ERhd9KZR.mjs.map +1 -0
- package/dist/index.cjs +266 -105
- package/dist/index.d.cts +54 -12
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +54 -12
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +266 -105
- package/dist/index.mjs.map +1 -1
- package/dist/runtime.iife.js +1 -0
- package/dist/slotAutoClose-BbKfzpkz.cjs +177 -0
- package/dist/slotAutoClose-CgDkf8fM.mjs +156 -0
- package/dist/slotAutoClose-CgDkf8fM.mjs.map +1 -0
- package/dist/ssr.cjs +29 -1
- package/dist/ssr.d.cts +32 -1
- package/dist/ssr.d.cts.map +1 -1
- package/dist/ssr.d.mts +32 -1
- package/dist/ssr.d.mts.map +1 -1
- package/dist/ssr.mjs +25 -2
- package/dist/ssr.mjs.map +1 -1
- package/package.json +8 -5
- package/dist/Effect-DazmAdyC.d.mts.map +0 -1
- package/dist/Effect-Dewn7MLc.d.cts.map +0 -1
- package/dist/fromWebSocket-CFGoMkV2.mjs.map +0 -1
package/dist/compile.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { n as autoCloseMessage, r as closesAncestor, t as AUTO_CLOSEABLE } from "./slotAutoClose-CgDkf8fM.mjs";
|
|
1
2
|
//#region src/compile/utils/endOfString.ts
|
|
2
3
|
function endOfString(char, content, start) {
|
|
3
4
|
for (let j = start + 1; j < content.length; j++) if (content[j] === char && content[j - 1] !== "\\") return j;
|
|
@@ -348,6 +349,114 @@ function nodeRendersComponent(node) {
|
|
|
348
349
|
return false;
|
|
349
350
|
}
|
|
350
351
|
//#endregion
|
|
352
|
+
//#region src/compile/utils/stalePropLets.ts
|
|
353
|
+
/**
|
|
354
|
+
* Detects the "plain `let` initialized from `$props`, read from markup"
|
|
355
|
+
* stale-capture trap. A component instantiated from a keyed `@for` stays
|
|
356
|
+
* alive across list mutations while its props are updated in place — reads
|
|
357
|
+
* of `$props.x` in template expressions track correctly, but a plain `let x =
|
|
358
|
+
* ...$props.y...` is evaluated once at setup, so template effects reading
|
|
359
|
+
* `x` never re-run and silently keep the previous row's values.
|
|
360
|
+
*
|
|
361
|
+
* Detection is best-effort and syntactic: top-level `let` declarations in the
|
|
362
|
+
* component script whose initializer (up to the first `;` or newline) mentions
|
|
363
|
+
* `$props`, and whose name then appears in a markup expression. Deliberately a
|
|
364
|
+
* warning, not an error — capturing a prop value once is sometimes intended,
|
|
365
|
+
* and destructured/renamed forms (`let { x } = $props`) aren't detected.
|
|
366
|
+
*/
|
|
367
|
+
function stalePropLets(segments, markup, source) {
|
|
368
|
+
let script = "";
|
|
369
|
+
const deltas = [];
|
|
370
|
+
for (const segment of segments) {
|
|
371
|
+
deltas.push({
|
|
372
|
+
localStart: script.length,
|
|
373
|
+
delta: segment.fileStart
|
|
374
|
+
});
|
|
375
|
+
script += segment.text;
|
|
376
|
+
}
|
|
377
|
+
const toFileOffset = (local) => {
|
|
378
|
+
let delta = deltas[0].delta;
|
|
379
|
+
for (const entry of deltas) if (entry.localStart <= local) delta = entry.delta - entry.localStart;
|
|
380
|
+
else break;
|
|
381
|
+
return local + delta;
|
|
382
|
+
};
|
|
383
|
+
const names = [];
|
|
384
|
+
const LET = /^let[\s\n]/;
|
|
385
|
+
for (let i = 0; i < script.length; i++) {
|
|
386
|
+
const char = script[i];
|
|
387
|
+
if (char === "'" || char === "\"" || char === "`" || char === "/") {
|
|
388
|
+
const skipped = skipStringOrComment(script, i);
|
|
389
|
+
if (skipped !== -1) {
|
|
390
|
+
i = skipped - 1;
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (!LET.test(script.slice(i, i + 4))) continue;
|
|
395
|
+
if (i > 0 && /[\w$]/.test(script[i - 1])) continue;
|
|
396
|
+
let j = i + 3;
|
|
397
|
+
while (/\s/.test(script[j] ?? "")) j++;
|
|
398
|
+
let name = "";
|
|
399
|
+
while (/[\w$]/.test(script[j] ?? "")) {
|
|
400
|
+
name += script[j];
|
|
401
|
+
j++;
|
|
402
|
+
}
|
|
403
|
+
if (!name) continue;
|
|
404
|
+
while (/\s/.test(script[j] ?? "")) j++;
|
|
405
|
+
if (script[j] === ":") {
|
|
406
|
+
j++;
|
|
407
|
+
while (script[j] !== void 0 && script[j] !== "=" && script[j] !== "\n") j++;
|
|
408
|
+
}
|
|
409
|
+
while (/\s/.test(script[j] ?? "")) j++;
|
|
410
|
+
if (script[j] !== "=" || script[j + 1] === "=") continue;
|
|
411
|
+
j++;
|
|
412
|
+
let init = "";
|
|
413
|
+
while (j < script.length && script[j] !== ";" && script[j] !== "\n") {
|
|
414
|
+
if (script[j] === "'" || script[j] === "\"" || script[j] === "`") {
|
|
415
|
+
const skipped = skipStringOrComment(script, j);
|
|
416
|
+
if (skipped !== -1) {
|
|
417
|
+
init += script.slice(j, skipped);
|
|
418
|
+
j = skipped;
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
init += script[j];
|
|
423
|
+
j++;
|
|
424
|
+
}
|
|
425
|
+
if (/\$props\b/.test(init)) names.push({
|
|
426
|
+
name,
|
|
427
|
+
local: i
|
|
428
|
+
});
|
|
429
|
+
i = j;
|
|
430
|
+
}
|
|
431
|
+
if (names.length === 0 || !markup) return [];
|
|
432
|
+
const expressions = collectMarkupExpressions(markup);
|
|
433
|
+
if (!expressions) return [];
|
|
434
|
+
const warnings = [];
|
|
435
|
+
for (const { name, local } of names) {
|
|
436
|
+
const escaped = name.replace(/\$/g, "\\$");
|
|
437
|
+
if (!new RegExp(`(^|[^\\w$])${escaped}([^\\w$]|$)`).test(expressions)) continue;
|
|
438
|
+
const absolute = toFileOffset(local);
|
|
439
|
+
let startLine = 0;
|
|
440
|
+
let lastLineStart = 0;
|
|
441
|
+
if (source !== void 0) {
|
|
442
|
+
for (let i = 0; i < absolute && i < source.length; i++) if (source[i] === "\n") {
|
|
443
|
+
startLine += 1;
|
|
444
|
+
lastLineStart = i + 1;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
warnings.push({
|
|
448
|
+
message: `'${name}' is a plain let initialized from $props. Its value is captured once at setup, so template expressions reading it won't update when the component's props change (keyed lists keep components alive and update props in place). Use a getter or $cache if it should stay live.`,
|
|
449
|
+
startIndex: absolute,
|
|
450
|
+
startLine,
|
|
451
|
+
startChar: absolute - lastLineStart,
|
|
452
|
+
endIndex: absolute,
|
|
453
|
+
endLine: startLine,
|
|
454
|
+
endChar: absolute - lastLineStart
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
return warnings;
|
|
458
|
+
}
|
|
459
|
+
//#endregion
|
|
351
460
|
//#region src/compile/build/client/addMappedText.ts
|
|
352
461
|
function addMappedText(preText, text, postText, span, status, b) {
|
|
353
462
|
if (status.options.mapped === true) {
|
|
@@ -717,6 +826,59 @@ function bindingTarget(value, right, name, imports) {
|
|
|
717
826
|
return `const t_bind_${varSuffix} = ${right};\nconst t_target_${varSuffix} = $peek(() => ${guard});\nif (t_target_${varSuffix} != null) t_target_${varSuffix}${suffix} = t_bind_${varSuffix};`;
|
|
718
827
|
}
|
|
719
828
|
//#endregion
|
|
829
|
+
//#region src/compile/utils/getContextUsage.ts
|
|
830
|
+
/**
|
|
831
|
+
* Gets the `$context` names that the compiled output references. The input is
|
|
832
|
+
* code-only text (a component's script plus markup expressions, or a slot
|
|
833
|
+
* fill's collected expressions), with `ranges` marking the positions that are
|
|
834
|
+
* code — matches that start inside a string, comment or regex literal are
|
|
835
|
+
* ignored, so mentions inside sample-code strings don't count.
|
|
836
|
+
*/
|
|
837
|
+
function getContextUsage(source, ranges) {
|
|
838
|
+
const contextsMatches = source.matchAll(/\$context\??\s*(?:\.([\d\w]+)|\[([^\]]+)\])/g);
|
|
839
|
+
const contexts = [];
|
|
840
|
+
for (let match of contextsMatches) {
|
|
841
|
+
if (!isInCode(ranges, match.index)) continue;
|
|
842
|
+
const name = trimQuotes(match[1] || match[2]);
|
|
843
|
+
if (!contexts.includes(name)) contexts.push(name);
|
|
844
|
+
}
|
|
845
|
+
if (!contexts.length) for (let match of source.matchAll(/(?<![\w$])\$context(?![\w])(?!\s*:)(?!<)/g)) {
|
|
846
|
+
if (!isInCode(ranges, match.index)) continue;
|
|
847
|
+
contexts.push("$context");
|
|
848
|
+
break;
|
|
849
|
+
}
|
|
850
|
+
return contexts.length ? contexts : void 0;
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* Returns true if `index` falls inside one of the (sorted, non-overlapping)
|
|
854
|
+
* code ranges — i.e. not inside a string, comment or regex literal.
|
|
855
|
+
*/
|
|
856
|
+
function isInCode(ranges, index) {
|
|
857
|
+
for (const [start, end] of ranges) {
|
|
858
|
+
if (index >= start && index < end) return true;
|
|
859
|
+
if (index < start) return false;
|
|
860
|
+
}
|
|
861
|
+
return false;
|
|
862
|
+
}
|
|
863
|
+
//#endregion
|
|
864
|
+
//#region src/compile/utils/fillUsesContext.ts
|
|
865
|
+
/**
|
|
866
|
+
* Returns true if a slot fill's content uses the `$context` parameter that
|
|
867
|
+
* the generated fill function declares: rendering a child component or slot
|
|
868
|
+
* forwards `$context` positionally (see buildComponentNode / buildSlotNode
|
|
869
|
+
* and their server counterparts), and a direct `$context` read in one of the
|
|
870
|
+
* fill's own expressions (interpolation, reactive attribute, event handler,
|
|
871
|
+
* control statement) reads it.
|
|
872
|
+
*
|
|
873
|
+
* Bias is towards `true`: when uncertain we keep `$context` named, which is
|
|
874
|
+
* always safe at the cost of a missed unused-parameter cleanup.
|
|
875
|
+
*/
|
|
876
|
+
function fillUsesContext(fill) {
|
|
877
|
+
if (markupRendersComponent({ children: fill.children ?? [] })) return true;
|
|
878
|
+
const expressions = collectMarkupExpressions(fill);
|
|
879
|
+
return getContextUsage(expressions, codeRanges(expressions)) !== void 0;
|
|
880
|
+
}
|
|
881
|
+
//#endregion
|
|
720
882
|
//#region src/compile/utils/isSpecialNode.ts
|
|
721
883
|
function isSpecialNode(node) {
|
|
722
884
|
return node.type === "special";
|
|
@@ -1282,23 +1444,52 @@ function getFragmentVarPath(fragment, status, name, path, varPaths) {
|
|
|
1282
1444
|
varPaths.set(varPath, name);
|
|
1283
1445
|
varPaths.set(name, name);
|
|
1284
1446
|
}
|
|
1285
|
-
while (
|
|
1447
|
+
while (/(?:t_next_text\(|t_next\(){2,}/.test(varPath)) {
|
|
1286
1448
|
status.imports.add("t_skip");
|
|
1287
|
-
const
|
|
1288
|
-
const
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1449
|
+
const runStart = /(?:t_next_text\(|t_next\(){2,}/.exec(varPath).index;
|
|
1450
|
+
const openings = [];
|
|
1451
|
+
let j = runStart;
|
|
1452
|
+
for (;;) {
|
|
1453
|
+
const open = /^(t_next_text|t_next)\(/.exec(varPath.slice(j));
|
|
1454
|
+
if (!open) break;
|
|
1455
|
+
openings.push({
|
|
1456
|
+
text: open[1] === "t_next_text",
|
|
1457
|
+
openEnd: j + open[0].length
|
|
1458
|
+
});
|
|
1459
|
+
j += open[0].length;
|
|
1460
|
+
}
|
|
1461
|
+
if (openings.length < 2) break;
|
|
1462
|
+
const count = openings.length;
|
|
1463
|
+
const innermostOpenEnd = openings[openings.length - 1].openEnd;
|
|
1464
|
+
let innerDepth = 0;
|
|
1465
|
+
let innermostClose = -1;
|
|
1466
|
+
for (let k = innermostOpenEnd; k < varPath.length; k++) if (varPath[k] === "(") innerDepth++;
|
|
1467
|
+
else if (varPath[k] === ")") {
|
|
1468
|
+
if (innerDepth === 0) {
|
|
1469
|
+
innermostClose = k;
|
|
1470
|
+
break;
|
|
1471
|
+
}
|
|
1472
|
+
innerDepth--;
|
|
1473
|
+
}
|
|
1474
|
+
if (innermostClose === -1) break;
|
|
1475
|
+
let outerDepth = 1;
|
|
1476
|
+
let outerClose = -1;
|
|
1477
|
+
for (let k = openings[0].openEnd; k < varPath.length; k++) if (varPath[k] === "(") outerDepth++;
|
|
1478
|
+
else if (varPath[k] === ")") {
|
|
1479
|
+
outerDepth--;
|
|
1480
|
+
if (outerDepth === 0) {
|
|
1481
|
+
outerClose = k;
|
|
1297
1482
|
break;
|
|
1298
|
-
}
|
|
1483
|
+
}
|
|
1299
1484
|
}
|
|
1300
|
-
|
|
1301
|
-
|
|
1485
|
+
if (outerClose === -1) break;
|
|
1486
|
+
let mask = 0;
|
|
1487
|
+
for (let k = 0; k < count; k++) if (openings[k].text) mask |= 1 << count - 1 - k;
|
|
1488
|
+
let param = varPath.substring(innermostOpenEnd, innermostClose);
|
|
1489
|
+
if (openings[openings.length - 1].text && param.endsWith(", true")) param = param.slice(0, -6);
|
|
1490
|
+
const head = varPath.substring(0, runStart);
|
|
1491
|
+
const tail = varPath.substring(outerClose + 1);
|
|
1492
|
+
varPath = `${head}t_skip(${param}, ${count}${mask ? `, ${mask}` : ""})${tail}`;
|
|
1302
1493
|
}
|
|
1303
1494
|
varPath = varPath.replaceAll("t_next_text", "t_next");
|
|
1304
1495
|
return varPath;
|
|
@@ -1544,7 +1735,7 @@ function buildComponentNode(node, status, b, root = false) {
|
|
|
1544
1735
|
"$sparent: ParentNode",
|
|
1545
1736
|
"$sanchor: Node | null",
|
|
1546
1737
|
slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>",
|
|
1547
|
-
"$context?: Record<PropertyKey, any>"
|
|
1738
|
+
fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"
|
|
1548
1739
|
];
|
|
1549
1740
|
b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = (\n${slotParams.join(",\n")}\n) => {`);
|
|
1550
1741
|
buildFragment(slot, status, b, "$sparent", "$sanchor");
|
|
@@ -1674,6 +1865,44 @@ function isForBodyLeafSafe(forBodyChildren) {
|
|
|
1674
1865
|
return !hasNestedControl(forBodyChildren);
|
|
1675
1866
|
}
|
|
1676
1867
|
//#endregion
|
|
1868
|
+
//#region src/compile/utils/forLoopVarNames.ts
|
|
1869
|
+
/**
|
|
1870
|
+
* Extracts the declared loop variable names from a `@for` statement — the
|
|
1871
|
+
* heuristic header parse shared by `buildForNode` (codegen) and the write
|
|
1872
|
+
* scanners (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect
|
|
1873
|
+
* nested loops that shadow an outer loop's variables).
|
|
1874
|
+
*
|
|
1875
|
+
* Handles the C-style (`for (let i = 0; i < n; i++)`), for-of and for-in
|
|
1876
|
+
* forms, with destructuring flattened to the bare names. TODO: Handle
|
|
1877
|
+
* destructuring, quotes, comments etc (same as buildForNode's note — this is
|
|
1878
|
+
* deliberately the same heuristic).
|
|
1879
|
+
*/
|
|
1880
|
+
function forLoopVarNames(statement) {
|
|
1881
|
+
const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
|
|
1882
|
+
const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
|
|
1883
|
+
const forOfRegex = /for\s*\(\s*(?:let\s*|var\s*){0,1}(.+?)\s+(?:of|in).*?\)/;
|
|
1884
|
+
const trimMatched = (value, start, end) => {
|
|
1885
|
+
const startIndex = value.indexOf(start);
|
|
1886
|
+
const endIndex = value.lastIndexOf(end);
|
|
1887
|
+
if (startIndex === -1 || endIndex === -1) return value;
|
|
1888
|
+
return value.slice(startIndex + 1, endIndex);
|
|
1889
|
+
};
|
|
1890
|
+
const names = [];
|
|
1891
|
+
const forLoopMatch = statement.match(forLoopRegex);
|
|
1892
|
+
if (forLoopMatch) {
|
|
1893
|
+
const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
|
|
1894
|
+
for (const match of forVarMatches) names.push(match[1]);
|
|
1895
|
+
return names;
|
|
1896
|
+
}
|
|
1897
|
+
const forOfMatch = statement.match(forOfRegex);
|
|
1898
|
+
if (forOfMatch) {
|
|
1899
|
+
const match = forOfMatch[1];
|
|
1900
|
+
if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) names.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
|
|
1901
|
+
else names.push(match);
|
|
1902
|
+
}
|
|
1903
|
+
return names;
|
|
1904
|
+
}
|
|
1905
|
+
//#endregion
|
|
1677
1906
|
//#region src/compile/utils/forVarsWrittenIn.ts
|
|
1678
1907
|
/**
|
|
1679
1908
|
* Returns the set of `forVars` that are written anywhere in `children`,
|
|
@@ -1705,13 +1934,16 @@ function scan(children, forVars, bareWritePattern) {
|
|
|
1705
1934
|
const found = /* @__PURE__ */ new Set();
|
|
1706
1935
|
if (forVars.length === 0) return found;
|
|
1707
1936
|
const collected = [];
|
|
1708
|
-
for (const child of children) collectExpressionStrings(child, collected);
|
|
1937
|
+
for (const child of children) collectExpressionStrings(child, collected, /* @__PURE__ */ new Set());
|
|
1709
1938
|
for (const varName of forVars) {
|
|
1710
1939
|
const escaped = varName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1711
1940
|
const writePattern = new RegExp(`(?<![\\w$.\\])\\)])\\[\\s*${escaped}\\s*\\]\\s*=(?![=>])|(?<![\\w$.\\])\\)])\\{\\s*${escaped}\\s*(:[^}]+)?\\}\\s*=(?![=>])|` + bareWritePattern(escaped) + `|(?<![\\w$.])(?:\\+\\+|--)\\s*${escaped}(?![\\w$])`);
|
|
1712
|
-
for (const
|
|
1713
|
-
|
|
1714
|
-
|
|
1941
|
+
for (const entry of collected) {
|
|
1942
|
+
if (entry.shadows.has(varName)) continue;
|
|
1943
|
+
if (writePattern.test(entry.text)) {
|
|
1944
|
+
found.add(varName);
|
|
1945
|
+
break;
|
|
1946
|
+
}
|
|
1715
1947
|
}
|
|
1716
1948
|
}
|
|
1717
1949
|
return found;
|
|
@@ -1723,26 +1955,53 @@ function isElementLike(node) {
|
|
|
1723
1955
|
* Collects every expression-like string from the body, including attribute
|
|
1724
1956
|
* values (with `&`-binding targets marked by a trailing `=`), text
|
|
1725
1957
|
* interpolations, and control statements (recursing into nested controls).
|
|
1958
|
+
*
|
|
1959
|
+
* Nested `@for` loops are special: their own statement is skipped entirely
|
|
1960
|
+
* (its declarations and init/update expressions belong to the inner loop's
|
|
1961
|
+
* variables — a C-style header's `i++` is the inner loop's own bookkeeping,
|
|
1962
|
+
* not a write of an outer loop's variable), and every string beneath it is
|
|
1963
|
+
* recorded with the inner loop's variable names as shadowing it.
|
|
1726
1964
|
*/
|
|
1727
|
-
function collectExpressionStrings(node, out) {
|
|
1965
|
+
function collectExpressionStrings(node, out, shadows) {
|
|
1728
1966
|
if (isTextNode(node)) {
|
|
1729
|
-
out.push(
|
|
1967
|
+
out.push({
|
|
1968
|
+
text: node.content,
|
|
1969
|
+
shadows
|
|
1970
|
+
});
|
|
1730
1971
|
return;
|
|
1731
1972
|
}
|
|
1732
1973
|
if (isElementLike(node)) {
|
|
1733
1974
|
for (const attr of node.attributes) {
|
|
1734
1975
|
if (attr.value !== void 0) {
|
|
1735
|
-
if (attr.name.startsWith("&")) out.push(
|
|
1736
|
-
|
|
1976
|
+
if (attr.name.startsWith("&")) out.push({
|
|
1977
|
+
text: `${attr.value} =`,
|
|
1978
|
+
shadows
|
|
1979
|
+
});
|
|
1980
|
+
else out.push({
|
|
1981
|
+
text: attr.value,
|
|
1982
|
+
shadows
|
|
1983
|
+
});
|
|
1737
1984
|
}
|
|
1738
|
-
if (attr.fullyReactive && attr.name !== attr.value) out.push(
|
|
1985
|
+
if (attr.fullyReactive && attr.name !== attr.value) out.push({
|
|
1986
|
+
text: attr.name,
|
|
1987
|
+
shadows
|
|
1988
|
+
});
|
|
1739
1989
|
}
|
|
1740
|
-
for (const child of node.children) collectExpressionStrings(child, out);
|
|
1990
|
+
for (const child of node.children) collectExpressionStrings(child, out, shadows);
|
|
1741
1991
|
return;
|
|
1742
1992
|
}
|
|
1743
1993
|
if (isControlNode(node)) {
|
|
1744
|
-
|
|
1745
|
-
|
|
1994
|
+
if (node.operation === "@for") {
|
|
1995
|
+
const nested = new Set(shadows);
|
|
1996
|
+
for (const name of forLoopVarNames(node.statement)) nested.add(name);
|
|
1997
|
+
for (const child of node.children) collectExpressionStrings(child, out, nested);
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
out.push({
|
|
2001
|
+
text: node.statement,
|
|
2002
|
+
shadows
|
|
2003
|
+
});
|
|
2004
|
+
for (const child of node.children) collectExpressionStrings(child, out, shadows);
|
|
1746
2005
|
}
|
|
1747
2006
|
}
|
|
1748
2007
|
//#endregion
|
|
@@ -1833,24 +2092,6 @@ function collectDirect(nodes, out) {
|
|
|
1833
2092
|
}
|
|
1834
2093
|
}
|
|
1835
2094
|
//#endregion
|
|
1836
|
-
//#region src/compile/utils/trimMatched.ts
|
|
1837
|
-
/**
|
|
1838
|
-
* Trims chars from the start and end of the supplied text when both the start and end match
|
|
1839
|
-
*
|
|
1840
|
-
* @param text The text to trim
|
|
1841
|
-
*
|
|
1842
|
-
* @returns The text without the chars at the start or the end
|
|
1843
|
-
*/
|
|
1844
|
-
function trimMatched(text, startChar, endChar) {
|
|
1845
|
-
let start = 0;
|
|
1846
|
-
let end = text.length;
|
|
1847
|
-
while (text[start] === startChar && text[end - 1] === endChar) {
|
|
1848
|
-
start += 1;
|
|
1849
|
-
end -= 1;
|
|
1850
|
-
}
|
|
1851
|
-
return text.substring(start, end);
|
|
1852
|
-
}
|
|
1853
|
-
//#endregion
|
|
1854
2095
|
//#region src/compile/build/client/addBuildError.ts
|
|
1855
2096
|
/**
|
|
1856
2097
|
* Adds an error to the build status. Mirrors `parse/utils/addError`, but is
|
|
@@ -1889,26 +2130,11 @@ function addBuildError(status, message, start, end = start) {
|
|
|
1889
2130
|
}
|
|
1890
2131
|
//#endregion
|
|
1891
2132
|
//#region src/compile/build/client/buildForNode.ts
|
|
1892
|
-
const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
|
|
1893
|
-
const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
|
|
1894
|
-
const forOfRegex = /for\s*\(\s*(?:let\s*|var\s*){0,1}(.+?)\s+(?:of|in).*?\)/;
|
|
1895
2133
|
function buildForNode(node, status, b) {
|
|
1896
2134
|
const parentName = node.parentName;
|
|
1897
2135
|
const anchorName = node.varName ?? "null";
|
|
1898
2136
|
node = node.children[0];
|
|
1899
|
-
const forVarNames =
|
|
1900
|
-
const forLoopMatch = node.statement.match(forLoopRegex);
|
|
1901
|
-
if (forLoopMatch) {
|
|
1902
|
-
const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
|
|
1903
|
-
for (let match of forVarMatches) forVarNames.push(match[1]);
|
|
1904
|
-
} else {
|
|
1905
|
-
const forOfMatch = node.statement.match(forOfRegex);
|
|
1906
|
-
if (forOfMatch) {
|
|
1907
|
-
const match = forOfMatch[1];
|
|
1908
|
-
if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) forVarNames.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
|
|
1909
|
-
else forVarNames.push(match);
|
|
1910
|
-
}
|
|
1911
|
-
}
|
|
2137
|
+
const forVarNames = forLoopVarNames(node.statement);
|
|
1912
2138
|
const regionName = nextVarName("for_region", status);
|
|
1913
2139
|
const listItemsName = nextVarName("new_items", status);
|
|
1914
2140
|
const itemName = nextVarName("item", status);
|
|
@@ -2085,7 +2311,6 @@ function buildIfNode(node, status, b) {
|
|
|
2085
2311
|
status.imports.add("t_region");
|
|
2086
2312
|
status.imports.add("t_run_control");
|
|
2087
2313
|
status.imports.add("t_run_branch");
|
|
2088
|
-
status.imports.add("t_push_region");
|
|
2089
2314
|
status.imports.add("t_pop_region");
|
|
2090
2315
|
b.append("");
|
|
2091
2316
|
b.append("/* @if */");
|
|
@@ -2103,12 +2328,9 @@ function buildIfNode(node, status, b) {
|
|
|
2103
2328
|
}
|
|
2104
2329
|
function buildIfBranch(node, status, b, parentName, regionName, indexName, index) {
|
|
2105
2330
|
addMappedText("", `${node.statement}`, " {", node.span, status, b);
|
|
2106
|
-
b.append(`
|
|
2331
|
+
b.append(`const t_old_region = t_run_branch(${regionName}, ${indexName}, ${index}${status.options.dev === true ? `, "if_branch"` : ""});`);
|
|
2332
|
+
b.append("if (t_old_region === null) return;");
|
|
2107
2333
|
if (node.children.length > 0) {
|
|
2108
|
-
b.append(`
|
|
2109
|
-
const t_new_region = t_region(${status.options.dev === true ? `"if_branch"` : ""});
|
|
2110
|
-
const t_old_region = t_push_region(t_new_region, true);
|
|
2111
|
-
`);
|
|
2112
2334
|
buildFragment(node, status, b, parentName, "t_before");
|
|
2113
2335
|
status.fragmentStack.push({
|
|
2114
2336
|
fragment: node.fragment,
|
|
@@ -2117,8 +2339,8 @@ function buildIfBranch(node, status, b, parentName, regionName, indexName, index
|
|
|
2117
2339
|
for (let child of node.children) buildNode(child, status, b, parentName, "t_before");
|
|
2118
2340
|
status.fragmentStack.pop();
|
|
2119
2341
|
buildAddFragment(node, status, b, parentName, "t_before");
|
|
2120
|
-
b.append("t_pop_region(t_old_region);");
|
|
2121
2342
|
}
|
|
2343
|
+
b.append("t_pop_region(t_old_region);");
|
|
2122
2344
|
b.append(`${indexName} = ${index};`);
|
|
2123
2345
|
b.append("}");
|
|
2124
2346
|
}
|
|
@@ -2132,7 +2354,6 @@ function buildReplaceNode(node, status, b) {
|
|
|
2132
2354
|
status.imports.add("t_region");
|
|
2133
2355
|
status.imports.add("t_run_control");
|
|
2134
2356
|
status.imports.add("t_run_branch");
|
|
2135
|
-
status.imports.add("t_push_region");
|
|
2136
2357
|
status.imports.add("t_pop_region");
|
|
2137
2358
|
b.append("");
|
|
2138
2359
|
b.append(`
|
|
@@ -2145,13 +2366,9 @@ function buildReplaceNode(node, status, b) {
|
|
|
2145
2366
|
b.append("");
|
|
2146
2367
|
}
|
|
2147
2368
|
function buildReplaceBranch(node, status, b, parentName, regionName) {
|
|
2148
|
-
status.imports.add("t_run_branch");
|
|
2149
2369
|
b.append(`${node.statement};`);
|
|
2150
|
-
b.append(`
|
|
2151
|
-
b.append(
|
|
2152
|
-
const t_new_region = t_region(${status.options.dev === true ? `"replace_branch"` : ""});
|
|
2153
|
-
const t_old_region = t_push_region(t_new_region, true);
|
|
2154
|
-
`);
|
|
2370
|
+
b.append(`const t_old_region = t_run_branch(${regionName}, 0, -1${status.options.dev === true ? `, "replace_branch"` : ""});`);
|
|
2371
|
+
b.append("if (t_old_region === null) return;");
|
|
2155
2372
|
buildFragment(node, status, b, parentName, "t_before");
|
|
2156
2373
|
status.fragmentStack.push({
|
|
2157
2374
|
fragment: node.fragment,
|
|
@@ -2195,7 +2412,6 @@ function buildSwitchNode(node, status, b) {
|
|
|
2195
2412
|
status.imports.add("t_region");
|
|
2196
2413
|
status.imports.add("t_run_control");
|
|
2197
2414
|
status.imports.add("t_run_branch");
|
|
2198
|
-
status.imports.add("t_push_region");
|
|
2199
2415
|
status.imports.add("t_pop_region");
|
|
2200
2416
|
b.append("");
|
|
2201
2417
|
b.append("/* @switch */");
|
|
@@ -2216,12 +2432,9 @@ function buildSwitchNode(node, status, b) {
|
|
|
2216
2432
|
}
|
|
2217
2433
|
function buildSwitchBranch(node, status, b, parentName, regionName, indexName, index) {
|
|
2218
2434
|
addMappedText("", `${node.statement}`, " {", node.span, status, b);
|
|
2219
|
-
b.append(`
|
|
2435
|
+
b.append(`const t_old_region = t_run_branch(${regionName}, ${indexName}, ${index}${status.options.dev === true ? `, "switch_branch"` : ""});`);
|
|
2436
|
+
b.append("if (t_old_region === null) return;");
|
|
2220
2437
|
if (node.children.length > 0) {
|
|
2221
|
-
b.append(`
|
|
2222
|
-
const t_new_region = t_region(${status.options.dev === true ? `"switch_branch"` : ""});
|
|
2223
|
-
const t_old_region = t_push_region(t_new_region, true);
|
|
2224
|
-
`);
|
|
2225
2438
|
buildFragment(node, status, b, parentName, "t_before");
|
|
2226
2439
|
status.fragmentStack.push({
|
|
2227
2440
|
fragment: node.fragment,
|
|
@@ -2230,14 +2443,32 @@ function buildSwitchBranch(node, status, b, parentName, regionName, indexName, i
|
|
|
2230
2443
|
for (let child of node.children) buildNode(child, status, b, parentName, "t_before");
|
|
2231
2444
|
status.fragmentStack.pop();
|
|
2232
2445
|
buildAddFragment(node, status, b, parentName, "t_before");
|
|
2233
|
-
b.append("t_pop_region(t_old_region);");
|
|
2234
2446
|
}
|
|
2447
|
+
b.append("t_pop_region(t_old_region);");
|
|
2235
2448
|
b.append(`
|
|
2236
2449
|
${indexName} = ${index};
|
|
2237
2450
|
break;
|
|
2238
2451
|
}`);
|
|
2239
2452
|
}
|
|
2240
2453
|
//#endregion
|
|
2454
|
+
//#region src/compile/utils/trimMatched.ts
|
|
2455
|
+
/**
|
|
2456
|
+
* Trims chars from the start and end of the supplied text when both the start and end match
|
|
2457
|
+
*
|
|
2458
|
+
* @param text The text to trim
|
|
2459
|
+
*
|
|
2460
|
+
* @returns The text without the chars at the start or the end
|
|
2461
|
+
*/
|
|
2462
|
+
function trimMatched(text, startChar, endChar) {
|
|
2463
|
+
let start = 0;
|
|
2464
|
+
let end = text.length;
|
|
2465
|
+
while (text[start] === startChar && text[end - 1] === endChar) {
|
|
2466
|
+
start += 1;
|
|
2467
|
+
end -= 1;
|
|
2468
|
+
}
|
|
2469
|
+
return text.substring(start, end);
|
|
2470
|
+
}
|
|
2471
|
+
//#endregion
|
|
2241
2472
|
//#region src/compile/build/client/buildTryNode.ts
|
|
2242
2473
|
function buildTryNode(node, status, b) {
|
|
2243
2474
|
const anchorName = node.varName ?? "null";
|
|
@@ -2903,11 +3134,11 @@ const importsMap$1 = {
|
|
|
2903
3134
|
t_push_dev_bound: "import { t_push_dev_bound } from \"${folder}/dev\";",
|
|
2904
3135
|
t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";"
|
|
2905
3136
|
};
|
|
2906
|
-
function buildCode(template, map, options, errors = []) {
|
|
3137
|
+
function buildCode(template, map, options, errors = [], warnings = []) {
|
|
2907
3138
|
let b = new Builder(options?.mapped);
|
|
2908
3139
|
let imports = /* @__PURE__ */ new Set();
|
|
2909
3140
|
imports.add("SlotRender");
|
|
2910
|
-
buildTemplate(template, map, imports, b, options, errors);
|
|
3141
|
+
buildTemplate(template, map, imports, b, options, errors, warnings);
|
|
2911
3142
|
let startSize = b.toString().length;
|
|
2912
3143
|
if (imports.size) {
|
|
2913
3144
|
const folder = options?.renderFolder ?? "@torpor/view";
|
|
@@ -2924,7 +3155,7 @@ function buildCode(template, map, options, errors = []) {
|
|
|
2924
3155
|
}
|
|
2925
3156
|
return b.toString();
|
|
2926
3157
|
}
|
|
2927
|
-
function buildTemplate(template, map, imports, b, options, errors = []) {
|
|
3158
|
+
function buildTemplate(template, map, imports, b, options, errors = [], warnings = []) {
|
|
2928
3159
|
let script = template.script.map((s) => s.script).join("\n");
|
|
2929
3160
|
for (const component of template.components) {
|
|
2930
3161
|
if (component.markup) script += "\n" + collectMarkupExpressions(component.markup);
|
|
@@ -2951,9 +3182,11 @@ function buildTemplate(template, map, imports, b, options, errors = []) {
|
|
|
2951
3182
|
let current = template.components[0];
|
|
2952
3183
|
let status = makeStatus(imports, map, current, options, errors);
|
|
2953
3184
|
let first = true;
|
|
3185
|
+
let componentScript = [];
|
|
2954
3186
|
for (let chunk of template.script) if (chunk.script === "/* @params */") {
|
|
2955
3187
|
if (!first) status = makeStatus(imports, map, current, options, errors);
|
|
2956
3188
|
first = false;
|
|
3189
|
+
componentScript = [];
|
|
2957
3190
|
b.append(`
|
|
2958
3191
|
${current.markup ? "$parent" : "_$parent"}: ParentNode,
|
|
2959
3192
|
${current.markup ? "$anchor" : "_$anchor"}: Node | null,`);
|
|
@@ -2999,10 +3232,17 @@ function buildTemplate(template, map, imports, b, options, errors = []) {
|
|
|
2999
3232
|
status.inHead = false;
|
|
3000
3233
|
}
|
|
3001
3234
|
} else if (chunk.script === "/* @style */") {} else if (chunk.script === "/* @end */") {
|
|
3235
|
+
if (current.markup && warnings !== void 0) warnings.push(...stalePropLets(componentScript, current.markup, options?.source));
|
|
3002
3236
|
addPopDevBoundary(status, b);
|
|
3003
3237
|
currentIndex += 1;
|
|
3004
3238
|
current = template.components[currentIndex];
|
|
3005
|
-
} else
|
|
3239
|
+
} else {
|
|
3240
|
+
addMappedText("", chunk.script, "", chunk.span, status, b);
|
|
3241
|
+
componentScript.push({
|
|
3242
|
+
text: chunk.script,
|
|
3243
|
+
fileStart: chunk.span.start
|
|
3244
|
+
});
|
|
3245
|
+
}
|
|
3006
3246
|
}
|
|
3007
3247
|
function makeStatus(imports, map, current, options, errors = []) {
|
|
3008
3248
|
return {
|
|
@@ -3142,7 +3382,7 @@ function buildServerComponentNode(node, status, b) {
|
|
|
3142
3382
|
for (let slot of node.children) if (isSpecialNode(slot) && (slot.tagName === "fill" || slot.tagName === "filldef")) {
|
|
3143
3383
|
const nameAttribute = slot.attributes.find((a) => a.name === "name");
|
|
3144
3384
|
const slotName = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
|
|
3145
|
-
const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", "$context?: Record<PropertyKey, any>"];
|
|
3385
|
+
const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
|
|
3146
3386
|
b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = async (\n${slotParams.join(",\n")}\n) => {`);
|
|
3147
3387
|
b.append(`let t_body = "";`);
|
|
3148
3388
|
for (let child of slot.children) buildServerNode(child, status, b);
|
|
@@ -3381,7 +3621,9 @@ function buildServerElementNode(node, status, b) {
|
|
|
3381
3621
|
if (!voidTags.includes(tagName)) {
|
|
3382
3622
|
const oldPreserveWhitespace = status.preserveWhitespace;
|
|
3383
3623
|
status.preserveWhitespace = ["pre", "code"].includes(tagName);
|
|
3624
|
+
if (!tagName.startsWith("@")) status.elementStack.push(tagName);
|
|
3384
3625
|
for (let child of node.children) buildServerNode(child, status, b);
|
|
3626
|
+
if (!tagName.startsWith("@")) status.elementStack.pop();
|
|
3385
3627
|
status.preserveWhitespace = oldPreserveWhitespace;
|
|
3386
3628
|
status.output += `</${tagName}>`;
|
|
3387
3629
|
}
|
|
@@ -3455,8 +3697,12 @@ function buildServerSlotNode(node, status, b) {
|
|
|
3455
3697
|
for (let { name, value } of slotAttributes) if (value != null) b.append(`${propsName}["${name}"] = ${value};`);
|
|
3456
3698
|
else b.append(`${propsName}["${name}"] = true;`);
|
|
3457
3699
|
}
|
|
3700
|
+
const closeTags = status.elementStack.filter((tag) => AUTO_CLOSEABLE.has(tag));
|
|
3458
3701
|
b.append(`if ($slots && $slots["${slotName}"]) {`);
|
|
3459
|
-
|
|
3702
|
+
if (closeTags.length > 0) {
|
|
3703
|
+
status.imports.add("t_slot_guard");
|
|
3704
|
+
b.append(`${status.inHead ? "t_head" : "t_body"} += t_slot_guard([${closeTags.map((tag) => `"${tag}"`).join(", ")}], await $slots["${slotName}"](${slotHasProps ? propsName : "undefined"}, $context), "${slotName}");`);
|
|
3705
|
+
} else b.append(`${status.inHead ? "t_head" : "t_body"} += await $slots["${slotName}"](${slotHasProps ? propsName : "undefined"}, $context);`);
|
|
3460
3706
|
const fill = node.children.find((c) => isSpecialNode(c) && (c.tagName === "fill" || c.tagName === "filldef"));
|
|
3461
3707
|
if (fill && isSpecialNode(fill) && fill.children.length) {
|
|
3462
3708
|
b.append(`} else {`);
|
|
@@ -3565,6 +3811,7 @@ const importsMap = {
|
|
|
3565
3811
|
t_attr: "import { t_attr } from \"${folder}\";",
|
|
3566
3812
|
t_class: "import { t_class } from \"${folder}\";",
|
|
3567
3813
|
t_style: "import { t_style } from \"${folder}\";",
|
|
3814
|
+
t_slot_guard: "import { t_slot_guard } from \"${folder}\";",
|
|
3568
3815
|
ServerSlotRender: "import { type ServerSlotRender } from \"${folder}\";"
|
|
3569
3816
|
};
|
|
3570
3817
|
function buildServerCode(template, options) {
|
|
@@ -3632,6 +3879,7 @@ function buildServerTemplate(template, imports, b, options) {
|
|
|
3632
3879
|
varNames: {},
|
|
3633
3880
|
preserveWhitespace: false,
|
|
3634
3881
|
awaitCount: 0,
|
|
3882
|
+
elementStack: [],
|
|
3635
3883
|
options
|
|
3636
3884
|
};
|
|
3637
3885
|
b.append("");
|
|
@@ -3656,6 +3904,7 @@ function buildServerTemplate(template, imports, b, options) {
|
|
|
3656
3904
|
varNames: {},
|
|
3657
3905
|
preserveWhitespace: false,
|
|
3658
3906
|
awaitCount: 0,
|
|
3907
|
+
elementStack: [],
|
|
3659
3908
|
options
|
|
3660
3909
|
};
|
|
3661
3910
|
b.append(`} catch (${current.errorVar}) {`);
|
|
@@ -3679,6 +3928,7 @@ function buildServerTemplate(template, imports, b, options) {
|
|
|
3679
3928
|
preserveWhitespace: false,
|
|
3680
3929
|
inHead: true,
|
|
3681
3930
|
awaitCount: 0,
|
|
3931
|
+
elementStack: [],
|
|
3682
3932
|
options
|
|
3683
3933
|
};
|
|
3684
3934
|
b.append("");
|
|
@@ -3833,16 +4083,1156 @@ function build(template, options) {
|
|
|
3833
4083
|
}
|
|
3834
4084
|
let map = [];
|
|
3835
4085
|
let errors = [];
|
|
4086
|
+
let warnings = [];
|
|
3836
4087
|
return {
|
|
3837
|
-
code: options?.server ? buildServerCode(template, options) : buildCode(template, map, options, errors),
|
|
4088
|
+
code: options?.server ? buildServerCode(template, options) : buildCode(template, map, options, errors, warnings),
|
|
3838
4089
|
styles: template.components.map((c) => c.style ? {
|
|
3839
4090
|
style: buildStyles(c.style, c.style.hash),
|
|
3840
4091
|
hash: c.style.hash
|
|
3841
4092
|
} : void 0).filter((c) => c !== void 0),
|
|
3842
4093
|
map,
|
|
4094
|
+
errors,
|
|
4095
|
+
warnings
|
|
4096
|
+
};
|
|
4097
|
+
}
|
|
4098
|
+
//#endregion
|
|
4099
|
+
//#region src/compile/build/restricted/scanState.ts
|
|
4100
|
+
/**
|
|
4101
|
+
* Matches `let|const|var <name> [type] = $watch(` at exactly the scan
|
|
4102
|
+
* position (sticky), tolerating a type annotation.
|
|
4103
|
+
*/
|
|
4104
|
+
const DECLARATION = /(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?\s*=\s*\$watch\s*(?:<[^>(]*>)?\s*\(/y;
|
|
4105
|
+
/**
|
|
4106
|
+
* Finds `let <name> = $watch(<initializer>)` declarations in a component's
|
|
4107
|
+
* script chunks (restricted mode's client state). Scans the code with
|
|
4108
|
+
* strings, comments and regex literals skipped — so a `$watch` inside a
|
|
4109
|
+
* string never matches — and returns each initializer source with its
|
|
4110
|
+
* absolute offset, so it can be parsed into a restricted expression with
|
|
4111
|
+
* correct error positions.
|
|
4112
|
+
*/
|
|
4113
|
+
function scanStateInitializers(chunks) {
|
|
4114
|
+
let text = "";
|
|
4115
|
+
const offsets = [];
|
|
4116
|
+
for (const chunk of chunks) {
|
|
4117
|
+
for (let i = 0; i < chunk.script.length; i++) offsets.push(chunk.span.start + i);
|
|
4118
|
+
text += chunk.script;
|
|
4119
|
+
}
|
|
4120
|
+
const results = [];
|
|
4121
|
+
let i = 0;
|
|
4122
|
+
while (i < text.length) {
|
|
4123
|
+
const skipped = skipStringOrComment(text, i);
|
|
4124
|
+
if (skipped !== -1) {
|
|
4125
|
+
i = skipped;
|
|
4126
|
+
continue;
|
|
4127
|
+
}
|
|
4128
|
+
DECLARATION.lastIndex = i;
|
|
4129
|
+
const match = DECLARATION.exec(text);
|
|
4130
|
+
if (match === null || match.index !== i) {
|
|
4131
|
+
i += 1;
|
|
4132
|
+
continue;
|
|
4133
|
+
}
|
|
4134
|
+
const name = match[1];
|
|
4135
|
+
const open = i + match[0].length - 1;
|
|
4136
|
+
let level = 0;
|
|
4137
|
+
let close = -1;
|
|
4138
|
+
let j = open;
|
|
4139
|
+
while (j < text.length) {
|
|
4140
|
+
const skipped = skipStringOrComment(text, j);
|
|
4141
|
+
if (skipped !== -1) {
|
|
4142
|
+
j = skipped;
|
|
4143
|
+
continue;
|
|
4144
|
+
}
|
|
4145
|
+
if (text[j] === "(") level += 1;
|
|
4146
|
+
else if (text[j] === ")") {
|
|
4147
|
+
level -= 1;
|
|
4148
|
+
if (level === 0) {
|
|
4149
|
+
close = j;
|
|
4150
|
+
break;
|
|
4151
|
+
}
|
|
4152
|
+
}
|
|
4153
|
+
j += 1;
|
|
4154
|
+
}
|
|
4155
|
+
if (close === -1) break;
|
|
4156
|
+
const initStart = open + 1;
|
|
4157
|
+
results.push({
|
|
4158
|
+
name,
|
|
4159
|
+
initSource: text.substring(initStart, close),
|
|
4160
|
+
start: offsets[initStart] ?? i
|
|
4161
|
+
});
|
|
4162
|
+
i = close;
|
|
4163
|
+
}
|
|
4164
|
+
return results;
|
|
4165
|
+
}
|
|
4166
|
+
//#endregion
|
|
4167
|
+
//#region src/compile/build/restricted/parseExpression.ts
|
|
4168
|
+
/**
|
|
4169
|
+
* Parses a restricted template expression into the serialized op set.
|
|
4170
|
+
*
|
|
4171
|
+
* This is intentionally a small, hand-written parser rather than a general
|
|
4172
|
+
* JS parser: the grammar *is* the restricted op set (the permanent format
|
|
4173
|
+
* API), so anything outside it is rejected with a positioned error instead
|
|
4174
|
+
* of being parsed and then policed. Regex-based tokenizing was rejected --
|
|
4175
|
+
* operators inside string literals and operator precedence make it
|
|
4176
|
+
* unsound.
|
|
4177
|
+
*
|
|
4178
|
+
* Supported: literals, identifiers (props/data/loop variables), property
|
|
4179
|
+
* and index access, unary `! - + typeof`, arithmetic/comparison/logic
|
|
4180
|
+
* (`* / %`, `+ -`, `< <= > >=`, `== != === !==`, `&&`, `||`, `??`),
|
|
4181
|
+
* ternaries, and array/object literals.
|
|
4182
|
+
*
|
|
4183
|
+
* Deliberately not supported (each gets a targeted error): calls (format
|
|
4184
|
+
* in `derive` instead), authored functions/arrows, `new`, `await`,
|
|
4185
|
+
* assignments and updates, optional chaining, template literals, spread.
|
|
4186
|
+
*/
|
|
4187
|
+
var RestrictedSyntaxError = class extends Error {
|
|
4188
|
+
/** Absolute index (including the parser's offset) where the error starts. */
|
|
4189
|
+
start;
|
|
4190
|
+
/** Absolute index where the error ends. */
|
|
4191
|
+
end;
|
|
4192
|
+
constructor(message, start, end) {
|
|
4193
|
+
super(message);
|
|
4194
|
+
this.name = "RestrictedSyntaxError";
|
|
4195
|
+
this.start = start;
|
|
4196
|
+
this.end = end;
|
|
4197
|
+
}
|
|
4198
|
+
};
|
|
4199
|
+
const MULTI_PUNCT = [
|
|
4200
|
+
"===",
|
|
4201
|
+
"!==",
|
|
4202
|
+
"&&=",
|
|
4203
|
+
"||=",
|
|
4204
|
+
"??=",
|
|
4205
|
+
"...",
|
|
4206
|
+
"=>",
|
|
4207
|
+
"?.",
|
|
4208
|
+
"==",
|
|
4209
|
+
"!=",
|
|
4210
|
+
"<=",
|
|
4211
|
+
">=",
|
|
4212
|
+
"&&",
|
|
4213
|
+
"||",
|
|
4214
|
+
"??",
|
|
4215
|
+
"++",
|
|
4216
|
+
"--",
|
|
4217
|
+
"+=",
|
|
4218
|
+
"-=",
|
|
4219
|
+
"*=",
|
|
4220
|
+
"/=",
|
|
4221
|
+
"%="
|
|
4222
|
+
];
|
|
4223
|
+
const SINGLE_PUNCT = new Set("+-*/%!<>=?:.,()[]{}".split(""));
|
|
4224
|
+
const ASSIGNMENT = /* @__PURE__ */ new Set([
|
|
4225
|
+
"=",
|
|
4226
|
+
"+=",
|
|
4227
|
+
"-=",
|
|
4228
|
+
"*=",
|
|
4229
|
+
"/=",
|
|
4230
|
+
"%=",
|
|
4231
|
+
"&&=",
|
|
4232
|
+
"||=",
|
|
4233
|
+
"??="
|
|
4234
|
+
]);
|
|
4235
|
+
/** Binary operators from lowest to highest precedence. */
|
|
4236
|
+
const BINARY_LEVELS = [
|
|
4237
|
+
["??"],
|
|
4238
|
+
["||"],
|
|
4239
|
+
["&&"],
|
|
4240
|
+
[
|
|
4241
|
+
"==",
|
|
4242
|
+
"!=",
|
|
4243
|
+
"===",
|
|
4244
|
+
"!=="
|
|
4245
|
+
],
|
|
4246
|
+
[
|
|
4247
|
+
"<",
|
|
4248
|
+
"<=",
|
|
4249
|
+
">",
|
|
4250
|
+
">="
|
|
4251
|
+
],
|
|
4252
|
+
["+", "-"],
|
|
4253
|
+
[
|
|
4254
|
+
"*",
|
|
4255
|
+
"/",
|
|
4256
|
+
"%"
|
|
4257
|
+
]
|
|
4258
|
+
];
|
|
4259
|
+
const UNARY_PUNCT = /* @__PURE__ */ new Set([
|
|
4260
|
+
"!",
|
|
4261
|
+
"-",
|
|
4262
|
+
"+"
|
|
4263
|
+
]);
|
|
4264
|
+
const DANGEROUS_KEYS = /* @__PURE__ */ new Set([
|
|
4265
|
+
"__proto__",
|
|
4266
|
+
"prototype",
|
|
4267
|
+
"constructor"
|
|
4268
|
+
]);
|
|
4269
|
+
const RESERVED = {
|
|
4270
|
+
new: "`new` isn't supported in restricted expressions.",
|
|
4271
|
+
await: "`await` isn't supported in restricted expressions; SSR data comes from `data` requirements.",
|
|
4272
|
+
this: "`this` isn't supported in restricted expressions.",
|
|
4273
|
+
super: "`super` isn't supported in restricted expressions.",
|
|
4274
|
+
function: "Function expressions aren't supported in restricted expressions.",
|
|
4275
|
+
class: "Classes aren't supported in restricted expressions.",
|
|
4276
|
+
yield: "`yield` isn't supported in restricted expressions.",
|
|
4277
|
+
delete: "`delete` isn't supported in restricted expressions.",
|
|
4278
|
+
void: "`void` isn't supported in restricted expressions.",
|
|
4279
|
+
in: "`in` isn't supported in restricted expressions.",
|
|
4280
|
+
instanceof: "`instanceof` isn't supported in restricted expressions.",
|
|
4281
|
+
const: "Declarations aren't supported in restricted expressions.",
|
|
4282
|
+
let: "Declarations aren't supported in restricted expressions.",
|
|
4283
|
+
var: "Declarations aren't supported in restricted expressions.",
|
|
4284
|
+
return: "`return` isn't supported in restricted expressions."
|
|
4285
|
+
};
|
|
4286
|
+
const CALLS_UNSUPPORTED = "Function calls aren't supported in restricted template expressions. Compute formatted/derived values in the data layer instead, e.g. `data view from derive { of: …, map: { formattedX: format($item.x) } }`, or have the host shape the requirement's result.";
|
|
4287
|
+
const ARROWS_UNSUPPORTED = "Arrow functions aren't supported in restricted expressions. Move the logic into a `derive` requirement, a host formatter, or the client build.";
|
|
4288
|
+
function tokenize(source, offset) {
|
|
4289
|
+
const tokens = [];
|
|
4290
|
+
let i = 0;
|
|
4291
|
+
const error = (message, start, end) => {
|
|
4292
|
+
throw new RestrictedSyntaxError(message, offset + start, offset + end);
|
|
4293
|
+
};
|
|
4294
|
+
while (i < source.length) {
|
|
4295
|
+
const char = source[i];
|
|
4296
|
+
if (char === " " || char === " " || char === "\n" || char === "\r") {
|
|
4297
|
+
i += 1;
|
|
4298
|
+
continue;
|
|
4299
|
+
}
|
|
4300
|
+
const start = i;
|
|
4301
|
+
if (char >= "0" && char <= "9") {
|
|
4302
|
+
i += 1;
|
|
4303
|
+
while (i < source.length && source[i] >= "0" && source[i] <= "9") i += 1;
|
|
4304
|
+
if (source[i] === "." && source[i + 1] >= "0" && source[i + 1] <= "9") {
|
|
4305
|
+
i += 1;
|
|
4306
|
+
while (i < source.length && source[i] >= "0" && source[i] <= "9") i += 1;
|
|
4307
|
+
}
|
|
4308
|
+
if (source[i] === "e" || source[i] === "E") {
|
|
4309
|
+
const exponentStart = i;
|
|
4310
|
+
i += 1;
|
|
4311
|
+
if (source[i] === "+" || source[i] === "-") i += 1;
|
|
4312
|
+
if (source[i] >= "0" && source[i] <= "9") while (i < source.length && source[i] >= "0" && source[i] <= "9") i += 1;
|
|
4313
|
+
else i = exponentStart;
|
|
4314
|
+
}
|
|
4315
|
+
tokens.push({
|
|
4316
|
+
type: "num",
|
|
4317
|
+
value: source.substring(start, i),
|
|
4318
|
+
start: offset + start,
|
|
4319
|
+
end: offset + i
|
|
4320
|
+
});
|
|
4321
|
+
continue;
|
|
4322
|
+
}
|
|
4323
|
+
if (char === "\"" || char === "'") {
|
|
4324
|
+
const quote = char;
|
|
4325
|
+
i += 1;
|
|
4326
|
+
let value = "";
|
|
4327
|
+
let closed = false;
|
|
4328
|
+
while (i < source.length) {
|
|
4329
|
+
const current = source[i];
|
|
4330
|
+
if (current === quote) {
|
|
4331
|
+
i += 1;
|
|
4332
|
+
closed = true;
|
|
4333
|
+
break;
|
|
4334
|
+
}
|
|
4335
|
+
if (current === "\n") break;
|
|
4336
|
+
if (current === "\\") {
|
|
4337
|
+
i += 1;
|
|
4338
|
+
const escape = source[i];
|
|
4339
|
+
if (escape === void 0) break;
|
|
4340
|
+
switch (escape) {
|
|
4341
|
+
case "n":
|
|
4342
|
+
value += "\n";
|
|
4343
|
+
break;
|
|
4344
|
+
case "r":
|
|
4345
|
+
value += "\r";
|
|
4346
|
+
break;
|
|
4347
|
+
case "t":
|
|
4348
|
+
value += " ";
|
|
4349
|
+
break;
|
|
4350
|
+
case "b":
|
|
4351
|
+
value += "\b";
|
|
4352
|
+
break;
|
|
4353
|
+
case "f":
|
|
4354
|
+
value += "\f";
|
|
4355
|
+
break;
|
|
4356
|
+
case "v":
|
|
4357
|
+
value += "\v";
|
|
4358
|
+
break;
|
|
4359
|
+
case "0":
|
|
4360
|
+
value += "\0";
|
|
4361
|
+
break;
|
|
4362
|
+
case "\\":
|
|
4363
|
+
value += "\\";
|
|
4364
|
+
break;
|
|
4365
|
+
case "'":
|
|
4366
|
+
value += "'";
|
|
4367
|
+
break;
|
|
4368
|
+
case "\"":
|
|
4369
|
+
value += "\"";
|
|
4370
|
+
break;
|
|
4371
|
+
case "u": {
|
|
4372
|
+
const hex = source.substring(i + 1, i + 5);
|
|
4373
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) error("Invalid unicode escape sequence", i - 1, i + 2);
|
|
4374
|
+
value += String.fromCharCode(parseInt(hex, 16));
|
|
4375
|
+
i += 4;
|
|
4376
|
+
break;
|
|
4377
|
+
}
|
|
4378
|
+
default: error(`Invalid escape sequence "\\${escape}"`, i - 1, i + 1);
|
|
4379
|
+
}
|
|
4380
|
+
i += 1;
|
|
4381
|
+
continue;
|
|
4382
|
+
}
|
|
4383
|
+
value += current;
|
|
4384
|
+
i += 1;
|
|
4385
|
+
}
|
|
4386
|
+
if (!closed) error("Unterminated string literal", start, i);
|
|
4387
|
+
tokens.push({
|
|
4388
|
+
type: "str",
|
|
4389
|
+
value,
|
|
4390
|
+
start: offset + start,
|
|
4391
|
+
end: offset + i
|
|
4392
|
+
});
|
|
4393
|
+
continue;
|
|
4394
|
+
}
|
|
4395
|
+
if (char === "`") error("Template literals aren't supported in restricted expressions; use string concatenation with `+`.", start, start + 1);
|
|
4396
|
+
if (char === "$" || char === "_" || /[A-Za-z]/.test(char)) {
|
|
4397
|
+
i += 1;
|
|
4398
|
+
while (i < source.length && /[A-Za-z0-9_$]/.test(source[i])) i += 1;
|
|
4399
|
+
tokens.push({
|
|
4400
|
+
type: "ident",
|
|
4401
|
+
value: source.substring(start, i),
|
|
4402
|
+
start: offset + start,
|
|
4403
|
+
end: offset + i
|
|
4404
|
+
});
|
|
4405
|
+
continue;
|
|
4406
|
+
}
|
|
4407
|
+
let matched;
|
|
4408
|
+
for (const punct of MULTI_PUNCT) if (source.startsWith(punct, i)) {
|
|
4409
|
+
matched = punct;
|
|
4410
|
+
break;
|
|
4411
|
+
}
|
|
4412
|
+
if (matched === void 0 && SINGLE_PUNCT.has(char)) matched = char;
|
|
4413
|
+
if (matched !== void 0) {
|
|
4414
|
+
i += matched.length;
|
|
4415
|
+
tokens.push({
|
|
4416
|
+
type: "punct",
|
|
4417
|
+
value: matched,
|
|
4418
|
+
start: offset + start,
|
|
4419
|
+
end: offset + i
|
|
4420
|
+
});
|
|
4421
|
+
continue;
|
|
4422
|
+
}
|
|
4423
|
+
error(`Unexpected character "${char}"`, start, start + 1);
|
|
4424
|
+
}
|
|
4425
|
+
tokens.push({
|
|
4426
|
+
type: "eof",
|
|
4427
|
+
value: "",
|
|
4428
|
+
start: offset + source.length,
|
|
4429
|
+
end: offset + source.length
|
|
4430
|
+
});
|
|
4431
|
+
return tokens;
|
|
4432
|
+
}
|
|
4433
|
+
/**
|
|
4434
|
+
* Parses one restricted expression.
|
|
4435
|
+
*
|
|
4436
|
+
* @param source The expression source text
|
|
4437
|
+
* @param offset The source index the expression starts at, so errors point
|
|
4438
|
+
* into the original file
|
|
4439
|
+
*/
|
|
4440
|
+
function parseExpression(source, offset = 0, options) {
|
|
4441
|
+
return parseCore(source, offset, false, options).expression;
|
|
4442
|
+
}
|
|
4443
|
+
/**
|
|
4444
|
+
* Parses an expression that is followed by more text (e.g. a requirement
|
|
4445
|
+
* spec's `,` or the end of the spec). Returns where the expression ended so
|
|
4446
|
+
* callers can continue scanning.
|
|
4447
|
+
*/
|
|
4448
|
+
function parseExpressionPrefix(source, offset = 0, options) {
|
|
4449
|
+
return parseCore(source, offset, true, options);
|
|
4450
|
+
}
|
|
4451
|
+
function parseCore(source, offset, allowTrailing, options) {
|
|
4452
|
+
const allowCalls = options?.allowCalls === true;
|
|
4453
|
+
const tokens = tokenize(source, offset);
|
|
4454
|
+
let index = 0;
|
|
4455
|
+
const peek = () => tokens[index];
|
|
4456
|
+
const next = () => tokens[index++];
|
|
4457
|
+
const error = (message, token = peek()) => {
|
|
4458
|
+
throw new RestrictedSyntaxError(message, token.start, token.end);
|
|
4459
|
+
};
|
|
4460
|
+
const expect = (value) => {
|
|
4461
|
+
const token = next();
|
|
4462
|
+
if (token.type === "eof" || token.value !== value) error(`Expected "${value}"${token.type === "eof" ? " but reached the end of the expression" : ` but found "${token.value}"`}`, token);
|
|
4463
|
+
return token;
|
|
4464
|
+
};
|
|
4465
|
+
const isPunct = (value) => peek().type === "punct" && peek().value === value;
|
|
4466
|
+
function parseTernary() {
|
|
4467
|
+
const test = parseBinary(0);
|
|
4468
|
+
if (!isPunct("?")) return test;
|
|
4469
|
+
next();
|
|
4470
|
+
const consequent = parseTernary();
|
|
4471
|
+
expect(":");
|
|
4472
|
+
return {
|
|
4473
|
+
op: "ternary",
|
|
4474
|
+
test,
|
|
4475
|
+
consequent,
|
|
4476
|
+
alternate: parseTernary()
|
|
4477
|
+
};
|
|
4478
|
+
}
|
|
4479
|
+
function parseBinary(level) {
|
|
4480
|
+
if (level >= BINARY_LEVELS.length) return parseUnary();
|
|
4481
|
+
const operators = BINARY_LEVELS[level];
|
|
4482
|
+
let left = parseBinary(level + 1);
|
|
4483
|
+
while (peek().type === "punct" && operators.includes(peek().value)) {
|
|
4484
|
+
const operator = next().value;
|
|
4485
|
+
const right = parseBinary(level + 1);
|
|
4486
|
+
left = {
|
|
4487
|
+
op: "binary",
|
|
4488
|
+
operator,
|
|
4489
|
+
left,
|
|
4490
|
+
right
|
|
4491
|
+
};
|
|
4492
|
+
}
|
|
4493
|
+
return left;
|
|
4494
|
+
}
|
|
4495
|
+
function parseUnary() {
|
|
4496
|
+
const token = peek();
|
|
4497
|
+
if (token.type === "punct" && UNARY_PUNCT.has(token.value) || token.type === "ident" && token.value === "typeof") {
|
|
4498
|
+
next();
|
|
4499
|
+
const operand = parseUnary();
|
|
4500
|
+
return {
|
|
4501
|
+
op: "unary",
|
|
4502
|
+
operator: token.value,
|
|
4503
|
+
operand
|
|
4504
|
+
};
|
|
4505
|
+
}
|
|
4506
|
+
return parsePostfix();
|
|
4507
|
+
}
|
|
4508
|
+
function parsePostfix() {
|
|
4509
|
+
let expression = parsePrimary();
|
|
4510
|
+
while (true) {
|
|
4511
|
+
const token = peek();
|
|
4512
|
+
if (token.type !== "punct") return expression;
|
|
4513
|
+
if (token.value === "." || token.value === "?.") {
|
|
4514
|
+
const optional = token.value === "?.";
|
|
4515
|
+
next();
|
|
4516
|
+
if (optional && peek().type === "punct" && peek().value === "[") {
|
|
4517
|
+
next();
|
|
4518
|
+
const indexExpr = parseTernary();
|
|
4519
|
+
expect("]");
|
|
4520
|
+
expression = {
|
|
4521
|
+
op: "index",
|
|
4522
|
+
object: expression,
|
|
4523
|
+
index: indexExpr,
|
|
4524
|
+
optional: true
|
|
4525
|
+
};
|
|
4526
|
+
continue;
|
|
4527
|
+
}
|
|
4528
|
+
const key = next();
|
|
4529
|
+
if (key.type !== "ident") error(`Expected a property name after "${token.value}"`, key);
|
|
4530
|
+
if (DANGEROUS_KEYS.has(key.value)) error(`Dangerous property name "${key.value}" isn't allowed in restricted expressions`, key);
|
|
4531
|
+
expression = optional ? {
|
|
4532
|
+
op: "get",
|
|
4533
|
+
object: expression,
|
|
4534
|
+
key: key.value,
|
|
4535
|
+
optional: true
|
|
4536
|
+
} : {
|
|
4537
|
+
op: "get",
|
|
4538
|
+
object: expression,
|
|
4539
|
+
key: key.value
|
|
4540
|
+
};
|
|
4541
|
+
continue;
|
|
4542
|
+
}
|
|
4543
|
+
if (token.value === "[") {
|
|
4544
|
+
next();
|
|
4545
|
+
const indexExpr = parseTernary();
|
|
4546
|
+
expect("]");
|
|
4547
|
+
expression = {
|
|
4548
|
+
op: "index",
|
|
4549
|
+
object: expression,
|
|
4550
|
+
index: indexExpr
|
|
4551
|
+
};
|
|
4552
|
+
continue;
|
|
4553
|
+
}
|
|
4554
|
+
if (token.value === "(") {
|
|
4555
|
+
if (!allowCalls) error(CALLS_UNSUPPORTED, token);
|
|
4556
|
+
if (expression.op !== "ref") error("Only named host functions can be called; method calls (a.b()) aren't supported in restricted expressions.", token);
|
|
4557
|
+
next();
|
|
4558
|
+
const args = [];
|
|
4559
|
+
while (!isPunct(")")) {
|
|
4560
|
+
if (peek().type === "eof") expect(")");
|
|
4561
|
+
args.push(parseTernary());
|
|
4562
|
+
if (isPunct(",")) next();
|
|
4563
|
+
}
|
|
4564
|
+
expect(")");
|
|
4565
|
+
expression = {
|
|
4566
|
+
op: "call",
|
|
4567
|
+
name: expression.name,
|
|
4568
|
+
args
|
|
4569
|
+
};
|
|
4570
|
+
continue;
|
|
4571
|
+
}
|
|
4572
|
+
if (token.value === "++" || token.value === "--") error("Updates (`++`/`--`) aren't supported in restricted expressions.", token);
|
|
4573
|
+
return expression;
|
|
4574
|
+
}
|
|
4575
|
+
}
|
|
4576
|
+
function parsePrimary() {
|
|
4577
|
+
const token = next();
|
|
4578
|
+
switch (token.type) {
|
|
4579
|
+
case "num": return {
|
|
4580
|
+
op: "lit",
|
|
4581
|
+
value: Number(token.value)
|
|
4582
|
+
};
|
|
4583
|
+
case "str": return {
|
|
4584
|
+
op: "lit",
|
|
4585
|
+
value: token.value
|
|
4586
|
+
};
|
|
4587
|
+
case "ident": {
|
|
4588
|
+
const name = token.value;
|
|
4589
|
+
if (name === "true") return {
|
|
4590
|
+
op: "lit",
|
|
4591
|
+
value: true
|
|
4592
|
+
};
|
|
4593
|
+
if (name === "false") return {
|
|
4594
|
+
op: "lit",
|
|
4595
|
+
value: false
|
|
4596
|
+
};
|
|
4597
|
+
if (name === "null" || name === "undefined") return {
|
|
4598
|
+
op: "lit",
|
|
4599
|
+
value: null
|
|
4600
|
+
};
|
|
4601
|
+
const reserved = RESERVED[name];
|
|
4602
|
+
if (reserved !== void 0) error(reserved, token);
|
|
4603
|
+
return {
|
|
4604
|
+
op: "ref",
|
|
4605
|
+
name
|
|
4606
|
+
};
|
|
4607
|
+
}
|
|
4608
|
+
case "punct":
|
|
4609
|
+
if (token.value === "(") {
|
|
4610
|
+
const expression = parseTernary();
|
|
4611
|
+
expect(")");
|
|
4612
|
+
return expression;
|
|
4613
|
+
}
|
|
4614
|
+
if (token.value === "[") {
|
|
4615
|
+
const items = [];
|
|
4616
|
+
while (!isPunct("]")) {
|
|
4617
|
+
if (peek().type === "eof") expect("]");
|
|
4618
|
+
if (isPunct(",")) {
|
|
4619
|
+
next();
|
|
4620
|
+
continue;
|
|
4621
|
+
}
|
|
4622
|
+
items.push(parseTernary());
|
|
4623
|
+
if (isPunct(",")) next();
|
|
4624
|
+
}
|
|
4625
|
+
expect("]");
|
|
4626
|
+
return {
|
|
4627
|
+
op: "array",
|
|
4628
|
+
items
|
|
4629
|
+
};
|
|
4630
|
+
}
|
|
4631
|
+
if (token.value === "{") {
|
|
4632
|
+
const entries = {};
|
|
4633
|
+
while (!isPunct("}")) {
|
|
4634
|
+
if (peek().type === "eof") expect("}");
|
|
4635
|
+
if (isPunct(",")) {
|
|
4636
|
+
next();
|
|
4637
|
+
continue;
|
|
4638
|
+
}
|
|
4639
|
+
const key = next();
|
|
4640
|
+
if (key.type !== "ident" && key.type !== "str" && key.type !== "num") error("Expected an object key (identifier, string or number)", key);
|
|
4641
|
+
if (DANGEROUS_KEYS.has(key.value)) error(`Dangerous property name "${key.value}" isn't allowed in restricted expressions`, key);
|
|
4642
|
+
expect(":");
|
|
4643
|
+
entries[key.value] = parseTernary();
|
|
4644
|
+
if (isPunct(",")) next();
|
|
4645
|
+
}
|
|
4646
|
+
expect("}");
|
|
4647
|
+
return {
|
|
4648
|
+
op: "object",
|
|
4649
|
+
entries
|
|
4650
|
+
};
|
|
4651
|
+
}
|
|
4652
|
+
if (token.value === "...") error("Spread isn't supported in restricted expressions.", token);
|
|
4653
|
+
if (token.value === "=>") error(ARROWS_UNSUPPORTED, token);
|
|
4654
|
+
if (ASSIGNMENT.has(token.value)) error("Assignments aren't supported in restricted expressions.", token);
|
|
4655
|
+
error(`Unexpected "${token.value}"`, token);
|
|
4656
|
+
}
|
|
4657
|
+
error("Unexpected end of expression", token);
|
|
4658
|
+
}
|
|
4659
|
+
const expression = parseTernary();
|
|
4660
|
+
const trailing = peek();
|
|
4661
|
+
if (trailing.type !== "eof" && !allowTrailing) {
|
|
4662
|
+
if (trailing.type === "punct" && trailing.value === "=>") error(ARROWS_UNSUPPORTED, trailing);
|
|
4663
|
+
if (trailing.type === "punct" && ASSIGNMENT.has(trailing.value)) error("Assignments aren't supported in restricted expressions.", trailing);
|
|
4664
|
+
if (trailing.type === "ident" && RESERVED[trailing.value] !== void 0) error(RESERVED[trailing.value], trailing);
|
|
4665
|
+
error(`Unexpected "${trailing.value}" after expression`, trailing);
|
|
4666
|
+
}
|
|
4667
|
+
return {
|
|
4668
|
+
expression,
|
|
4669
|
+
end: trailing.type === "eof" ? offset + source.length : trailing.start
|
|
4670
|
+
};
|
|
4671
|
+
}
|
|
4672
|
+
//#endregion
|
|
4673
|
+
//#region src/compile/build/restricted/buildRestricted.ts
|
|
4674
|
+
/**
|
|
4675
|
+
* Builds a template into a serialized restricted program: the server-side
|
|
4676
|
+
* instruction tree interpreted by `renderRestricted` (no `eval`, so it is
|
|
4677
|
+
* legal on workerd).
|
|
4678
|
+
*
|
|
4679
|
+
* Must be called on a **freshly parsed** template: it maps text
|
|
4680
|
+
* interpolations through the parse-time source spans. Trimming whitespace
|
|
4681
|
+
* nodes here is safe (only whitespace-only nodes change), and matches the
|
|
4682
|
+
* JS build; `build()` calling `trimWhitespace` again is idempotent.
|
|
4683
|
+
*/
|
|
4684
|
+
function buildRestricted(template, options) {
|
|
4685
|
+
const source = options?.source ?? "";
|
|
4686
|
+
const errors = [];
|
|
4687
|
+
const report = (message, start, end = start) => {
|
|
4688
|
+
errors.push(compileError(message, start, end, source));
|
|
4689
|
+
};
|
|
4690
|
+
const components = [];
|
|
4691
|
+
const styles = [];
|
|
4692
|
+
for (let componentIndex = 0; componentIndex < template.components.length; componentIndex++) {
|
|
4693
|
+
const component = template.components[componentIndex];
|
|
4694
|
+
const styleHash = component.style?.hash ?? "";
|
|
4695
|
+
if (component.style) styles.push({
|
|
4696
|
+
style: buildStyles(component.style, styleHash),
|
|
4697
|
+
hash: styleHash
|
|
4698
|
+
});
|
|
4699
|
+
if (component.head) report("@head content isn't supported in restricted mode yet.", component.start ?? 0);
|
|
4700
|
+
if (component.error) report("@error blocks aren't supported in restricted mode yet.", component.start ?? 0);
|
|
4701
|
+
const state = [];
|
|
4702
|
+
const stateNames = [];
|
|
4703
|
+
const allowedRefs = /* @__PURE__ */ new Set(["$props", "$data"]);
|
|
4704
|
+
const context = {
|
|
4705
|
+
source,
|
|
4706
|
+
styleHash,
|
|
4707
|
+
preserveWhitespace: options?.preserveWhitespace === true,
|
|
4708
|
+
errors,
|
|
4709
|
+
report,
|
|
4710
|
+
allowedRefs,
|
|
4711
|
+
stateNames,
|
|
4712
|
+
loopVars: [],
|
|
4713
|
+
elementStack: []
|
|
4714
|
+
};
|
|
4715
|
+
if (component.markup && options?.preserveWhitespace !== true) trimWhitespace(component.markup);
|
|
4716
|
+
const nextStart = template.components[componentIndex + 1]?.scriptStart ?? template.script.length;
|
|
4717
|
+
const componentChunks = template.script.slice(component.scriptStart ?? 0, nextStart);
|
|
4718
|
+
for (const scanned of scanStateInitializers(componentChunks)) try {
|
|
4719
|
+
const init = parseExprAt(scanned.initSource, scanned.start, context);
|
|
4720
|
+
validateRefs(init, /* @__PURE__ */ new Set(["$props"]), context, scanned.start, `state initializer "${scanned.name}"`, []);
|
|
4721
|
+
state.push({
|
|
4722
|
+
name: scanned.name,
|
|
4723
|
+
init
|
|
4724
|
+
});
|
|
4725
|
+
stateNames.push(scanned.name);
|
|
4726
|
+
allowedRefs.add(scanned.name);
|
|
4727
|
+
} catch (error) {
|
|
4728
|
+
if (error instanceof RestrictedSyntaxError) report(error.message, error.start, error.end);
|
|
4729
|
+
else throw error;
|
|
4730
|
+
}
|
|
4731
|
+
const markup = component.markup ? serializeChildren(component.markup.children, context) : [];
|
|
4732
|
+
components.push({
|
|
4733
|
+
name: component.name,
|
|
4734
|
+
default: component.default,
|
|
4735
|
+
markup,
|
|
4736
|
+
state: state.length > 0 ? state : void 0
|
|
4737
|
+
});
|
|
4738
|
+
}
|
|
4739
|
+
errors.sort((a, b) => a.startIndex - b.startIndex);
|
|
4740
|
+
return {
|
|
4741
|
+
program: {
|
|
4742
|
+
requirements: [],
|
|
4743
|
+
components
|
|
4744
|
+
},
|
|
4745
|
+
styles,
|
|
3843
4746
|
errors
|
|
3844
4747
|
};
|
|
3845
4748
|
}
|
|
4749
|
+
function compileError(message, start, end, source) {
|
|
4750
|
+
let startLine = 0;
|
|
4751
|
+
let lastLineStart = 0;
|
|
4752
|
+
let i = 0;
|
|
4753
|
+
for (; i < start && i < source.length; i++) if (source[i] === "\n") {
|
|
4754
|
+
startLine += 1;
|
|
4755
|
+
lastLineStart = i + 1;
|
|
4756
|
+
}
|
|
4757
|
+
const startChar = start - lastLineStart;
|
|
4758
|
+
let endLine = startLine;
|
|
4759
|
+
for (; i < end && i < source.length; i++) if (source[i] === "\n") {
|
|
4760
|
+
endLine += 1;
|
|
4761
|
+
lastLineStart = i + 1;
|
|
4762
|
+
}
|
|
4763
|
+
return {
|
|
4764
|
+
message,
|
|
4765
|
+
startIndex: start,
|
|
4766
|
+
startLine,
|
|
4767
|
+
startChar,
|
|
4768
|
+
endIndex: end,
|
|
4769
|
+
endLine,
|
|
4770
|
+
endChar: end - lastLineStart
|
|
4771
|
+
};
|
|
4772
|
+
}
|
|
4773
|
+
function serializeChildren(nodes, context) {
|
|
4774
|
+
const result = [];
|
|
4775
|
+
for (const node of nodes) {
|
|
4776
|
+
const serialized = serializeNode(node, context);
|
|
4777
|
+
if (serialized !== void 0) result.push(serialized);
|
|
4778
|
+
}
|
|
4779
|
+
return result;
|
|
4780
|
+
}
|
|
4781
|
+
function serializeNode(node, context) {
|
|
4782
|
+
if (isTextNode(node)) return serializeText(node, context);
|
|
4783
|
+
if (isControlNode(node)) return serializeControl(node, context);
|
|
4784
|
+
if (node.type === "comment") return;
|
|
4785
|
+
if (isComponentNode(node)) return serializeComponent(node, context);
|
|
4786
|
+
if (isSpecialNode(node)) {
|
|
4787
|
+
if (node.tagName === "slot") return serializeSlotElement(node, context);
|
|
4788
|
+
context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
|
|
4789
|
+
return;
|
|
4790
|
+
}
|
|
4791
|
+
return serializeElement(node, context);
|
|
4792
|
+
}
|
|
4793
|
+
/** Component attributes: static values and fully-reactive expressions only. */
|
|
4794
|
+
function serializeComponentProps(node, context) {
|
|
4795
|
+
const attributes = [];
|
|
4796
|
+
let needsClass = node.scopeStyles === true && context.styleHash !== "";
|
|
4797
|
+
for (const attribute of node.attributes) {
|
|
4798
|
+
const { name, value, fullyReactive, reactive } = attribute;
|
|
4799
|
+
if (name.startsWith("on") || name.startsWith(":on")) continue;
|
|
4800
|
+
if (name.startsWith("&")) {
|
|
4801
|
+
context.report(`Bindings ("${name}") aren't supported on components in restricted mode.`, attribute.span.start, attribute.span.end);
|
|
4802
|
+
continue;
|
|
4803
|
+
}
|
|
4804
|
+
if (name.startsWith(":")) {
|
|
4805
|
+
context.report(`Directives ("${name}") aren't supported on components in restricted mode.`, attribute.span.start, attribute.span.end);
|
|
4806
|
+
continue;
|
|
4807
|
+
}
|
|
4808
|
+
if (value === void 0) {
|
|
4809
|
+
attributes.push({ name });
|
|
4810
|
+
continue;
|
|
4811
|
+
}
|
|
4812
|
+
if (fullyReactive) {
|
|
4813
|
+
const expr = parseExprAt(value, attribute.span.start, context);
|
|
4814
|
+
if (name === "class" && needsClass) {
|
|
4815
|
+
attributes.push({
|
|
4816
|
+
name,
|
|
4817
|
+
expr,
|
|
4818
|
+
scoped: `torp-${context.styleHash}`
|
|
4819
|
+
});
|
|
4820
|
+
needsClass = false;
|
|
4821
|
+
} else attributes.push({
|
|
4822
|
+
name,
|
|
4823
|
+
expr
|
|
4824
|
+
});
|
|
4825
|
+
} else if (reactive) context.report(`Mixed static/dynamic prop values aren't supported in restricted mode; compute the whole "${name}" value with an expression.`, attribute.span.start, attribute.span.end);
|
|
4826
|
+
else {
|
|
4827
|
+
const literal = trimQuotes(value);
|
|
4828
|
+
if (name === "class" && needsClass) {
|
|
4829
|
+
attributes.push({
|
|
4830
|
+
name,
|
|
4831
|
+
value: literal,
|
|
4832
|
+
scoped: `torp-${context.styleHash}`
|
|
4833
|
+
});
|
|
4834
|
+
needsClass = false;
|
|
4835
|
+
} else attributes.push({
|
|
4836
|
+
name,
|
|
4837
|
+
value: literal
|
|
4838
|
+
});
|
|
4839
|
+
}
|
|
4840
|
+
}
|
|
4841
|
+
return attributes;
|
|
4842
|
+
}
|
|
4843
|
+
/**
|
|
4844
|
+
* Component children are slot fills: loose children become the default fill
|
|
4845
|
+
* (`_`) and `<fill name="x">` children become named fills. Fill children may
|
|
4846
|
+
* read `$slot.<name>` for the slot props the host component passes; other
|
|
4847
|
+
* attributes on fills aren't supported.
|
|
4848
|
+
*/
|
|
4849
|
+
function serializeComponent(node, context) {
|
|
4850
|
+
const fills = [];
|
|
4851
|
+
const defaultFill = [];
|
|
4852
|
+
const fillContext = {
|
|
4853
|
+
...context,
|
|
4854
|
+
allowedRefs: /* @__PURE__ */ new Set([...context.allowedRefs, "$slot"]),
|
|
4855
|
+
elementStack: []
|
|
4856
|
+
};
|
|
4857
|
+
for (const child of node.children) if (isFill(child)) {
|
|
4858
|
+
if (child.attributes.filter((attribute) => attribute.name !== "name").length > 0) {
|
|
4859
|
+
context.report(`Unexpected attributes on <fill>. Slot props are read as $slot.<name> inside the fill; only "name" is allowed here.`, child.span.start, child.span.end);
|
|
4860
|
+
continue;
|
|
4861
|
+
}
|
|
4862
|
+
const nameAttribute = child.attributes.find((attribute) => attribute.name === "name");
|
|
4863
|
+
const name = nameAttribute ? trimQuotes(nameAttribute.value ?? "") || "_" : "_";
|
|
4864
|
+
fills.push({
|
|
4865
|
+
name,
|
|
4866
|
+
children: serializeChildren(child.children, fillContext)
|
|
4867
|
+
});
|
|
4868
|
+
} else if (isTextNode(child) && child.content.trim() === "") continue;
|
|
4869
|
+
else {
|
|
4870
|
+
const serialized = serializeNode(child, fillContext);
|
|
4871
|
+
if (serialized !== void 0) defaultFill.push(serialized);
|
|
4872
|
+
}
|
|
4873
|
+
if (defaultFill.length > 0) fills.unshift({
|
|
4874
|
+
name: "_",
|
|
4875
|
+
children: defaultFill
|
|
4876
|
+
});
|
|
4877
|
+
return {
|
|
4878
|
+
t: "component",
|
|
4879
|
+
name: node.tagName,
|
|
4880
|
+
props: serializeComponentProps(node, context),
|
|
4881
|
+
fills
|
|
4882
|
+
};
|
|
4883
|
+
}
|
|
4884
|
+
function isFill(node) {
|
|
4885
|
+
return isSpecialNode(node) && (node.tagName === "fill" || node.tagName === "filldef");
|
|
4886
|
+
}
|
|
4887
|
+
/** `<slot name="…">fallback</slot>` in a restricted template. Slot props
|
|
4888
|
+
* (`<slot item={row}/>` — anything but `name`) are evaluated in the
|
|
4889
|
+
* artifact's scope and passed to the incoming slot render, matching the JS
|
|
4890
|
+
* server build. */
|
|
4891
|
+
function serializeSlotElement(node, context) {
|
|
4892
|
+
const nameAttribute = node.attributes.find((attribute) => attribute.name === "name");
|
|
4893
|
+
const name = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
|
|
4894
|
+
const props = [];
|
|
4895
|
+
for (const attribute of node.attributes) {
|
|
4896
|
+
const { name: propName, value, fullyReactive, reactive } = attribute;
|
|
4897
|
+
if (propName === "name") continue;
|
|
4898
|
+
if (propName.startsWith("on") || propName.startsWith(":on")) continue;
|
|
4899
|
+
if (propName.startsWith("&")) {
|
|
4900
|
+
context.report(`Bindings ("${propName}") aren't supported on slot elements in restricted mode.`, attribute.span.start, attribute.span.end);
|
|
4901
|
+
continue;
|
|
4902
|
+
}
|
|
4903
|
+
if (propName.startsWith(":")) {
|
|
4904
|
+
context.report(`Directives ("${propName}") aren't supported on slot elements in restricted mode.`, attribute.span.start, attribute.span.end);
|
|
4905
|
+
continue;
|
|
4906
|
+
}
|
|
4907
|
+
if (value === void 0) {
|
|
4908
|
+
props.push({ name: propName });
|
|
4909
|
+
continue;
|
|
4910
|
+
}
|
|
4911
|
+
if (fullyReactive) props.push({
|
|
4912
|
+
name: propName,
|
|
4913
|
+
expr: parseExprAt(value, attribute.span.start, context)
|
|
4914
|
+
});
|
|
4915
|
+
else if (reactive) context.report(`Mixed static/dynamic slot prop values aren't supported in restricted mode; compute the whole "${propName}" value with an expression.`, attribute.span.start, attribute.span.end);
|
|
4916
|
+
else props.push({
|
|
4917
|
+
name: propName,
|
|
4918
|
+
value: trimQuotes(value)
|
|
4919
|
+
});
|
|
4920
|
+
}
|
|
4921
|
+
const autoClose = context.elementStack.filter((tag) => AUTO_CLOSEABLE.has(tag));
|
|
4922
|
+
const fallbackTag = firstFallbackTag(node.children);
|
|
4923
|
+
if (fallbackTag !== void 0 && closesAncestor(fallbackTag, context.elementStack)) {
|
|
4924
|
+
const ancestor = [...context.elementStack].reverse().find((ancestor) => closesAncestor(fallbackTag, [ancestor]));
|
|
4925
|
+
context.report(`Slot fallback starts with <${fallbackTag}>, which auto-closes the enclosing <${ancestor}>: ` + autoCloseMessage(fallbackTag, ancestor), node.span.start, node.span.end);
|
|
4926
|
+
}
|
|
4927
|
+
const children = [];
|
|
4928
|
+
for (const child of node.children) if (isFill(child)) children.push(...serializeChildren(child.children, context));
|
|
4929
|
+
else {
|
|
4930
|
+
const serialized = serializeNode(child, context);
|
|
4931
|
+
if (serialized !== void 0) children.push(serialized);
|
|
4932
|
+
}
|
|
4933
|
+
const slot = {
|
|
4934
|
+
t: "slot",
|
|
4935
|
+
name,
|
|
4936
|
+
props,
|
|
4937
|
+
children
|
|
4938
|
+
};
|
|
4939
|
+
if (autoClose.length > 0) slot.autoClose = autoClose;
|
|
4940
|
+
return slot;
|
|
4941
|
+
}
|
|
4942
|
+
/** The tag of the first meaningful child (skipping whitespace text). */
|
|
4943
|
+
function firstFallbackTag(children) {
|
|
4944
|
+
for (const child of children) {
|
|
4945
|
+
if (isFill(child)) return firstFallbackTag(child.children);
|
|
4946
|
+
if (isTextNode(child)) {
|
|
4947
|
+
if (child.content.trim() === "") continue;
|
|
4948
|
+
return;
|
|
4949
|
+
}
|
|
4950
|
+
if (child.type === "element") return child.tagName;
|
|
4951
|
+
return;
|
|
4952
|
+
}
|
|
4953
|
+
}
|
|
4954
|
+
function serializeElement(node, context) {
|
|
4955
|
+
if (node.type === "component") {
|
|
4956
|
+
context.report(`Nested components ("<${node.tagName}>") aren't supported in restricted mode yet. Inline the markup, or render it client-side.`, node.span.start, node.span.end);
|
|
4957
|
+
return;
|
|
4958
|
+
}
|
|
4959
|
+
if (node.type === "special") {
|
|
4960
|
+
context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
|
|
4961
|
+
return;
|
|
4962
|
+
}
|
|
4963
|
+
const childContext = node.tagName === "pre" || node.tagName === "code" ? {
|
|
4964
|
+
...context,
|
|
4965
|
+
preserveWhitespace: true
|
|
4966
|
+
} : context;
|
|
4967
|
+
if (!voidTags.includes(node.tagName)) childContext.elementStack.push(node.tagName);
|
|
4968
|
+
const children = voidTags.includes(node.tagName) ? [] : serializeChildren(node.children, childContext);
|
|
4969
|
+
if (!voidTags.includes(node.tagName)) childContext.elementStack.pop();
|
|
4970
|
+
return {
|
|
4971
|
+
t: "el",
|
|
4972
|
+
tag: node.tagName,
|
|
4973
|
+
attrs: serializeAttributes(node, context),
|
|
4974
|
+
children
|
|
4975
|
+
};
|
|
4976
|
+
}
|
|
4977
|
+
function serializeAttributes(node, context) {
|
|
4978
|
+
const attributes = [];
|
|
4979
|
+
let needsClass = node.scopeStyles === true && context.styleHash !== "";
|
|
4980
|
+
for (const attribute of node.attributes) {
|
|
4981
|
+
const { name, value, fullyReactive, reactive } = attribute;
|
|
4982
|
+
if (name === "self" && node.tagName === "@element") continue;
|
|
4983
|
+
if (name === "&ref") continue;
|
|
4984
|
+
if (name.startsWith("on") || name.startsWith(":on")) continue;
|
|
4985
|
+
if (name.startsWith("transition")) continue;
|
|
4986
|
+
if (name.startsWith("&")) {
|
|
4987
|
+
context.report(`Form bindings ("${name}") aren't supported in restricted mode yet; use ${name.substring(1)}={…} instead.`, attribute.span.start, attribute.span.end);
|
|
4988
|
+
continue;
|
|
4989
|
+
}
|
|
4990
|
+
if (name.startsWith(":")) {
|
|
4991
|
+
context.report(`Directives ("${name}") aren't supported in restricted mode yet.`, attribute.span.start, attribute.span.end);
|
|
4992
|
+
continue;
|
|
4993
|
+
}
|
|
4994
|
+
if (value === void 0) {
|
|
4995
|
+
if (name === "class" && needsClass) {
|
|
4996
|
+
attributes.push({
|
|
4997
|
+
name: "class",
|
|
4998
|
+
value: `torp-${context.styleHash}`
|
|
4999
|
+
});
|
|
5000
|
+
needsClass = false;
|
|
5001
|
+
} else attributes.push({ name });
|
|
5002
|
+
continue;
|
|
5003
|
+
}
|
|
5004
|
+
if (fullyReactive) {
|
|
5005
|
+
const expr = parseExprAt(value, attribute.span.start, context);
|
|
5006
|
+
if (name === "class") {
|
|
5007
|
+
attributes.push({
|
|
5008
|
+
name,
|
|
5009
|
+
expr,
|
|
5010
|
+
format: "class",
|
|
5011
|
+
scoped: needsClass ? `torp-${context.styleHash}` : void 0
|
|
5012
|
+
});
|
|
5013
|
+
needsClass = false;
|
|
5014
|
+
} else if (name === "style") attributes.push({
|
|
5015
|
+
name,
|
|
5016
|
+
expr,
|
|
5017
|
+
format: "style"
|
|
5018
|
+
});
|
|
5019
|
+
else attributes.push({
|
|
5020
|
+
name,
|
|
5021
|
+
expr,
|
|
5022
|
+
format: "attr"
|
|
5023
|
+
});
|
|
5024
|
+
} else if (reactive) context.report(`Mixed static/dynamic attribute values aren't supported in restricted mode; compute the whole "${name}" value with an expression.`, attribute.span.start, attribute.span.end);
|
|
5025
|
+
else {
|
|
5026
|
+
let literal = trimQuotes(value);
|
|
5027
|
+
if (name === "class" && needsClass) {
|
|
5028
|
+
literal = literal ? `${literal} torp-${context.styleHash}` : `torp-${context.styleHash}`;
|
|
5029
|
+
needsClass = false;
|
|
5030
|
+
}
|
|
5031
|
+
attributes.push({
|
|
5032
|
+
name,
|
|
5033
|
+
value: literal
|
|
5034
|
+
});
|
|
5035
|
+
}
|
|
5036
|
+
}
|
|
5037
|
+
if (needsClass) attributes.push({
|
|
5038
|
+
name: "class",
|
|
5039
|
+
value: `torp-${context.styleHash}`
|
|
5040
|
+
});
|
|
5041
|
+
return attributes;
|
|
5042
|
+
}
|
|
5043
|
+
function serializeText(node, context) {
|
|
5044
|
+
const parts = [];
|
|
5045
|
+
const pushLiteral = (literal) => {
|
|
5046
|
+
const collapsed = context.preserveWhitespace ? literal : literal.replace(/\s+/g, " ");
|
|
5047
|
+
if (collapsed.length === 0) return;
|
|
5048
|
+
const last = parts[parts.length - 1];
|
|
5049
|
+
if (typeof last === "string") parts[parts.length - 1] = last + collapsed;
|
|
5050
|
+
else parts.push(collapsed);
|
|
5051
|
+
};
|
|
5052
|
+
if (node.spans.length === 0 || node.start === void 0) pushLiteral(node.content);
|
|
5053
|
+
else {
|
|
5054
|
+
const start = node.start;
|
|
5055
|
+
let cursor = 0;
|
|
5056
|
+
for (const span of node.spans) {
|
|
5057
|
+
const literalEnd = span.start - start - 1;
|
|
5058
|
+
pushLiteral(node.content.substring(cursor, literalEnd));
|
|
5059
|
+
parts.push(parseExprAt(context.source.substring(span.start, span.end), span.start, context));
|
|
5060
|
+
cursor = span.end - start + 1;
|
|
5061
|
+
}
|
|
5062
|
+
pushLiteral(node.content.substring(cursor));
|
|
5063
|
+
}
|
|
5064
|
+
if (parts.length === 0) return void 0;
|
|
5065
|
+
return {
|
|
5066
|
+
t: "text",
|
|
5067
|
+
parts
|
|
5068
|
+
};
|
|
5069
|
+
}
|
|
5070
|
+
function serializeControl(node, context) {
|
|
5071
|
+
if (node.operation === "@if group") return {
|
|
5072
|
+
t: "if",
|
|
5073
|
+
branches: node.children.filter(isControlNode).map((branch) => {
|
|
5074
|
+
if (branch.operation === "@else") return { children: serializeChildren(branch.children, context) };
|
|
5075
|
+
const statement = branch.statement;
|
|
5076
|
+
const open = statement.indexOf("(");
|
|
5077
|
+
if (open === -1) {
|
|
5078
|
+
context.report(`Malformed ${branch.operation} statement.`, branch.span.start, branch.span.end);
|
|
5079
|
+
return {
|
|
5080
|
+
test: {
|
|
5081
|
+
op: "lit",
|
|
5082
|
+
value: null
|
|
5083
|
+
},
|
|
5084
|
+
children: []
|
|
5085
|
+
};
|
|
5086
|
+
}
|
|
5087
|
+
const { inner, innerStart } = extractBalanced(statement, open, branch, context);
|
|
5088
|
+
return {
|
|
5089
|
+
test: parseExprAt(inner, branch.span.start + innerStart, context),
|
|
5090
|
+
children: serializeChildren(branch.children, context)
|
|
5091
|
+
};
|
|
5092
|
+
})
|
|
5093
|
+
};
|
|
5094
|
+
if (node.operation === "@for group") {
|
|
5095
|
+
const forNode = node.children.find((child) => isControlNode(child) && child.operation === "@for");
|
|
5096
|
+
if (!forNode) {
|
|
5097
|
+
context.report("Malformed @for block.", node.span.start, node.span.end);
|
|
5098
|
+
return;
|
|
5099
|
+
}
|
|
5100
|
+
const open = forNode.statement.indexOf("(");
|
|
5101
|
+
if (open === -1) {
|
|
5102
|
+
context.report("Malformed @for statement.", forNode.span.start, forNode.span.end);
|
|
5103
|
+
return;
|
|
5104
|
+
}
|
|
5105
|
+
const { inner, innerStart } = extractBalanced(forNode.statement, open, forNode, context);
|
|
5106
|
+
const match = /^\s*(?:(?:let|const|var)\s+)?([A-Za-z_$][\w$]*)\s+(of|in)\s+([\s\S]+)$/.exec(inner);
|
|
5107
|
+
if (!match) {
|
|
5108
|
+
context.report("Only `@for (item of list)` is supported in restricted mode yet (no destructuring, index variables, or C-style loops).", forNode.span.start, forNode.span.end);
|
|
5109
|
+
return;
|
|
5110
|
+
}
|
|
5111
|
+
if (match[2] === "in") {
|
|
5112
|
+
context.report("`in` loops aren't supported in restricted mode; use `of`.", forNode.span.start, forNode.span.end);
|
|
5113
|
+
return;
|
|
5114
|
+
}
|
|
5115
|
+
const item = match[1];
|
|
5116
|
+
const listSource = match[3].trim();
|
|
5117
|
+
const listIndex = inner.lastIndexOf(listSource);
|
|
5118
|
+
const list = parseExprAt(listSource, forNode.span.start + innerStart + listIndex, context);
|
|
5119
|
+
const keyNode = forNode.children.find((child) => isControlNode(child) && child.operation === "@key");
|
|
5120
|
+
let key;
|
|
5121
|
+
if (keyNode) {
|
|
5122
|
+
const keyContext = {
|
|
5123
|
+
...context,
|
|
5124
|
+
loopVars: [...context.loopVars, item]
|
|
5125
|
+
};
|
|
5126
|
+
const equal = keyNode.statement.indexOf("=");
|
|
5127
|
+
const keySource = keyNode.statement.substring(equal + 1).replace(/;\s*$/, "").trim();
|
|
5128
|
+
key = parseExprAt(keySource, keyNode.span.start + keyNode.statement.indexOf(keySource), keyContext);
|
|
5129
|
+
}
|
|
5130
|
+
const childContext = {
|
|
5131
|
+
...context,
|
|
5132
|
+
loopVars: [...context.loopVars, item]
|
|
5133
|
+
};
|
|
5134
|
+
return {
|
|
5135
|
+
t: "for",
|
|
5136
|
+
item,
|
|
5137
|
+
list,
|
|
5138
|
+
key,
|
|
5139
|
+
children: serializeChildren(forNode.children.filter((child) => !(isControlNode(child) && child.operation === "@key")), childContext)
|
|
5140
|
+
};
|
|
5141
|
+
}
|
|
5142
|
+
context.report(`"${node.operation}" isn't supported in restricted mode yet.`, controlSpan(node).start, controlSpan(node).end);
|
|
5143
|
+
}
|
|
5144
|
+
/** Group nodes (`@if group`, `@html group`…) carry zero spans; their first
|
|
5145
|
+
* control child has the real source span. */
|
|
5146
|
+
function controlSpan(node) {
|
|
5147
|
+
if (node.span.start === 0 && node.span.end === 0) {
|
|
5148
|
+
const child = node.children.find(isControlNode);
|
|
5149
|
+
if (child) return child.span;
|
|
5150
|
+
}
|
|
5151
|
+
return node.span;
|
|
5152
|
+
}
|
|
5153
|
+
/**
|
|
5154
|
+
* Extracts the text between `source[open]` and its matching `)`, skipping
|
|
5155
|
+
* strings and comments. `innerStart` is the index just after the `(`.
|
|
5156
|
+
*/
|
|
5157
|
+
function extractBalanced(source, open, node, context) {
|
|
5158
|
+
let level = 0;
|
|
5159
|
+
for (let i = open; i < source.length; i++) {
|
|
5160
|
+
const skipped = skipStringOrComment(source, i);
|
|
5161
|
+
if (skipped !== -1) {
|
|
5162
|
+
i = skipped - 1;
|
|
5163
|
+
continue;
|
|
5164
|
+
}
|
|
5165
|
+
if (source[i] === "(") level += 1;
|
|
5166
|
+
else if (source[i] === ")") {
|
|
5167
|
+
level -= 1;
|
|
5168
|
+
if (level === 0) return {
|
|
5169
|
+
inner: source.substring(open + 1, i),
|
|
5170
|
+
innerStart: open + 1
|
|
5171
|
+
};
|
|
5172
|
+
}
|
|
5173
|
+
}
|
|
5174
|
+
context.report("Unbalanced parentheses in a control statement.", node.span.start, node.span.end);
|
|
5175
|
+
return {
|
|
5176
|
+
inner: source.substring(open + 1),
|
|
5177
|
+
innerStart: open + 1
|
|
5178
|
+
};
|
|
5179
|
+
}
|
|
5180
|
+
function parseExprAt(source, offset, context) {
|
|
5181
|
+
try {
|
|
5182
|
+
const expr = parseExpression(source, offset);
|
|
5183
|
+
validateRefs(expr, context.allowedRefs, context, offset, "template");
|
|
5184
|
+
return expr;
|
|
5185
|
+
} catch (error) {
|
|
5186
|
+
if (error instanceof RestrictedSyntaxError) {
|
|
5187
|
+
context.report(error.message, error.start, error.end);
|
|
5188
|
+
return {
|
|
5189
|
+
op: "lit",
|
|
5190
|
+
value: null
|
|
5191
|
+
};
|
|
5192
|
+
}
|
|
5193
|
+
throw error;
|
|
5194
|
+
}
|
|
5195
|
+
}
|
|
5196
|
+
/**
|
|
5197
|
+
* Validates that every identifier reference in a serialized expression is
|
|
5198
|
+
* available in the scope the interpreter will run it with -- so typos and
|
|
5199
|
+
* unknown roots are compile errors instead of render errors.
|
|
5200
|
+
*/
|
|
5201
|
+
function validateRefs(expr, allowed, context, start, where, loopVars = context.loopVars) {
|
|
5202
|
+
switch (expr.op) {
|
|
5203
|
+
case "ref":
|
|
5204
|
+
if (!allowed.has(expr.name) && !loopVars.includes(expr.name)) {
|
|
5205
|
+
const available = [...allowed, ...loopVars].join(", ");
|
|
5206
|
+
context.report(`Unknown identifier "${expr.name}" in ${where}. Available: ${available || "(none)"}.`, start, start + expr.name.length + 2);
|
|
5207
|
+
}
|
|
5208
|
+
return;
|
|
5209
|
+
case "get":
|
|
5210
|
+
validateRefs(expr.object, allowed, context, start, where, loopVars);
|
|
5211
|
+
return;
|
|
5212
|
+
case "index":
|
|
5213
|
+
validateRefs(expr.object, allowed, context, start, where, loopVars);
|
|
5214
|
+
validateRefs(expr.index, allowed, context, start, where, loopVars);
|
|
5215
|
+
return;
|
|
5216
|
+
case "unary":
|
|
5217
|
+
validateRefs(expr.operand, allowed, context, start, where, loopVars);
|
|
5218
|
+
return;
|
|
5219
|
+
case "binary":
|
|
5220
|
+
validateRefs(expr.left, allowed, context, start, where, loopVars);
|
|
5221
|
+
validateRefs(expr.right, allowed, context, start, where, loopVars);
|
|
5222
|
+
return;
|
|
5223
|
+
case "ternary":
|
|
5224
|
+
validateRefs(expr.test, allowed, context, start, where, loopVars);
|
|
5225
|
+
validateRefs(expr.consequent, allowed, context, start, where, loopVars);
|
|
5226
|
+
validateRefs(expr.alternate, allowed, context, start, where, loopVars);
|
|
5227
|
+
return;
|
|
5228
|
+
case "array":
|
|
5229
|
+
for (const item of expr.items) validateRefs(item, allowed, context, start, where, loopVars);
|
|
5230
|
+
return;
|
|
5231
|
+
case "object":
|
|
5232
|
+
for (const value of Object.values(expr.entries)) validateRefs(value, allowed, context, start, where, loopVars);
|
|
5233
|
+
return;
|
|
5234
|
+
}
|
|
5235
|
+
}
|
|
3846
5236
|
//#endregion
|
|
3847
5237
|
//#region src/compile/buildType.ts
|
|
3848
5238
|
/**
|
|
@@ -4236,12 +5626,14 @@ function parseText(status, element) {
|
|
|
4236
5626
|
if (content || spaceContent) {
|
|
4237
5627
|
const previousNode = element.children[element.children.length - 1];
|
|
4238
5628
|
if (previousNode && isTextNode(previousNode)) {
|
|
5629
|
+
if (previousNode.start === void 0) previousNode.start = start - previousNode.content.length;
|
|
4239
5630
|
previousNode.content += content + spaceContent;
|
|
4240
5631
|
previousNode.spans.push(...spans);
|
|
4241
5632
|
} else {
|
|
4242
5633
|
const text = {
|
|
4243
5634
|
type: "text",
|
|
4244
5635
|
content: content + spaceContent,
|
|
5636
|
+
start,
|
|
4245
5637
|
spans
|
|
4246
5638
|
};
|
|
4247
5639
|
element.children.push(text);
|
|
@@ -4522,6 +5914,10 @@ function parseControlOpen(status) {
|
|
|
4522
5914
|
if (operation === "@replace" || operation === "@html") statement = trimMatched(statement.substring(statement.indexOf("(")).trim(), "(", ")");
|
|
4523
5915
|
if (operation === "@await" && /^await\s*\(/.test(statement)) addError(status, "old `@await (expr) { … } then (…) { … }` syntax is removed — use `@await { … } with { … }` with `$async` getters", start, status.i);
|
|
4524
5916
|
} else {
|
|
5917
|
+
if (/^@[a-zA-Z]+</.test(operation)) {
|
|
5918
|
+
addError(status, `Unknown operation: ${operation}. A literal '@' in text must be escaped as '@'`, start, status.i);
|
|
5919
|
+
return null;
|
|
5920
|
+
}
|
|
4525
5921
|
addError(status, `Unknown operation: ${operation}`, status.i, status.i + operation.length);
|
|
4526
5922
|
return null;
|
|
4527
5923
|
}
|
|
@@ -5318,39 +6714,6 @@ function getPropsUsage(source, ranges) {
|
|
|
5318
6714
|
}
|
|
5319
6715
|
return props.length ? props : void 0;
|
|
5320
6716
|
}
|
|
5321
|
-
/**
|
|
5322
|
-
* Gets the `$context` names that the compiled output references. The input is
|
|
5323
|
-
* the component's code-only text (script plus markup expressions), with
|
|
5324
|
-
* `ranges` marking the positions that are code — matches that start inside a
|
|
5325
|
-
* string, comment or regex literal are ignored, so mentions inside
|
|
5326
|
-
* sample-code strings or prose don't count.
|
|
5327
|
-
*/
|
|
5328
|
-
function getContextUsage(source, ranges) {
|
|
5329
|
-
const contextsMatches = source.matchAll(/\$context\??\s*(?:\.([\d\w]+)|\[([^\]]+)\])/g);
|
|
5330
|
-
const contexts = [];
|
|
5331
|
-
for (let match of contextsMatches) {
|
|
5332
|
-
if (!isInCode(ranges, match.index)) continue;
|
|
5333
|
-
const name = trimQuotes(match[1] || match[2]);
|
|
5334
|
-
if (!contexts.includes(name)) contexts.push(name);
|
|
5335
|
-
}
|
|
5336
|
-
if (!contexts.length) for (let match of source.matchAll(/(?<![\w$])\$context(?![\w])(?!\s*:)(?!<)/g)) {
|
|
5337
|
-
if (!isInCode(ranges, match.index)) continue;
|
|
5338
|
-
contexts.push("$context");
|
|
5339
|
-
break;
|
|
5340
|
-
}
|
|
5341
|
-
return contexts.length ? contexts : void 0;
|
|
5342
|
-
}
|
|
5343
|
-
/**
|
|
5344
|
-
* Returns true if `index` falls inside one of the (sorted, non-overlapping)
|
|
5345
|
-
* code ranges — i.e. not inside a string, comment or regex literal.
|
|
5346
|
-
*/
|
|
5347
|
-
function isInCode(ranges, index) {
|
|
5348
|
-
for (const [start, end] of ranges) {
|
|
5349
|
-
if (index >= start && index < end) return true;
|
|
5350
|
-
if (index < start) return false;
|
|
5351
|
-
}
|
|
5352
|
-
return false;
|
|
5353
|
-
}
|
|
5354
6717
|
function consumeScriptComments(status) {
|
|
5355
6718
|
const skipped = skipStringOrComment(status.source, status.i);
|
|
5356
6719
|
if (skipped !== -1) {
|
|
@@ -5373,6 +6736,27 @@ function parse(source) {
|
|
|
5373
6736
|
return parseCode(source);
|
|
5374
6737
|
}
|
|
5375
6738
|
//#endregion
|
|
5376
|
-
|
|
6739
|
+
//#region src/compile/parse/bindDataTemplate.ts
|
|
6740
|
+
/**
|
|
6741
|
+
* Binds `$data` in a parsed template whose requirements come from an app
|
|
6742
|
+
* manifest (see `@torpor/embed/app`): inserts the `let $data = …` chunk
|
|
6743
|
+
* after the start-marker chunk and keeps `$props` from being renamed as an
|
|
6744
|
+
* unused param. Without it, builds reference an undeclared `$data`.
|
|
6745
|
+
*/
|
|
6746
|
+
function bindDataTemplate(template) {
|
|
6747
|
+
for (let i = 0; i < template.script.length; i++) if (template.script[i].script === "/* @start */") {
|
|
6748
|
+
template.script.splice(i + 1, 0, {
|
|
6749
|
+
script: " let $data = $props?.$data ?? {};",
|
|
6750
|
+
span: {
|
|
6751
|
+
start: 0,
|
|
6752
|
+
end: 0
|
|
6753
|
+
}
|
|
6754
|
+
});
|
|
6755
|
+
i += 1;
|
|
6756
|
+
}
|
|
6757
|
+
for (const component of template.components) if (!component.props?.length) component.props = ["$data"];
|
|
6758
|
+
}
|
|
6759
|
+
//#endregion
|
|
6760
|
+
export { RestrictedSyntaxError, bindDataTemplate, build, buildRestricted, buildType, parse, parseExpressionPrefix };
|
|
5377
6761
|
|
|
5378
6762
|
//# sourceMappingURL=compile.mjs.map
|