@rohal12/spindle 0.62.8 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3715,10 +3715,10 @@ function parameterError(macro, param, problem, fix) {
3715
3715
  var metadataRegistry = new NameMap();
3716
3716
  /** Indexed at registration, so parsing each tag does not scan every macro. */
3717
3717
  var companionParents = new NameMap();
3718
- /** The parents declaring a branching companion (listbox options are values). */
3718
+ /** The parents declaring a branching companion (input options are values). */
3719
3719
  function branchParents(name, macros) {
3720
- if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox");
3721
- return effectiveNamedDefinitions(macros).filter((macro) => macro.name.toLowerCase() !== "listbox" && macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase())).map((macro) => macro.name.toLowerCase());
3720
+ if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox" && parent !== "cycle");
3721
+ return effectiveNamedDefinitions(macros).filter((macro) => macro.name.toLowerCase() !== "listbox" && macro.name.toLowerCase() !== "cycle" && macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase())).map((macro) => macro.name.toLowerCase());
3722
3722
  }
3723
3723
  /** The declared parameters of the macro `name`, if it declares any. */
3724
3724
  function getMacroParameters(name) {
@@ -3753,14 +3753,16 @@ var BLOCK_MACROS = new NameSet([
3753
3753
  ]);
3754
3754
  /**
3755
3755
  * The block widgets (those whose body renders `{@children}`), kept apart from
3756
- * BLOCK_MACROS: a widget is redefined, so it is a block only while its latest
3757
- * definition is, whereas the macros in BLOCK_MACROS stay blocks.
3756
+ * built-in defaults: a widget is a block only while its latest definition is.
3758
3757
  */
3759
3758
  var BLOCK_WIDGETS = new NameSet();
3760
3759
  /** All widgets, including inline ones, override built-in parsing semantics. */
3761
3760
  var WIDGETS = new NameSet();
3762
3761
  /** Classification owned by defineMacro, independent of explicit registrations. */
3763
3762
  var DEFINED_BLOCK_MACROS = new NameSet();
3763
+ var DEFINED_MACROS = new NameSet();
3764
+ /** Explicit registrations remain independent of macro/widget replacements. */
3765
+ var REGISTERED_BLOCK_MACROS = new NameSet();
3764
3766
  /** Macros whose body is JavaScript source, kept verbatim. */
3765
3767
  var RAW_BODY_MACROS = /* @__PURE__ */ new Set(["do"]);
3766
3768
  /** Whether a macro's body is JavaScript, kept verbatim (`{do}`). */
@@ -3769,7 +3771,14 @@ function isRawMacro(name, widget = WIDGETS.has(name)) {
3769
3771
  }
3770
3772
  /** Whether a macro takes a body closed by `{/name}`. */
3771
3773
  function isBlockMacro(name) {
3772
- return BLOCK_MACROS.has(name) || DEFINED_BLOCK_MACROS.has(name) || BLOCK_WIDGETS.has(name);
3774
+ if (REGISTERED_BLOCK_MACROS.has(name)) return true;
3775
+ if (WIDGETS.has(name)) return BLOCK_WIDGETS.has(name);
3776
+ if (DEFINED_MACROS.has(name)) return DEFINED_BLOCK_MACROS.has(name);
3777
+ return BLOCK_MACROS.has(name);
3778
+ }
3779
+ /** Explicit parser registrations, unaffected by effective tooling metadata. */
3780
+ function isRegisteredBlockMacro(name) {
3781
+ return REGISTERED_BLOCK_MACROS.has(name);
3773
3782
  }
3774
3783
  /** Macros whose branches render as one: the node holds one per branch. */
3775
3784
  var BRANCHING = /* @__PURE__ */ new Set([
@@ -3894,6 +3903,8 @@ function sourcePositions(text) {
3894
3903
  * runtime reads it, or, when it matches one further out, closes that one and
3895
3904
  * what was open inside it stays unclosed.
3896
3905
  */
3906
+ /** Keep AST construction and recursive rendering within a safe call depth. */
3907
+ var MAX_MARKUP_DEPTH = 256;
3897
3908
  /** The last of `items`. */
3898
3909
  var last$1 = (items) => items[items.length - 1];
3899
3910
  /** The macro each branch macro belongs to. */
@@ -4031,6 +4042,10 @@ function pairMarkup(tokens, options = {}) {
4031
4042
  add(node);
4032
4043
  continue;
4033
4044
  }
4045
+ if (stack.length === MAX_MARKUP_DEPTH) report("nesting-limit", token, `Markup nesting exceeds the limit of ${MAX_MARKUP_DEPTH} elements`, token.start, {
4046
+ name: nameOf(token),
4047
+ limit: String(MAX_MARKUP_DEPTH)
4048
+ });
4034
4049
  const body = {
4035
4050
  children: [],
4036
4051
  branches: []
@@ -9616,6 +9631,29 @@ function parseMemberIdentifier(src) {
9616
9631
  if (object.type !== "Identifier" || object.start !== 0 || object.end !== 1 || property.type !== "Identifier" || property.start !== 2 || property.end !== src.length + 2) return null;
9617
9632
  return property.name;
9618
9633
  }
9634
+ /** Read the contiguous dot members after a variable, keeping decoded names. */
9635
+ function readMemberPath(src, end) {
9636
+ const path = [];
9637
+ const p = tokenizerAt(src, end, "expression", { afterOperand: true });
9638
+ try {
9639
+ for (;;) {
9640
+ p.nextToken();
9641
+ if (p.type !== types$1.dot || p.start !== end) break;
9642
+ const dotEnd = p.end;
9643
+ p.nextToken();
9644
+ if (p.start !== dotEnd || p.type !== types$1.name && !p.type.keyword) break;
9645
+ if (!/^\w+$/.test(String(p.value))) break;
9646
+ path.push(String(p.value));
9647
+ end = p.end;
9648
+ }
9649
+ } catch (error) {
9650
+ if (!(error instanceof SyntaxError)) throw error;
9651
+ }
9652
+ return {
9653
+ path,
9654
+ end
9655
+ };
9656
+ }
9619
9657
  /**
9620
9658
  * Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
9621
9659
  * noting where it read a transient in `transientsRead`.
@@ -9661,118 +9699,144 @@ function propertyName(node, src) {
9661
9699
  * identifiers here are declared (a `let`, a parameter), where a sigil
9662
9700
  * variable can't be. `shorthand`: the node is a shorthand property's value.
9663
9701
  */
9664
- function walk(node, src, out, binding, shorthand, access = "read") {
9665
- if (Array.isArray(node)) {
9666
- for (const n of node) walk(n, src, out, binding, false, access);
9667
- return;
9668
- }
9669
- if (!isNode(node)) return;
9670
- const sub = (child, bind = false, short = false, role = "read") => walk(child, src, out, bind, short, role);
9671
- switch (node.type) {
9672
- case "Identifier": {
9673
- const sigil = sigilOf(node, src);
9674
- if (!sigil) return;
9675
- if (binding) throw new CodeSyntaxError(`"${node.name}" is a ${NAMESPACE_NAME[sigil[0]]} variable and can't be declared`, src, node.start);
9676
- out.refs.push({
9677
- sigil: sigil[0],
9678
- name: sigil[1],
9679
- start: node.start,
9680
- end: node.end,
9681
- shorthand,
9682
- read: access !== "write",
9683
- write: access !== "read"
9684
- });
9702
+ function walk(root, src, out, binding, shorthand, access = "read") {
9703
+ const pending = [[
9704
+ root,
9705
+ binding,
9706
+ shorthand,
9707
+ access
9708
+ ]];
9709
+ while (pending.length) {
9710
+ const [node, bind, short, role] = pending.pop();
9711
+ const children = [];
9712
+ visit(node, bind, short, role, children);
9713
+ for (let i = children.length - 1; i >= 0; i--) pending.push(children[i]);
9714
+ }
9715
+ function visit(node, binding, shorthand, access, children) {
9716
+ if (Array.isArray(node)) {
9717
+ for (const n of node) children.push([
9718
+ n,
9719
+ binding,
9720
+ false,
9721
+ access
9722
+ ]);
9685
9723
  return;
9686
9724
  }
9687
- case "Literal":
9688
- if (typeof node.value === "string") out.strings.push(src.slice(node.start + 1, node.end - 1));
9689
- return;
9690
- case "TemplateElement":
9691
- out.strings.push(node.value.raw);
9692
- return;
9693
- case "MemberExpression":
9694
- sub(node.object);
9695
- if (node.computed) sub(node.property);
9696
- else propertyName(node.property, src);
9697
- return;
9698
- case "Property":
9699
- if (node.computed) sub(node.key);
9700
- else if (!node.shorthand) propertyName(node.key, src);
9701
- if (node.shorthand) {
9702
- const value = node.value;
9703
- if (value.type === "AssignmentPattern") {
9704
- sub(value.left, binding, true, access);
9705
- sub(value.right);
9706
- } else sub(value, binding, true, access);
9707
- } else sub(node.value, binding, false, access);
9708
- return;
9709
- case "MethodDefinition":
9710
- case "PropertyDefinition":
9711
- if (node.computed) sub(node.key);
9712
- else propertyName(node.key, src);
9713
- sub(node.value);
9714
- return;
9715
- case "LabeledStatement":
9716
- sub(node.body);
9717
- return;
9718
- case "BreakStatement":
9719
- case "ContinueStatement":
9720
- case "MetaProperty":
9721
- case "PrivateIdentifier": return;
9722
- case "VariableDeclarator":
9723
- sub(node.id, true);
9724
- sub(node.init);
9725
- return;
9726
- case "FunctionDeclaration":
9727
- case "FunctionExpression":
9728
- case "ArrowFunctionExpression":
9729
- sub(node.id, true);
9730
- for (const p of node.params) sub(p, true);
9731
- sub(node.body);
9732
- return;
9733
- case "ClassDeclaration":
9734
- case "ClassExpression":
9735
- sub(node.id, true);
9736
- sub(node.superClass);
9737
- sub(node.body);
9738
- return;
9739
- case "CatchClause":
9740
- sub(node.param, true);
9741
- sub(node.body);
9742
- return;
9743
- case "AssignmentExpression":
9744
- sub(node.left, false, false, node.operator === "=" ? "write" : "readwrite");
9745
- sub(node.right);
9746
- return;
9747
- case "UnaryExpression":
9748
- sub(node.argument, false, false, node.operator === "delete" ? "write" : "read");
9749
- return;
9750
- case "UpdateExpression":
9751
- sub(node.argument, false, false, "readwrite");
9752
- return;
9753
- case "ForInStatement":
9754
- case "ForOfStatement":
9755
- sub(node.left, false, false, "write");
9756
- sub(node.right);
9757
- sub(node.body);
9758
- return;
9759
- case "AssignmentPattern":
9760
- sub(node.left, binding, false, access);
9761
- sub(node.right);
9762
- return;
9763
- case "ObjectPattern":
9764
- case "ArrayPattern":
9765
- case "RestElement":
9766
- for (const key of [
9767
- "properties",
9768
- "elements",
9769
- "argument"
9770
- ]) sub(node[key], binding, false, access);
9771
- return;
9772
- default: for (const key in node) {
9773
- if (key === "type" || key === "start" || key === "end") continue;
9774
- const v = node[key];
9775
- if (typeof v === "object" && v !== null) sub(v);
9725
+ if (!isNode(node)) return;
9726
+ const sub = (child, bind = false, short = false, role = "read") => {
9727
+ children.push([
9728
+ child,
9729
+ bind,
9730
+ short,
9731
+ role
9732
+ ]);
9733
+ };
9734
+ switch (node.type) {
9735
+ case "Identifier": {
9736
+ const sigil = sigilOf(node, src);
9737
+ if (!sigil) return;
9738
+ if (binding) throw new CodeSyntaxError(`"${node.name}" is a ${NAMESPACE_NAME[sigil[0]]} variable and can't be declared`, src, node.start);
9739
+ out.refs.push({
9740
+ sigil: sigil[0],
9741
+ name: sigil[1],
9742
+ start: node.start,
9743
+ end: node.end,
9744
+ shorthand,
9745
+ read: access !== "write",
9746
+ write: access !== "read"
9747
+ });
9748
+ return;
9749
+ }
9750
+ case "Literal":
9751
+ if (typeof node.value === "string") out.strings.push(src.slice(node.start + 1, node.end - 1));
9752
+ return;
9753
+ case "TemplateElement":
9754
+ out.strings.push(node.value.raw);
9755
+ return;
9756
+ case "MemberExpression":
9757
+ sub(node.object);
9758
+ if (node.computed) sub(node.property);
9759
+ else propertyName(node.property, src);
9760
+ return;
9761
+ case "Property":
9762
+ if (node.computed) sub(node.key);
9763
+ else if (!node.shorthand) propertyName(node.key, src);
9764
+ if (node.shorthand) {
9765
+ const value = node.value;
9766
+ if (value.type === "AssignmentPattern") {
9767
+ sub(value.left, binding, true, access);
9768
+ sub(value.right);
9769
+ } else sub(value, binding, true, access);
9770
+ } else sub(node.value, binding, false, access);
9771
+ return;
9772
+ case "MethodDefinition":
9773
+ case "PropertyDefinition":
9774
+ if (node.computed) sub(node.key);
9775
+ else propertyName(node.key, src);
9776
+ sub(node.value);
9777
+ return;
9778
+ case "LabeledStatement":
9779
+ sub(node.body);
9780
+ return;
9781
+ case "BreakStatement":
9782
+ case "ContinueStatement":
9783
+ case "MetaProperty":
9784
+ case "PrivateIdentifier": return;
9785
+ case "VariableDeclarator":
9786
+ sub(node.id, true);
9787
+ sub(node.init);
9788
+ return;
9789
+ case "FunctionDeclaration":
9790
+ case "FunctionExpression":
9791
+ case "ArrowFunctionExpression":
9792
+ sub(node.id, true);
9793
+ for (const p of node.params) sub(p, true);
9794
+ sub(node.body);
9795
+ return;
9796
+ case "ClassDeclaration":
9797
+ case "ClassExpression":
9798
+ sub(node.id, true);
9799
+ sub(node.superClass);
9800
+ sub(node.body);
9801
+ return;
9802
+ case "CatchClause":
9803
+ sub(node.param, true);
9804
+ sub(node.body);
9805
+ return;
9806
+ case "AssignmentExpression":
9807
+ sub(node.left, false, false, node.operator === "=" ? "write" : "readwrite");
9808
+ sub(node.right);
9809
+ return;
9810
+ case "UnaryExpression":
9811
+ sub(node.argument, false, false, node.operator === "delete" ? "write" : "read");
9812
+ return;
9813
+ case "UpdateExpression":
9814
+ sub(node.argument, false, false, "readwrite");
9815
+ return;
9816
+ case "ForInStatement":
9817
+ case "ForOfStatement":
9818
+ sub(node.left, false, false, "write");
9819
+ sub(node.right);
9820
+ sub(node.body);
9821
+ return;
9822
+ case "AssignmentPattern":
9823
+ sub(node.left, binding, false, access);
9824
+ sub(node.right);
9825
+ return;
9826
+ case "ObjectPattern":
9827
+ case "ArrayPattern":
9828
+ case "RestElement":
9829
+ for (const key of [
9830
+ "properties",
9831
+ "elements",
9832
+ "argument"
9833
+ ]) sub(node[key], binding, false, access);
9834
+ return;
9835
+ default: for (const key in node) {
9836
+ if (key === "type" || key === "start" || key === "end") continue;
9837
+ const v = node[key];
9838
+ if (typeof v === "object" && v !== null) sub(v);
9839
+ }
9776
9840
  }
9777
9841
  }
9778
9842
  }
@@ -10542,7 +10606,7 @@ function scanMarkupTolerant(source, options = {}, completion = false) {
10542
10606
  const rest = source.slice(base);
10543
10607
  const result = attempt(rest, base);
10544
10608
  if (Array.isArray(result)) {
10545
- tokens.push(...result);
10609
+ for (const token of result) tokens.push(token);
10546
10610
  break;
10547
10611
  }
10548
10612
  const at = base + result.offset;
@@ -10555,7 +10619,7 @@ function scanMarkupTolerant(source, options = {}, completion = false) {
10555
10619
  cut = prefix.offset;
10556
10620
  prefix = attempt(rest.slice(0, cut), base);
10557
10621
  }
10558
- tokens.push(...prefix);
10622
+ for (const token of prefix) tokens.push(token);
10559
10623
  damage.push(base + cut);
10560
10624
  if (cut < rest.length) {
10561
10625
  const start = base + cut;
@@ -11267,6 +11331,27 @@ function subMacroParameters(name) {
11267
11331
  return SUB_MACRO_PARAMETERS.get(name.toLowerCase());
11268
11332
  }
11269
11333
  //#endregion
11334
+ //#region src/markup/expansion-budget.ts
11335
+ var _MarkupExpansionBudget;
11336
+ /** Shared bounds for reparsing markup inside labels, selectors and attributes. */
11337
+ var MarkupExpansionBudget = class MarkupExpansionBudget {
11338
+ constructor(sourceLength) {
11339
+ this.depth = 0;
11340
+ this.remaining = Math.max(65536, sourceLength * 8);
11341
+ }
11342
+ enter(length) {
11343
+ if (this.depth >= MarkupExpansionBudget.maxDepth || length > this.remaining) return false;
11344
+ this.remaining -= length;
11345
+ this.depth++;
11346
+ return true;
11347
+ }
11348
+ leave() {
11349
+ this.depth--;
11350
+ }
11351
+ };
11352
+ _MarkupExpansionBudget = MarkupExpansionBudget;
11353
+ _MarkupExpansionBudget.maxDepth = 64;
11354
+ //#endregion
11270
11355
  //#region src/code-check.ts
11271
11356
  /** While a pass runs: the code it parsed so far, by goal and source. */
11272
11357
  var parses = null;
@@ -11417,6 +11502,7 @@ function* codeAndText(src, tokens, parametersOf) {
11417
11502
  offset: token.targetStart,
11418
11503
  length: token.targetEnd - token.targetStart,
11419
11504
  macro: "link",
11505
+ ...usesBuiltinSemantics("link", parametersOf) && { navigation: true },
11420
11506
  label: src.slice(token.start, token.end)
11421
11507
  };
11422
11508
  if (token.display.includes("{")) yield textPiece(token.display, token.displayStart, "In the label of a link: ");
@@ -11486,7 +11572,10 @@ function* codeAndText(src, tokens, parametersOf) {
11486
11572
  continue;
11487
11573
  }
11488
11574
  const params = parametersOf(name);
11489
- if (params) yield* argPieces(args, argsAt, params, token.name, label);
11575
+ if (params) {
11576
+ const navigation = usesBuiltinSemantics(name, parametersOf) ? name === "goto" || name === "link" ? ["passage"] : name === "watch" ? ["goto"] : [] : [];
11577
+ yield* argPieces(args, argsAt, params, token.name, label, navigation);
11578
+ }
11490
11579
  if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
11491
11580
  }
11492
11581
  }
@@ -11500,37 +11589,50 @@ function* codeAndText(src, tokens, parametersOf) {
11500
11589
  function* passagePiecesOf(src, tokens, parametersOf, options = {}) {
11501
11590
  let position;
11502
11591
  const locate = (offset) => (position ?? (position = sourcePositions(src)))(offset);
11503
- yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0, locate);
11592
+ yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0, locate, new MarkupExpansionBudget(src.length));
11504
11593
  }
11505
11594
  /**
11506
11595
  * The pieces of `tokens`, the tokens of `src`, which is the text described by
11507
11596
  * `where` (none for `root`, the markup of the whole passage), and whose
11508
11597
  * offsets `toRoot` turns into offsets in `root`.
11509
11598
  */
11510
- function* expand(root, src, tokens, parametersOf, options, toRoot, where, locate) {
11599
+ function* expand(root, src, tokens, parametersOf, options, toRoot, where, locate, budget) {
11511
11600
  for (const flat of codeAndText(src, tokens, parametersOf)) {
11512
11601
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
11513
11602
  if (flat.kind !== "text" || !flat.text.includes("{")) {
11514
11603
  yield piece;
11515
11604
  continue;
11516
11605
  }
11517
- const toText = (i) => toRoot(pieceOffset(flat, i));
11518
- const inner = analyzeMarkup(flat.text, {
11519
- text: true,
11520
- hooks: {
11521
- ...options.isBlock && { isBlock: options.isBlock },
11522
- isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0)
11523
- }
11524
- });
11525
- yield {
11526
- ...piece,
11527
- tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
11528
- errors: inner.errors.map((e) => {
11529
- const { line, column } = locate(toText(e.offset));
11530
- return new MarkupError(e.reason, toText(e.offset), line, column, e.code, toText(e.end), e.data);
11531
- })
11532
- };
11533
- yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where, locate);
11606
+ const toText = (i) => pieceOffset(piece, i);
11607
+ if (!budget.enter(flat.text.length)) {
11608
+ const at = toText(0);
11609
+ const { line, column } = locate(at);
11610
+ yield {
11611
+ ...piece,
11612
+ errors: [new MarkupError("Markup in labels and attributes exceeds the nesting or work limit", at, line, column, "nesting-limit", toText(flat.text.length), { limit: String(MarkupExpansionBudget.maxDepth) })]
11613
+ };
11614
+ continue;
11615
+ }
11616
+ try {
11617
+ const inner = analyzeMarkup(flat.text, {
11618
+ text: true,
11619
+ hooks: {
11620
+ ...options.isBlock && { isBlock: options.isBlock },
11621
+ isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0)
11622
+ }
11623
+ });
11624
+ yield {
11625
+ ...piece,
11626
+ tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
11627
+ errors: inner.errors.map((e) => {
11628
+ const { line, column } = locate(toText(e.offset));
11629
+ return new MarkupError(e.reason, toText(e.offset), line, column, e.code, toText(e.end), e.data);
11630
+ })
11631
+ };
11632
+ yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where, locate, budget);
11633
+ } finally {
11634
+ budget.leave();
11635
+ }
11534
11636
  }
11535
11637
  }
11536
11638
  /** `piece`, of a text in another, with its offsets turned by `toRoot`. */
@@ -11609,7 +11711,7 @@ function escapeOffsets(raw, at, value, escapes) {
11609
11711
  return escaped ? offsets : void 0;
11610
11712
  }
11611
11713
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
11612
- function* argPieces(args, offset, params, macro, label) {
11714
+ function* argPieces(args, offset, params, macro, label, navigation = []) {
11613
11715
  let values;
11614
11716
  const spans = /* @__PURE__ */ new Map();
11615
11717
  try {
@@ -11626,7 +11728,7 @@ function* argPieces(args, offset, params, macro, label) {
11626
11728
  };
11627
11729
  return;
11628
11730
  }
11629
- yield* valuePieces(args, offset, params, values, spans, macro, label, "quotes");
11731
+ yield* valuePieces(args, offset, params, values, spans, macro, label, "quotes", navigation);
11630
11732
  }
11631
11733
  /**
11632
11734
  * The code and text in the arguments `args` (at `offset`) of the widget
@@ -11659,7 +11761,7 @@ function* widgetPieces(args, offset, params, macro, label) {
11659
11761
  * (at `offset`), whose `spans` tell where each was written and whose strings
11660
11762
  * are unescaped as `escapes` says.
11661
11763
  */
11662
- function* valuePieces(args, offset, params, values, spans, macro, label, escapes) {
11764
+ function* valuePieces(args, offset, params, values, spans, macro, label, escapes, navigation = []) {
11663
11765
  const name = macro.toLowerCase();
11664
11766
  /** The pieces of the parameters `list`, with their values in `from`. */
11665
11767
  function* visit(list, from) {
@@ -11680,7 +11782,8 @@ function* valuePieces(args, offset, params, values, spans, macro, label, escapes
11680
11782
  offset: offset + start,
11681
11783
  length: end - start,
11682
11784
  macro: name,
11683
- label
11785
+ label,
11786
+ ...navigation.includes(param.name) && { navigation: true }
11684
11787
  });
11685
11788
  const goal = codeGoal(param);
11686
11789
  if (param.type === "passage") {
@@ -11958,18 +12061,19 @@ registeredParameters.source = getMacroParameters.source;
11958
12061
  * Whether the text of an attribute value or macro label renders a
11959
12062
  * `{@children}`: it is markup, parsed as the renderer parses it.
11960
12063
  */
11961
- function textContainsChildren(text, parametersOf, hooks) {
12064
+ function textContainsChildren(text, parametersOf, hooks, budget = new MarkupExpansionBudget(text.length)) {
11962
12065
  if (!text.includes("{")) return false;
11963
- let nodes;
12066
+ if (!budget.enter(text.length)) return false;
11964
12067
  try {
11965
- nodes = parseMarkup(text, {
12068
+ return astContainsChildren(parseMarkup(text, {
11966
12069
  text: true,
11967
12070
  hooks
11968
- });
12071
+ }), parametersOf, hooks, budget);
11969
12072
  } catch {
11970
12073
  return false;
12074
+ } finally {
12075
+ budget.leave();
11971
12076
  }
11972
- return astContainsChildren(nodes, parametersOf, hooks);
11973
12077
  }
11974
12078
  /**
11975
12079
  * Whether a tag renders a `{@children}` in an attribute value or a macro
@@ -11979,19 +12083,21 @@ function textContainsChildren(text, parametersOf, hooks) {
11979
12083
  * are read from it); a token made from an AST has none. Discovery hooks
11980
12084
  * also apply inside these texts, before widgets have been registered.
11981
12085
  */
11982
- function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "", hooks) {
11983
- for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf, hooks)) return true;
12086
+ function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "", hooks, budget) {
12087
+ for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf, hooks, budget)) return true;
11984
12088
  return false;
11985
12089
  }
11986
12090
  /**
11987
- * Recursively scan an AST node array for a VariableNode
12091
+ * Scan an AST node array for a VariableNode
11988
12092
  * with scope 'local' and name 'children' (@children), in the content and in
11989
12093
  * the attributes and labels that render markup. A nested `{widget}` is not
11990
12094
  * entered: its slot belongs to the innermost widget (as widgetDefinitions
11991
12095
  * reads it), and a definition renders nothing of its own.
11992
12096
  */
11993
- function astContainsChildren(nodes, parametersOf = registeredParameters, hooks) {
11994
- for (const node of nodes) {
12097
+ function astContainsChildren(nodes, parametersOf = registeredParameters, hooks, budget) {
12098
+ const pending = [...nodes];
12099
+ while (pending.length) {
12100
+ const node = pending.pop();
11995
12101
  if (node.type === "variable" && node.scope === "local" && node.name === "children") return true;
11996
12102
  if (node.type !== "html" && node.type !== "macro") continue;
11997
12103
  if (node.type === "macro" && node.name.toLowerCase() === "widget") continue;
@@ -12014,10 +12120,9 @@ function astContainsChildren(nodes, parametersOf = registeredParameters, hooks)
12014
12120
  nameEnd: 0,
12015
12121
  argsStart: 0,
12016
12122
  argsEnd: 0
12017
- }, parametersOf, "", hooks) || astContainsChildren(node.children, parametersOf, hooks)) return true;
12018
- if (node.type === "macro" && node.branches) {
12019
- for (const branch of node.branches) if (astContainsChildren(branch.children, parametersOf, hooks)) return true;
12020
- }
12123
+ }, parametersOf, "", hooks, budget)) return true;
12124
+ for (const child of node.children) pending.push(child);
12125
+ if (node.type === "macro" && node.branches) for (const branch of node.branches) for (const child of branch.children) pending.push(child);
12021
12126
  }
12022
12127
  return false;
12023
12128
  }
@@ -12098,6 +12203,7 @@ function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
12098
12203
  const hooks = { isRaw: (name) => isRawMacro(name, replacesDo || parametersOf.widget?.(name) !== void 0) };
12099
12204
  for (const passage of list) {
12100
12205
  if (passage.name !== "StoryInit" && !passage.tags?.includes("widget")) continue;
12206
+ const budget = new MarkupExpansionBudget(passage.content.length);
12101
12207
  const open = [];
12102
12208
  const done = [];
12103
12209
  for (const token of tokenizeMarkupTolerant$1(passage.content, { hooks }).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") {
@@ -12112,7 +12218,7 @@ function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
12112
12218
  closeStart: token.start
12113
12219
  });
12114
12220
  }
12115
- } else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf, passage.content, hooks))) open[open.length - 1].isBlock = true;
12221
+ } else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf, passage.content, hooks, budget))) open[open.length - 1].isBlock = true;
12116
12222
  done.push(...open);
12117
12223
  const defs = [];
12118
12224
  for (const { token, isBlock, closeStart } of done) try {
@@ -12149,6 +12255,26 @@ function effectiveWidgetDefinitions(definitions) {
12149
12255
  return [...effective.values()];
12150
12256
  }
12151
12257
  //#endregion
12258
+ //#region src/passage-roles.ts
12259
+ /** Runtime-owned passage roles, shared with stateless authoring tools. */
12260
+ var SPECIAL_PASSAGES = /* @__PURE__ */ new Set([
12261
+ "StoryInit",
12262
+ "StoryInterface",
12263
+ "StoryVariables",
12264
+ "StoryTransients",
12265
+ "StoryLoading",
12266
+ "SaveTitle",
12267
+ "PassageReady",
12268
+ "PassageHeader",
12269
+ "PassageFooter",
12270
+ "PassageDone",
12271
+ "StoryContext"
12272
+ ]);
12273
+ /** Whether `name` is a special passage, which navigation never goes to. */
12274
+ function isSpecialPassage(name) {
12275
+ return SPECIAL_PASSAGES.has(name);
12276
+ }
12277
+ //#endregion
12152
12278
  //#region src/markup/validate.ts
12153
12279
  /**
12154
12280
  * Markup validation: parse every passage when the story starts and report
@@ -12332,6 +12458,13 @@ function validateMarkup(passages, options) {
12332
12458
  report(passage, at, at + piece.length, "argument-error", `${where}${piece.message} in ${piece.label}`, { macro: piece.macro });
12333
12459
  break;
12334
12460
  case "passage":
12461
+ if (piece.navigation && isSpecialPassage(piece.name)) {
12462
+ report(passage, at, at + piece.length, "special-passage", `${where}Cannot navigate to special passage ${JSON.stringify(piece.name)} in ${piece.label}.`, {
12463
+ name: piece.name,
12464
+ macro: piece.macro
12465
+ });
12466
+ break;
12467
+ }
12335
12468
  if (options.checkPassageNames !== false && !passageNames.has(piece.name)) {
12336
12469
  const best = closestName(piece.name, passageNames);
12337
12470
  report(passage, at, at + piece.length, "unknown-passage", `${where}No passage named ${JSON.stringify(piece.name)} in ${piece.label}.${didYouMean(best, JSON.stringify)}`, {
@@ -12812,8 +12945,6 @@ function declarationRegex(sigil) {
12812
12945
  const escaped = sigil.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12813
12946
  return new RegExp(`^${escaped}(\\w+)\\s*=\\s*(.+)$`);
12814
12947
  }
12815
- /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
12816
- var VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
12817
12948
  var VALID_VAR_TYPES = /* @__PURE__ */ new Set([
12818
12949
  "number",
12819
12950
  "string",
@@ -13039,36 +13170,19 @@ function checkReference(ref, declared) {
13039
13170
  return null;
13040
13171
  }
13041
13172
  var NO_STORE_VAR_MACROS = /* @__PURE__ */ new Set();
13042
- /** A `.field` path written right after a reference, which may be empty. */
13043
- var FIELD_PATH_RE = /(?:\.\w+)*/y;
13044
13173
  /**
13045
13174
  * The reference to variable `name`, which JavaScript reads at `[start, end)`
13046
13175
  * of `code` (the sigil and the name as written, which may be spelled with
13047
13176
  * escapes), with the dot path written after it.
13048
13177
  */
13049
- function referenceAt(code, sigil, name, start, end, at) {
13050
- FIELD_PATH_RE.lastIndex = end;
13051
- const fields = FIELD_PATH_RE.exec(code)[0];
13178
+ function referenceAt(code, { sigil, name, start, end }, at) {
13179
+ const fields = readMemberPath(code, end);
13052
13180
  return {
13053
13181
  sigil,
13054
13182
  name,
13055
- path: fields ? fields.slice(1).split(".") : [],
13183
+ path: fields.path,
13056
13184
  start: at(start),
13057
- end: at(end + fields.length)
13058
- };
13059
- }
13060
- /** A reference written at `index` of `term`, a `variable` parameter as written. */
13061
- function termReferenceAt(term, index, at) {
13062
- VAR_PATH_RE.lastIndex = index;
13063
- const match = VAR_PATH_RE.exec(term);
13064
- if (!match) return void 0;
13065
- const [name, ...path] = match[2].split(".");
13066
- return {
13067
- sigil: match[1],
13068
- name,
13069
- path,
13070
- start: at(index),
13071
- end: at(index + match[0].length)
13185
+ end: at(fields.end)
13072
13186
  };
13073
13187
  }
13074
13188
  /**
@@ -13087,7 +13201,15 @@ function scanSigilReferences(value, at, emit) {
13087
13201
  */
13088
13202
  function scanInterpolations(text, at, emit, options) {
13089
13203
  if (!text.includes("{")) return;
13090
- collectTokenRefs(text, tokensOf(text, true, options), at, emit, options);
13204
+ const budget = options.expansionBudget;
13205
+ if (!budget.enter(text.length)) return;
13206
+ try {
13207
+ const offset = at(0);
13208
+ const sourceOffsets = at(text.length) - offset === text.length ? void 0 : Array.from({ length: text.length + 1 }, (_, i) => at(i));
13209
+ collectTokenRefs(text, tokensOf(text, true, options), (i) => sourceOffsets?.[i] ?? offset + i, emit, options);
13210
+ } finally {
13211
+ budget.leave();
13212
+ }
13091
13213
  }
13092
13214
  /**
13093
13215
  * Report `$var` references in JavaScript code, lexed as the expression
@@ -13105,7 +13227,7 @@ function scanCode(code, at, emit, goal = "expression") {
13105
13227
  }
13106
13228
  for (const ref of parsed.refs) {
13107
13229
  if (ref.sigil !== "$" && ref.sigil !== "%") continue;
13108
- emit(referenceAt(code, ref.sigil, ref.name, ref.start, ref.end, at));
13230
+ emit(referenceAt(code, ref, at));
13109
13231
  }
13110
13232
  }
13111
13233
  /** `scanCode` for code acorn can't parse: lexed leniently. */
@@ -13113,7 +13235,12 @@ function scanCodeLeniently(code, at, emit, goal) {
13113
13235
  lexJs(code, {
13114
13236
  variable(sigil, name, index, _nesting, end) {
13115
13237
  if (sigil !== "$" && sigil !== "%") return;
13116
- emit(referenceAt(code, sigil, name, index, end, at));
13238
+ emit(referenceAt(code, {
13239
+ sigil,
13240
+ name,
13241
+ start: index,
13242
+ end
13243
+ }, at));
13117
13244
  },
13118
13245
  literal() {}
13119
13246
  }, goal);
@@ -13142,7 +13269,7 @@ function scanArgs(token, parametersOf, at, emit, options) {
13142
13269
  const params = parametersOf(token.name);
13143
13270
  let byParameters = false;
13144
13271
  if (params) {
13145
- if (options.all && !options.storeVarMacros.has(token.name.toLowerCase())) scanVariableParameters(token, params, at, emit);
13272
+ if (!options.storeVarMacros.has(token.name.toLowerCase())) scanVariableParameters(token, params, at, emit, options.all);
13146
13273
  const pieces = [...argPieces(token.rawArgs, token.argsStart, params, token.name, "")];
13147
13274
  byParameters = !pieces.some((piece) => piece.kind === "argument-error");
13148
13275
  if (byParameters) scanPieces(pieces, at, emit, options);
@@ -13153,10 +13280,10 @@ function scanArgs(token, parametersOf, at, emit, options) {
13153
13280
  }
13154
13281
  /**
13155
13282
  * Report the variables the `variable` parameters of a macro name
13156
- * (`{unset $x}`, `{computed $x = …}`), when they are `$` or `%` variables.
13157
- * Arguments that do not parse hold none.
13283
+ * (`{unset $x}`, `{computed $x = …}`). Computed members read variables even
13284
+ * when the receiver itself is only included in the complete editor list.
13158
13285
  */
13159
- function scanVariableParameters(token, params, at, emit) {
13286
+ function scanVariableParameters(token, params, at, emit, all) {
13160
13287
  const spans = /* @__PURE__ */ new Map();
13161
13288
  try {
13162
13289
  parseMacroArgs(token.rawArgs, params, spans);
@@ -13167,8 +13294,10 @@ function scanVariableParameters(token, params, at, emit) {
13167
13294
  for (const param of params) {
13168
13295
  const span = spans.get(param);
13169
13296
  if (param.type !== "variable" || !span) continue;
13170
- const ref = termReferenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
13171
- if (ref) emit(ref);
13297
+ const start = token.argsStart + span[0];
13298
+ scanCode(token.rawArgs.slice(span[0], span[1]), (i) => at(start + i), (ref) => {
13299
+ if (all || ref.start !== at(start)) emit(ref);
13300
+ });
13172
13301
  }
13173
13302
  }
13174
13303
  /** Report the references in the selectors of a token, which are interpolated. */
@@ -13262,7 +13391,10 @@ function collectTokenRefs(content, tokens, at, emit, options) {
13262
13391
  */
13263
13392
  function collectVariableReferences(content, options) {
13264
13393
  const found = [];
13265
- withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), options));
13394
+ withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), {
13395
+ ...options,
13396
+ expansionBudget: new MarkupExpansionBudget(content.length)
13397
+ }));
13266
13398
  return found.sort((a, b) => a.start - b.start);
13267
13399
  }
13268
13400
  /**
@@ -25393,7 +25525,7 @@ async function formatLf(text, options) {
25393
25525
  }
25394
25526
  if (region.type === "html") {
25395
25527
  const htmlText = region.lines.join("\n");
25396
- if (WHITESPACE_AS_WRITTEN.test(htmlText) || region.lines.some((line) => literalLines.has(line.trim()))) {
25528
+ if (WHITESPACE_AS_WRITTEN.test(htmlText) || region.lines.some((line) => literalLines.has(line.trim())) || hasMarkdownBoundaries(htmlText, isBlock)) {
25397
25529
  for (let i = 0; i < region.lines.length; i++) preservedLines.add(lines.length + i);
25398
25530
  lines.push(...region.lines);
25399
25531
  continue;
@@ -25426,6 +25558,30 @@ async function formatLf(text, options) {
25426
25558
  }
25427
25559
  /** Literal HTML and opaque SVG, whose text can inherit significant whitespace. */
25428
25560
  var WHITESPACE_AS_WRITTEN = /<(?:pre|textarea|svg)[\s>]|white-space\s*:/i;
25561
+ /** HTML whitespace formatting must not collapse the Markdown in its bodies. */
25562
+ var HTML_MARKDOWN_BOUNDARIES = /* @__PURE__ */ new Set([
25563
+ "hardBreakTrailing",
25564
+ "hardBreakEscape",
25565
+ "atxHeading",
25566
+ "setextHeading",
25567
+ "listOrdered",
25568
+ "listUnordered",
25569
+ "blockQuote",
25570
+ "thematicBreak",
25571
+ "definition",
25572
+ "table",
25573
+ "codeFenced"
25574
+ ]);
25575
+ function hasMarkdownBoundaries(source, isBlock) {
25576
+ const { tokens } = analyzeMarkup(source, { hooks: { isBlock } });
25577
+ let possibleBoundary = false;
25578
+ for (const token of tokens) {
25579
+ if (token.type !== "text") continue;
25580
+ if (/\n[ \t]*\n/.test(token.value)) return true;
25581
+ if (/[\\#*+\d=>[`~|-]|[ \t]\n/.test(token.value)) possibleBoundary = true;
25582
+ }
25583
+ return possibleBoundary && markdownLines(source, isBlock, HTML_MARKDOWN_BOUNDARIES).size > 0;
25584
+ }
25429
25585
  /** Preserve whole literal elements, including openers beside nested tags. */
25430
25586
  function whitespaceSensitiveLines(source, isBlock) {
25431
25587
  const lines = /* @__PURE__ */ new Set();
@@ -25832,20 +25988,23 @@ function validateStoryMarkup(passages, macros, options = {}) {
25832
25988
  const all = effectiveToolingMacros(macros);
25833
25989
  const known = /* @__PURE__ */ new Set();
25834
25990
  const widgets = effectiveWidgetDefinitions(widgetDefinitions$1(list, parameterLookup(all)));
25835
- const blocks = new Set(widgets.filter((def) => def.block).map((def) => def.name.toLowerCase()));
25836
25991
  const parametersOf = parameterLookup([...all, ...definedWidgetMacros(widgets)]);
25837
25992
  for (const macro of all) {
25838
25993
  const name = macro.name.toLowerCase();
25839
25994
  known.add(name);
25840
25995
  for (const sub of macro.subMacros) known.add(sub.toLowerCase());
25841
- if (macro.block) blocks.add(name);
25842
25996
  }
25843
25997
  return validateMarkup(list, {
25844
25998
  branchParents: (name) => branchParents(name, all),
25845
25999
  isKnownMacro: (name) => known.has(name),
25846
26000
  macroNames: known,
25847
26001
  parametersOf,
25848
- isBlockMacro: (name) => blocks.has(name.toLowerCase()) || isBlockMacro(name),
26002
+ isBlockMacro: blockLookup([...all, ...widgets.map((w) => ({
26003
+ name: w.name,
26004
+ block: w.block,
26005
+ subMacros: [],
26006
+ widget: w
26007
+ }))]),
25849
26008
  checkPassageNames: options.checkPassageNames,
25850
26009
  tolerant: options.tolerant
25851
26010
  });
@@ -25859,8 +26018,9 @@ function definedWidgetMacros(widgets) {
25859
26018
  }
25860
26019
  /** Whether a macro takes a body, among `macros` and the built-in ones. */
25861
26020
  function blockLookup(macros) {
25862
- const blocks = new Set(macros.filter((m) => m.block).map((m) => m.name.toLowerCase()));
25863
- return (name) => blocks.has(name.toLowerCase()) || isBlockMacro(name);
26021
+ const definitions = new NameMap();
26022
+ for (const macro of effectiveToolingMacros(macros)) definitions.set(macro.name, macro.block);
26023
+ return (name) => isRegisteredBlockMacro(name) || (definitions.get(name) ?? isBlockMacro(name));
25864
26024
  }
25865
26025
  /**
25866
26026
  * What a passage's markup runs and names, and where: the pieces of code
@@ -25959,4 +26119,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
25959
26119
  return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
25960
26120
  }
25961
26121
  //#endregion
25962
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, lexJs, lexTemplate, macroArgumentSpans, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
26122
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, isSpecialPassage, lexJs, lexTemplate, macroArgumentSpans, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };