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