@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.
@@ -5827,6 +5827,29 @@ function parseMemberIdentifier(src) {
5827
5827
  if (object.type !== "Identifier" || object.start !== 0 || object.end !== 1 || property.type !== "Identifier" || property.start !== 2 || property.end !== src.length + 2) return null;
5828
5828
  return property.name;
5829
5829
  }
5830
+ /** Read the contiguous dot members after a variable, keeping decoded names. */
5831
+ function readMemberPath(src, end) {
5832
+ const path = [];
5833
+ const p = tokenizerAt(src, end, "expression", { afterOperand: true });
5834
+ try {
5835
+ for (;;) {
5836
+ p.nextToken();
5837
+ if (p.type !== types$1.dot || p.start !== end) break;
5838
+ const dotEnd = p.end;
5839
+ p.nextToken();
5840
+ if (p.start !== dotEnd || p.type !== types$1.name && !p.type.keyword) break;
5841
+ if (!/^\w+$/.test(String(p.value))) break;
5842
+ path.push(String(p.value));
5843
+ end = p.end;
5844
+ }
5845
+ } catch (error) {
5846
+ if (!(error instanceof SyntaxError)) throw error;
5847
+ }
5848
+ return {
5849
+ path,
5850
+ end
5851
+ };
5852
+ }
5830
5853
  /**
5831
5854
  * Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
5832
5855
  * noting where it read a transient in `transientsRead`.
@@ -5872,118 +5895,144 @@ function propertyName(node, src) {
5872
5895
  * identifiers here are declared (a `let`, a parameter), where a sigil
5873
5896
  * variable can't be. `shorthand`: the node is a shorthand property's value.
5874
5897
  */
5875
- function walk(node, src, out, binding, shorthand, access = "read") {
5876
- if (Array.isArray(node)) {
5877
- for (const n of node) walk(n, src, out, binding, false, access);
5878
- return;
5879
- }
5880
- if (!isNode(node)) return;
5881
- const sub = (child, bind = false, short = false, role = "read") => walk(child, src, out, bind, short, role);
5882
- switch (node.type) {
5883
- case "Identifier": {
5884
- const sigil = sigilOf(node, src);
5885
- if (!sigil) return;
5886
- if (binding) throw new CodeSyntaxError(`"${node.name}" is a ${NAMESPACE_NAME[sigil[0]]} variable and can't be declared`, src, node.start);
5887
- out.refs.push({
5888
- sigil: sigil[0],
5889
- name: sigil[1],
5890
- start: node.start,
5891
- end: node.end,
5892
- shorthand,
5893
- read: access !== "write",
5894
- write: access !== "read"
5895
- });
5898
+ function walk(root, src, out, binding, shorthand, access = "read") {
5899
+ const pending = [[
5900
+ root,
5901
+ binding,
5902
+ shorthand,
5903
+ access
5904
+ ]];
5905
+ while (pending.length) {
5906
+ const [node, bind, short, role] = pending.pop();
5907
+ const children = [];
5908
+ visit(node, bind, short, role, children);
5909
+ for (let i = children.length - 1; i >= 0; i--) pending.push(children[i]);
5910
+ }
5911
+ function visit(node, binding, shorthand, access, children) {
5912
+ if (Array.isArray(node)) {
5913
+ for (const n of node) children.push([
5914
+ n,
5915
+ binding,
5916
+ false,
5917
+ access
5918
+ ]);
5896
5919
  return;
5897
5920
  }
5898
- case "Literal":
5899
- if (typeof node.value === "string") out.strings.push(src.slice(node.start + 1, node.end - 1));
5900
- return;
5901
- case "TemplateElement":
5902
- out.strings.push(node.value.raw);
5903
- return;
5904
- case "MemberExpression":
5905
- sub(node.object);
5906
- if (node.computed) sub(node.property);
5907
- else propertyName(node.property, src);
5908
- return;
5909
- case "Property":
5910
- if (node.computed) sub(node.key);
5911
- else if (!node.shorthand) propertyName(node.key, src);
5912
- if (node.shorthand) {
5913
- const value = node.value;
5914
- if (value.type === "AssignmentPattern") {
5915
- sub(value.left, binding, true, access);
5916
- sub(value.right);
5917
- } else sub(value, binding, true, access);
5918
- } else sub(node.value, binding, false, access);
5919
- return;
5920
- case "MethodDefinition":
5921
- case "PropertyDefinition":
5922
- if (node.computed) sub(node.key);
5923
- else propertyName(node.key, src);
5924
- sub(node.value);
5925
- return;
5926
- case "LabeledStatement":
5927
- sub(node.body);
5928
- return;
5929
- case "BreakStatement":
5930
- case "ContinueStatement":
5931
- case "MetaProperty":
5932
- case "PrivateIdentifier": return;
5933
- case "VariableDeclarator":
5934
- sub(node.id, true);
5935
- sub(node.init);
5936
- return;
5937
- case "FunctionDeclaration":
5938
- case "FunctionExpression":
5939
- case "ArrowFunctionExpression":
5940
- sub(node.id, true);
5941
- for (const p of node.params) sub(p, true);
5942
- sub(node.body);
5943
- return;
5944
- case "ClassDeclaration":
5945
- case "ClassExpression":
5946
- sub(node.id, true);
5947
- sub(node.superClass);
5948
- sub(node.body);
5949
- return;
5950
- case "CatchClause":
5951
- sub(node.param, true);
5952
- sub(node.body);
5953
- return;
5954
- case "AssignmentExpression":
5955
- sub(node.left, false, false, node.operator === "=" ? "write" : "readwrite");
5956
- sub(node.right);
5957
- return;
5958
- case "UnaryExpression":
5959
- sub(node.argument, false, false, node.operator === "delete" ? "write" : "read");
5960
- return;
5961
- case "UpdateExpression":
5962
- sub(node.argument, false, false, "readwrite");
5963
- return;
5964
- case "ForInStatement":
5965
- case "ForOfStatement":
5966
- sub(node.left, false, false, "write");
5967
- sub(node.right);
5968
- sub(node.body);
5969
- return;
5970
- case "AssignmentPattern":
5971
- sub(node.left, binding, false, access);
5972
- sub(node.right);
5973
- return;
5974
- case "ObjectPattern":
5975
- case "ArrayPattern":
5976
- case "RestElement":
5977
- for (const key of [
5978
- "properties",
5979
- "elements",
5980
- "argument"
5981
- ]) sub(node[key], binding, false, access);
5982
- return;
5983
- default: for (const key in node) {
5984
- if (key === "type" || key === "start" || key === "end") continue;
5985
- const v = node[key];
5986
- if (typeof v === "object" && v !== null) sub(v);
5921
+ if (!isNode(node)) return;
5922
+ const sub = (child, bind = false, short = false, role = "read") => {
5923
+ children.push([
5924
+ child,
5925
+ bind,
5926
+ short,
5927
+ role
5928
+ ]);
5929
+ };
5930
+ switch (node.type) {
5931
+ case "Identifier": {
5932
+ const sigil = sigilOf(node, src);
5933
+ if (!sigil) return;
5934
+ if (binding) throw new CodeSyntaxError(`"${node.name}" is a ${NAMESPACE_NAME[sigil[0]]} variable and can't be declared`, src, node.start);
5935
+ out.refs.push({
5936
+ sigil: sigil[0],
5937
+ name: sigil[1],
5938
+ start: node.start,
5939
+ end: node.end,
5940
+ shorthand,
5941
+ read: access !== "write",
5942
+ write: access !== "read"
5943
+ });
5944
+ return;
5945
+ }
5946
+ case "Literal":
5947
+ if (typeof node.value === "string") out.strings.push(src.slice(node.start + 1, node.end - 1));
5948
+ return;
5949
+ case "TemplateElement":
5950
+ out.strings.push(node.value.raw);
5951
+ return;
5952
+ case "MemberExpression":
5953
+ sub(node.object);
5954
+ if (node.computed) sub(node.property);
5955
+ else propertyName(node.property, src);
5956
+ return;
5957
+ case "Property":
5958
+ if (node.computed) sub(node.key);
5959
+ else if (!node.shorthand) propertyName(node.key, src);
5960
+ if (node.shorthand) {
5961
+ const value = node.value;
5962
+ if (value.type === "AssignmentPattern") {
5963
+ sub(value.left, binding, true, access);
5964
+ sub(value.right);
5965
+ } else sub(value, binding, true, access);
5966
+ } else sub(node.value, binding, false, access);
5967
+ return;
5968
+ case "MethodDefinition":
5969
+ case "PropertyDefinition":
5970
+ if (node.computed) sub(node.key);
5971
+ else propertyName(node.key, src);
5972
+ sub(node.value);
5973
+ return;
5974
+ case "LabeledStatement":
5975
+ sub(node.body);
5976
+ return;
5977
+ case "BreakStatement":
5978
+ case "ContinueStatement":
5979
+ case "MetaProperty":
5980
+ case "PrivateIdentifier": return;
5981
+ case "VariableDeclarator":
5982
+ sub(node.id, true);
5983
+ sub(node.init);
5984
+ return;
5985
+ case "FunctionDeclaration":
5986
+ case "FunctionExpression":
5987
+ case "ArrowFunctionExpression":
5988
+ sub(node.id, true);
5989
+ for (const p of node.params) sub(p, true);
5990
+ sub(node.body);
5991
+ return;
5992
+ case "ClassDeclaration":
5993
+ case "ClassExpression":
5994
+ sub(node.id, true);
5995
+ sub(node.superClass);
5996
+ sub(node.body);
5997
+ return;
5998
+ case "CatchClause":
5999
+ sub(node.param, true);
6000
+ sub(node.body);
6001
+ return;
6002
+ case "AssignmentExpression":
6003
+ sub(node.left, false, false, node.operator === "=" ? "write" : "readwrite");
6004
+ sub(node.right);
6005
+ return;
6006
+ case "UnaryExpression":
6007
+ sub(node.argument, false, false, node.operator === "delete" ? "write" : "read");
6008
+ return;
6009
+ case "UpdateExpression":
6010
+ sub(node.argument, false, false, "readwrite");
6011
+ return;
6012
+ case "ForInStatement":
6013
+ case "ForOfStatement":
6014
+ sub(node.left, false, false, "write");
6015
+ sub(node.right);
6016
+ sub(node.body);
6017
+ return;
6018
+ case "AssignmentPattern":
6019
+ sub(node.left, binding, false, access);
6020
+ sub(node.right);
6021
+ return;
6022
+ case "ObjectPattern":
6023
+ case "ArrayPattern":
6024
+ case "RestElement":
6025
+ for (const key of [
6026
+ "properties",
6027
+ "elements",
6028
+ "argument"
6029
+ ]) sub(node[key], binding, false, access);
6030
+ return;
6031
+ default: for (const key in node) {
6032
+ if (key === "type" || key === "start" || key === "end") continue;
6033
+ const v = node[key];
6034
+ if (typeof v === "object" && v !== null) sub(v);
6035
+ }
5987
6036
  }
5988
6037
  }
5989
6038
  }
@@ -13310,10 +13359,10 @@ function registerMacroMetadata(name, metadata) {
13310
13359
  companionParents.set(sub, parents);
13311
13360
  }
13312
13361
  }
13313
- /** The parents declaring a branching companion (listbox options are values). */
13362
+ /** The parents declaring a branching companion (input options are values). */
13314
13363
  function branchParents(name, macros) {
13315
- if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox");
13316
- return effectiveNamedDefinitions(macros).filter((macro) => macro.name.toLowerCase() !== "listbox" && macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase())).map((macro) => macro.name.toLowerCase());
13364
+ if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox" && parent !== "cycle");
13365
+ 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());
13317
13366
  }
13318
13367
  /** The declared parameters of the macro `name`, if it declares any. */
13319
13368
  function getMacroParameters(name) {
@@ -13348,15 +13397,18 @@ var BLOCK_MACROS = new NameSet([
13348
13397
  ]);
13349
13398
  /**
13350
13399
  * The block widgets (those whose body renders `{@children}`), kept apart from
13351
- * BLOCK_MACROS: a widget is redefined, so it is a block only while its latest
13352
- * definition is, whereas the macros in BLOCK_MACROS stay blocks.
13400
+ * built-in defaults: a widget is a block only while its latest definition is.
13353
13401
  */
13354
13402
  var BLOCK_WIDGETS = new NameSet();
13355
13403
  /** All widgets, including inline ones, override built-in parsing semantics. */
13356
13404
  var WIDGETS = new NameSet();
13357
13405
  /** Classification owned by defineMacro, independent of explicit registrations. */
13358
13406
  var DEFINED_BLOCK_MACROS = new NameSet();
13407
+ var DEFINED_MACROS = new NameSet();
13408
+ /** Explicit registrations remain independent of macro/widget replacements. */
13409
+ var REGISTERED_BLOCK_MACROS = new NameSet();
13359
13410
  function setDefinedBlockMacro(name, isBlock) {
13411
+ DEFINED_MACROS.add(name);
13360
13412
  setClassification(DEFINED_BLOCK_MACROS, name, isBlock);
13361
13413
  }
13362
13414
  /** Update the classification owned by one registration source. */
@@ -13372,7 +13424,10 @@ function isRawMacro(name, widget = WIDGETS.has(name)) {
13372
13424
  }
13373
13425
  /** Whether a macro takes a body closed by `{/name}`. */
13374
13426
  function isBlockMacro(name) {
13375
- return BLOCK_MACROS.has(name) || DEFINED_BLOCK_MACROS.has(name) || BLOCK_WIDGETS.has(name);
13427
+ if (REGISTERED_BLOCK_MACROS.has(name)) return true;
13428
+ if (WIDGETS.has(name)) return BLOCK_WIDGETS.has(name);
13429
+ if (DEFINED_MACROS.has(name)) return DEFINED_BLOCK_MACROS.has(name);
13430
+ return BLOCK_MACROS.has(name);
13376
13431
  }
13377
13432
  /**
13378
13433
  * Record whether the widget `name` takes a body, as its latest definition
@@ -13505,6 +13560,8 @@ function sourcePositions(text) {
13505
13560
  * runtime reads it, or, when it matches one further out, closes that one and
13506
13561
  * what was open inside it stays unclosed.
13507
13562
  */
13563
+ /** Keep AST construction and recursive rendering within a safe call depth. */
13564
+ var MAX_MARKUP_DEPTH = 256;
13508
13565
  /** The last of `items`. */
13509
13566
  var last = (items) => items[items.length - 1];
13510
13567
  /** The macro each branch macro belongs to. */
@@ -13642,6 +13699,10 @@ function pairMarkup(tokens, options = {}) {
13642
13699
  add(node);
13643
13700
  continue;
13644
13701
  }
13702
+ if (stack.length === MAX_MARKUP_DEPTH) report("nesting-limit", token, `Markup nesting exceeds the limit of ${MAX_MARKUP_DEPTH} elements`, token.start, {
13703
+ name: nameOf(token),
13704
+ limit: String(MAX_MARKUP_DEPTH)
13705
+ });
13645
13706
  const body = {
13646
13707
  children: [],
13647
13708
  branches: []
@@ -14069,7 +14130,7 @@ function scanMarkupTolerant(source, options = {}, completion = false) {
14069
14130
  const rest = source.slice(base);
14070
14131
  const result = attempt(rest, base);
14071
14132
  if (Array.isArray(result)) {
14072
- tokens.push(...result);
14133
+ for (const token of result) tokens.push(token);
14073
14134
  break;
14074
14135
  }
14075
14136
  const at = base + result.offset;
@@ -14082,7 +14143,7 @@ function scanMarkupTolerant(source, options = {}, completion = false) {
14082
14143
  cut = prefix.offset;
14083
14144
  prefix = attempt(rest.slice(0, cut), base);
14084
14145
  }
14085
- tokens.push(...prefix);
14146
+ for (const token of prefix) tokens.push(token);
14086
14147
  damage.push(base + cut);
14087
14148
  if (cut < rest.length) {
14088
14149
  const start = base + cut;
@@ -14838,6 +14899,27 @@ function extractOptions(children) {
14838
14899
  return options;
14839
14900
  }
14840
14901
  //#endregion
14902
+ //#region src/markup/expansion-budget.ts
14903
+ /** Shared bounds for reparsing markup inside labels, selectors and attributes. */
14904
+ var MarkupExpansionBudget = class MarkupExpansionBudget {
14905
+ static {
14906
+ this.maxDepth = 64;
14907
+ }
14908
+ constructor(sourceLength) {
14909
+ this.depth = 0;
14910
+ this.remaining = Math.max(65536, sourceLength * 8);
14911
+ }
14912
+ enter(length) {
14913
+ if (this.depth >= MarkupExpansionBudget.maxDepth || length > this.remaining) return false;
14914
+ this.remaining -= length;
14915
+ this.depth++;
14916
+ return true;
14917
+ }
14918
+ leave() {
14919
+ this.depth--;
14920
+ }
14921
+ };
14922
+ //#endregion
14841
14923
  //#region src/code-check.ts
14842
14924
  /** While a pass runs: the code it parsed so far, by goal and source. */
14843
14925
  var parses = null;
@@ -14988,6 +15070,7 @@ function* codeAndText(src, tokens, parametersOf) {
14988
15070
  offset: token.targetStart,
14989
15071
  length: token.targetEnd - token.targetStart,
14990
15072
  macro: "link",
15073
+ ...usesBuiltinSemantics("link", parametersOf) && { navigation: true },
14991
15074
  label: src.slice(token.start, token.end)
14992
15075
  };
14993
15076
  if (token.display.includes("{")) yield textPiece(token.display, token.displayStart, "In the label of a link: ");
@@ -15057,7 +15140,10 @@ function* codeAndText(src, tokens, parametersOf) {
15057
15140
  continue;
15058
15141
  }
15059
15142
  const params = parametersOf(name);
15060
- if (params) yield* argPieces(args, argsAt, params, token.name, label);
15143
+ if (params) {
15144
+ const navigation = usesBuiltinSemantics(name, parametersOf) ? name === "goto" || name === "link" ? ["passage"] : name === "watch" ? ["goto"] : [] : [];
15145
+ yield* argPieces(args, argsAt, params, token.name, label, navigation);
15146
+ }
15061
15147
  if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
15062
15148
  }
15063
15149
  }
@@ -15071,37 +15157,50 @@ function* codeAndText(src, tokens, parametersOf) {
15071
15157
  function* passagePiecesOf(src, tokens, parametersOf, options = {}) {
15072
15158
  let position;
15073
15159
  const locate = (offset) => (position ??= sourcePositions(src))(offset);
15074
- yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0, locate);
15160
+ yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0, locate, new MarkupExpansionBudget(src.length));
15075
15161
  }
15076
15162
  /**
15077
15163
  * The pieces of `tokens`, the tokens of `src`, which is the text described by
15078
15164
  * `where` (none for `root`, the markup of the whole passage), and whose
15079
15165
  * offsets `toRoot` turns into offsets in `root`.
15080
15166
  */
15081
- function* expand(root, src, tokens, parametersOf, options, toRoot, where, locate) {
15167
+ function* expand(root, src, tokens, parametersOf, options, toRoot, where, locate, budget) {
15082
15168
  for (const flat of codeAndText(src, tokens, parametersOf)) {
15083
15169
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
15084
15170
  if (flat.kind !== "text" || !flat.text.includes("{")) {
15085
15171
  yield piece;
15086
15172
  continue;
15087
15173
  }
15088
- const toText = (i) => toRoot(pieceOffset(flat, i));
15089
- const inner = analyzeMarkup(flat.text, {
15090
- text: true,
15091
- hooks: {
15092
- ...options.isBlock && { isBlock: options.isBlock },
15093
- isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0)
15094
- }
15095
- });
15096
- yield {
15097
- ...piece,
15098
- tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
15099
- errors: inner.errors.map((e) => {
15100
- const { line, column } = locate(toText(e.offset));
15101
- return new MarkupError(e.reason, toText(e.offset), line, column, e.code, toText(e.end), e.data);
15102
- })
15103
- };
15104
- yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where, locate);
15174
+ const toText = (i) => pieceOffset(piece, i);
15175
+ if (!budget.enter(flat.text.length)) {
15176
+ const at = toText(0);
15177
+ const { line, column } = locate(at);
15178
+ yield {
15179
+ ...piece,
15180
+ 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) })]
15181
+ };
15182
+ continue;
15183
+ }
15184
+ try {
15185
+ const inner = analyzeMarkup(flat.text, {
15186
+ text: true,
15187
+ hooks: {
15188
+ ...options.isBlock && { isBlock: options.isBlock },
15189
+ isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0)
15190
+ }
15191
+ });
15192
+ yield {
15193
+ ...piece,
15194
+ tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
15195
+ errors: inner.errors.map((e) => {
15196
+ const { line, column } = locate(toText(e.offset));
15197
+ return new MarkupError(e.reason, toText(e.offset), line, column, e.code, toText(e.end), e.data);
15198
+ })
15199
+ };
15200
+ yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where, locate, budget);
15201
+ } finally {
15202
+ budget.leave();
15203
+ }
15105
15204
  }
15106
15205
  }
15107
15206
  /** `piece`, of a text in another, with its offsets turned by `toRoot`. */
@@ -15180,7 +15279,7 @@ function escapeOffsets(raw, at, value, escapes) {
15180
15279
  return escaped ? offsets : void 0;
15181
15280
  }
15182
15281
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
15183
- function* argPieces(args, offset, params, macro, label) {
15282
+ function* argPieces(args, offset, params, macro, label, navigation = []) {
15184
15283
  let values;
15185
15284
  const spans = /* @__PURE__ */ new Map();
15186
15285
  try {
@@ -15197,7 +15296,7 @@ function* argPieces(args, offset, params, macro, label) {
15197
15296
  };
15198
15297
  return;
15199
15298
  }
15200
- yield* valuePieces(args, offset, params, values, spans, macro, label, "quotes");
15299
+ yield* valuePieces(args, offset, params, values, spans, macro, label, "quotes", navigation);
15201
15300
  }
15202
15301
  /**
15203
15302
  * The code and text in the arguments `args` (at `offset`) of the widget
@@ -15230,7 +15329,7 @@ function* widgetPieces(args, offset, params, macro, label) {
15230
15329
  * (at `offset`), whose `spans` tell where each was written and whose strings
15231
15330
  * are unescaped as `escapes` says.
15232
15331
  */
15233
- function* valuePieces(args, offset, params, values, spans, macro, label, escapes) {
15332
+ function* valuePieces(args, offset, params, values, spans, macro, label, escapes, navigation = []) {
15234
15333
  const name = macro.toLowerCase();
15235
15334
  /** The pieces of the parameters `list`, with their values in `from`. */
15236
15335
  function* visit(list, from) {
@@ -15251,7 +15350,8 @@ function* valuePieces(args, offset, params, values, spans, macro, label, escapes
15251
15350
  offset: offset + start,
15252
15351
  length: end - start,
15253
15352
  macro: name,
15254
- label
15353
+ label,
15354
+ ...navigation.includes(param.name) && { navigation: true }
15255
15355
  });
15256
15356
  const goal = codeGoal(param);
15257
15357
  if (param.type === "passage") {
@@ -15380,18 +15480,19 @@ registeredParameters.source = getMacroParameters.source;
15380
15480
  * Whether the text of an attribute value or macro label renders a
15381
15481
  * `{@children}`: it is markup, parsed as the renderer parses it.
15382
15482
  */
15383
- function textContainsChildren(text, parametersOf, hooks) {
15483
+ function textContainsChildren(text, parametersOf, hooks, budget = new MarkupExpansionBudget(text.length)) {
15384
15484
  if (!text.includes("{")) return false;
15385
- let nodes;
15485
+ if (!budget.enter(text.length)) return false;
15386
15486
  try {
15387
- nodes = parseMarkup(text, {
15487
+ return astContainsChildren(parseMarkup(text, {
15388
15488
  text: true,
15389
15489
  hooks
15390
- });
15490
+ }), parametersOf, hooks, budget);
15391
15491
  } catch {
15392
15492
  return false;
15493
+ } finally {
15494
+ budget.leave();
15393
15495
  }
15394
- return astContainsChildren(nodes, parametersOf, hooks);
15395
15496
  }
15396
15497
  /**
15397
15498
  * Whether a tag renders a `{@children}` in an attribute value or a macro
@@ -15401,19 +15502,21 @@ function textContainsChildren(text, parametersOf, hooks) {
15401
15502
  * are read from it); a token made from an AST has none. Discovery hooks
15402
15503
  * also apply inside these texts, before widgets have been registered.
15403
15504
  */
15404
- function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "", hooks) {
15405
- for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf, hooks)) return true;
15505
+ function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "", hooks, budget) {
15506
+ for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf, hooks, budget)) return true;
15406
15507
  return false;
15407
15508
  }
15408
15509
  /**
15409
- * Recursively scan an AST node array for a VariableNode
15510
+ * Scan an AST node array for a VariableNode
15410
15511
  * with scope 'local' and name 'children' (@children), in the content and in
15411
15512
  * the attributes and labels that render markup. A nested `{widget}` is not
15412
15513
  * entered: its slot belongs to the innermost widget (as widgetDefinitions
15413
15514
  * reads it), and a definition renders nothing of its own.
15414
15515
  */
15415
- function astContainsChildren(nodes, parametersOf = registeredParameters, hooks) {
15416
- for (const node of nodes) {
15516
+ function astContainsChildren(nodes, parametersOf = registeredParameters, hooks, budget) {
15517
+ const pending = [...nodes];
15518
+ while (pending.length) {
15519
+ const node = pending.pop();
15417
15520
  if (node.type === "variable" && node.scope === "local" && node.name === "children") return true;
15418
15521
  if (node.type !== "html" && node.type !== "macro") continue;
15419
15522
  if (node.type === "macro" && node.name.toLowerCase() === "widget") continue;
@@ -15436,10 +15539,9 @@ function astContainsChildren(nodes, parametersOf = registeredParameters, hooks)
15436
15539
  nameEnd: 0,
15437
15540
  argsStart: 0,
15438
15541
  argsEnd: 0
15439
- }, parametersOf, "", hooks) || astContainsChildren(node.children, parametersOf, hooks)) return true;
15440
- if (node.type === "macro" && node.branches) {
15441
- for (const branch of node.branches) if (astContainsChildren(branch.children, parametersOf, hooks)) return true;
15442
- }
15542
+ }, parametersOf, "", hooks, budget)) return true;
15543
+ for (const child of node.children) pending.push(child);
15544
+ if (node.type === "macro" && node.branches) for (const branch of node.branches) for (const child of branch.children) pending.push(child);
15443
15545
  }
15444
15546
  return false;
15445
15547
  }
@@ -15526,6 +15628,7 @@ function widgetDefinitions(passages, parametersOf = registeredParameters) {
15526
15628
  const hooks = { isRaw: (name) => isRawMacro(name, replacesDo || parametersOf.widget?.(name) !== void 0) };
15527
15629
  for (const passage of list) {
15528
15630
  if (passage.name !== "StoryInit" && !passage.tags?.includes("widget")) continue;
15631
+ const budget = new MarkupExpansionBudget(passage.content.length);
15529
15632
  const open = [];
15530
15633
  const done = [];
15531
15634
  for (const token of tokenizeMarkupTolerant(passage.content, { hooks }).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") {
@@ -15540,7 +15643,7 @@ function widgetDefinitions(passages, parametersOf = registeredParameters) {
15540
15643
  closeStart: token.start
15541
15644
  });
15542
15645
  }
15543
- } 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;
15646
+ } 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;
15544
15647
  done.push(...open);
15545
15648
  const defs = [];
15546
15649
  for (const { token, isBlock, closeStart } of done) try {
@@ -16513,7 +16616,7 @@ var StructuralContext = createContext(false);
16513
16616
  /**
16514
16617
  * True while rendering inside an element whose content is not markdown: SVG
16515
16618
  * (whose namespace `<p>` wrappers would break) and the preformatted `<pre>`
16516
- * `<textarea>` and `<style>`, whose text (indentation, `#`, `*`, ...) is literal.
16619
+ * `<textarea>`, `<style>` and `<script>`, whose text is literal.
16517
16620
  * Macro and widget bodies read it so their content stays literal too.
16518
16621
  */
16519
16622
  var RawTextContext = createContext(false);
@@ -16560,7 +16663,8 @@ var STRUCTURAL_ELEMENTS = /* @__PURE__ */ new Set([
16560
16663
  var PREFORMATTED_ELEMENTS = /* @__PURE__ */ new Set([
16561
16664
  "pre",
16562
16665
  "textarea",
16563
- "style"
16666
+ "style",
16667
+ "script"
16564
16668
  ]);
16565
16669
  var WidgetChildrenContext = createContext(null);
16566
16670
  function placeholderHtml(nonce, index) {
@@ -17055,7 +17159,7 @@ function HtmlNodeRenderer({ node }) {
17055
17159
  let children = void 0;
17056
17160
  let structural = false;
17057
17161
  if (node.children.length > 0) {
17058
- if (tag === "style") children = node.children.map((n) => n.type === "text" ? n.value : renderSingleNode(n));
17162
+ if (tag === "style" || tag === "script") children = node.children.map((n) => n.type === "text" ? n.value : renderSingleNode(n));
17059
17163
  else if (rawContent || isRawRoot) children = renderInlineNodes(node.children);
17060
17164
  else {
17061
17165
  const leadAt = leadingPartIndex(tag, node.children);
@@ -19150,9 +19254,8 @@ function initializeStory(session) {
19150
19254
  if (!session) recordStoryInitState();
19151
19255
  }
19152
19256
  //#endregion
19153
- //#region src/store.ts
19154
- enablePatches();
19155
- enableMapSet();
19257
+ //#region src/passage-roles.ts
19258
+ /** Runtime-owned passage roles, shared with stateless authoring tools. */
19156
19259
  var SPECIAL_PASSAGES = /* @__PURE__ */ new Set([
19157
19260
  "StoryInit",
19158
19261
  "StoryInterface",
@@ -19170,6 +19273,10 @@ var SPECIAL_PASSAGES = /* @__PURE__ */ new Set([
19170
19273
  function isSpecialPassage(name) {
19171
19274
  return SPECIAL_PASSAGES.has(name);
19172
19275
  }
19276
+ //#endregion
19277
+ //#region src/store.ts
19278
+ enablePatches();
19279
+ enableMapSet();
19173
19280
  /** Full variable snapshot at history index 0. */
19174
19281
  var variableBase = createNamespace();
19175
19282
  /**
@@ -20078,13 +20185,13 @@ var useStoryStore = create()(storyStore((set, get) => ({
20078
20185
  setVariable: (name, value) => {
20079
20186
  set((state) => {
20080
20187
  checkVariableName(name, `$${name}`);
20081
- state.variables[name] = value;
20188
+ setByPath(state.variables, [name], value);
20082
20189
  });
20083
20190
  },
20084
20191
  setTemporary: (name, value) => {
20085
20192
  set((state) => {
20086
20193
  checkVariableName(name, `_${name}`);
20087
- state.temporary[name] = value;
20194
+ setByPath(state.temporary, [name], value);
20088
20195
  });
20089
20196
  },
20090
20197
  deleteVariable: (name) => {
@@ -20102,7 +20209,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20102
20209
  setTransient: (name, value) => {
20103
20210
  set((state) => {
20104
20211
  checkVariableName(name, `%${name}`);
20105
- state.transient[name] = value;
20212
+ setByPath(state.transient, [name], value);
20106
20213
  });
20107
20214
  },
20108
20215
  deleteTransient: (name) => {
@@ -21084,11 +21191,11 @@ var escapeAttributeReferences = (text) => text.replace(/&/g, "&amp;");
21084
21191
  var escapeTextReferences = (text) => escapeAttributeReferences(text).replace(/</g, "&lt;");
21085
21192
  /**
21086
21193
  * Elements whose text the renderer shows as written, with no character
21087
- * references decoded: the one it treats as raw text (`style`, see
21194
+ * references decoded: those it treats as raw text (`style`, `script`, see
21088
21195
  * HtmlNodeRenderer), for which the browser did not decode any either.
21089
21196
  */
21090
21197
  function isLiteralTextElement(parent) {
21091
- return parent.localName === "style" && parent.namespaceURI === HTML_NAMESPACE;
21198
+ return ["style", "script"].includes(parent.localName) && parent.namespaceURI === HTML_NAMESPACE;
21092
21199
  }
21093
21200
  /**
21094
21201
  * `value` with the text in it escaped by `escape`, but not markup
@@ -21869,7 +21976,7 @@ function observe() {
21869
21976
  text: body ? observableText(body, DIALOG) : ""
21870
21977
  }));
21871
21978
  const errors = [
21872
- passageEl,
21979
+ document.getElementById("root") ?? passageEl,
21873
21980
  ...bodies.map((d) => d.body),
21874
21981
  contextEl
21875
21982
  ].flatMap((el) => el ? observableErrors(el, DIALOG, el === contextEl ? el : void 0) : []);
@@ -21951,9 +22058,7 @@ function warnIfUndeclared(isTransient, key) {
21951
22058
  /** Set a single variable on an Immer draft, resolving dot-paths if present. */
21952
22059
  function setOne(draft, name, value) {
21953
22060
  const { isTransient, key } = parseName(name);
21954
- const namespace = isTransient ? draft.transient : draft.variables;
21955
- if (key.includes(".")) setByPath(namespace, key.split("."), value);
21956
- else namespace[key] = value;
22061
+ setByPath(isTransient ? draft.transient : draft.variables, key.split("."), value);
21957
22062
  }
21958
22063
  /** A method calling the store action `name`, as the store holds it then. */
21959
22064
  function storeAction(name) {
@@ -22372,6 +22477,13 @@ function validateMarkup(passages, options) {
22372
22477
  report(passage, at, at + piece.length, "argument-error", `${where}${piece.message} in ${piece.label}`, { macro: piece.macro });
22373
22478
  break;
22374
22479
  case "passage":
22480
+ if (piece.navigation && isSpecialPassage(piece.name)) {
22481
+ report(passage, at, at + piece.length, "special-passage", `${where}Cannot navigate to special passage ${JSON.stringify(piece.name)} in ${piece.label}.`, {
22482
+ name: piece.name,
22483
+ macro: piece.macro
22484
+ });
22485
+ break;
22486
+ }
22375
22487
  if (options.checkPassageNames !== false && !passageNames.has(piece.name)) {
22376
22488
  const best = closestName(piece.name, passageNames);
22377
22489
  report(passage, at, at + piece.length, "unknown-passage", `${where}No passage named ${JSON.stringify(piece.name)} in ${piece.label}.${didYouMean(best, JSON.stringify)}`, {
@@ -22852,8 +22964,6 @@ function declarationRegex(sigil) {
22852
22964
  const escaped = sigil.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22853
22965
  return new RegExp(`^${escaped}(\\w+)\\s*=\\s*(.+)$`);
22854
22966
  }
22855
- /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
22856
- var VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
22857
22967
  var VALID_VAR_TYPES = /* @__PURE__ */ new Set([
22858
22968
  "number",
22859
22969
  "string",
@@ -23092,36 +23202,19 @@ var BUILTIN_STORE_VAR_MACROS = [
23092
23202
  "textbox"
23093
23203
  ];
23094
23204
  var NO_STORE_VAR_MACROS = /* @__PURE__ */ new Set();
23095
- /** A `.field` path written right after a reference, which may be empty. */
23096
- var FIELD_PATH_RE = /(?:\.\w+)*/y;
23097
23205
  /**
23098
23206
  * The reference to variable `name`, which JavaScript reads at `[start, end)`
23099
23207
  * of `code` (the sigil and the name as written, which may be spelled with
23100
23208
  * escapes), with the dot path written after it.
23101
23209
  */
23102
- function referenceAt(code, sigil, name, start, end, at) {
23103
- FIELD_PATH_RE.lastIndex = end;
23104
- const fields = FIELD_PATH_RE.exec(code)[0];
23210
+ function referenceAt(code, { sigil, name, start, end }, at) {
23211
+ const fields = readMemberPath(code, end);
23105
23212
  return {
23106
23213
  sigil,
23107
23214
  name,
23108
- path: fields ? fields.slice(1).split(".") : [],
23215
+ path: fields.path,
23109
23216
  start: at(start),
23110
- end: at(end + fields.length)
23111
- };
23112
- }
23113
- /** A reference written at `index` of `term`, a `variable` parameter as written. */
23114
- function termReferenceAt(term, index, at) {
23115
- VAR_PATH_RE.lastIndex = index;
23116
- const match = VAR_PATH_RE.exec(term);
23117
- if (!match) return void 0;
23118
- const [name, ...path] = match[2].split(".");
23119
- return {
23120
- sigil: match[1],
23121
- name,
23122
- path,
23123
- start: at(index),
23124
- end: at(index + match[0].length)
23217
+ end: at(fields.end)
23125
23218
  };
23126
23219
  }
23127
23220
  /**
@@ -23140,7 +23233,15 @@ function scanSigilReferences(value, at, emit) {
23140
23233
  */
23141
23234
  function scanInterpolations(text, at, emit, options) {
23142
23235
  if (!text.includes("{")) return;
23143
- collectTokenRefs(text, tokensOf(text, true, options), at, emit, options);
23236
+ const budget = options.expansionBudget;
23237
+ if (!budget.enter(text.length)) return;
23238
+ try {
23239
+ const offset = at(0);
23240
+ const sourceOffsets = at(text.length) - offset === text.length ? void 0 : Array.from({ length: text.length + 1 }, (_, i) => at(i));
23241
+ collectTokenRefs(text, tokensOf(text, true, options), (i) => sourceOffsets?.[i] ?? offset + i, emit, options);
23242
+ } finally {
23243
+ budget.leave();
23244
+ }
23144
23245
  }
23145
23246
  /**
23146
23247
  * Report `$var` references in JavaScript code, lexed as the expression
@@ -23158,7 +23259,7 @@ function scanCode(code, at, emit, goal = "expression") {
23158
23259
  }
23159
23260
  for (const ref of parsed.refs) {
23160
23261
  if (ref.sigil !== "$" && ref.sigil !== "%") continue;
23161
- emit(referenceAt(code, ref.sigil, ref.name, ref.start, ref.end, at));
23262
+ emit(referenceAt(code, ref, at));
23162
23263
  }
23163
23264
  }
23164
23265
  /** `scanCode` for code acorn can't parse: lexed leniently. */
@@ -23166,7 +23267,12 @@ function scanCodeLeniently(code, at, emit, goal) {
23166
23267
  lexJs(code, {
23167
23268
  variable(sigil, name, index, _nesting, end) {
23168
23269
  if (sigil !== "$" && sigil !== "%") return;
23169
- emit(referenceAt(code, sigil, name, index, end, at));
23270
+ emit(referenceAt(code, {
23271
+ sigil,
23272
+ name,
23273
+ start: index,
23274
+ end
23275
+ }, at));
23170
23276
  },
23171
23277
  literal() {}
23172
23278
  }, goal);
@@ -23195,7 +23301,7 @@ function scanArgs(token, parametersOf, at, emit, options) {
23195
23301
  const params = parametersOf(token.name);
23196
23302
  let byParameters = false;
23197
23303
  if (params) {
23198
- if (options.all && !options.storeVarMacros.has(token.name.toLowerCase())) scanVariableParameters(token, params, at, emit);
23304
+ if (!options.storeVarMacros.has(token.name.toLowerCase())) scanVariableParameters(token, params, at, emit, options.all);
23199
23305
  const pieces = [...argPieces(token.rawArgs, token.argsStart, params, token.name, "")];
23200
23306
  byParameters = !pieces.some((piece) => piece.kind === "argument-error");
23201
23307
  if (byParameters) scanPieces(pieces, at, emit, options);
@@ -23206,10 +23312,10 @@ function scanArgs(token, parametersOf, at, emit, options) {
23206
23312
  }
23207
23313
  /**
23208
23314
  * Report the variables the `variable` parameters of a macro name
23209
- * (`{unset $x}`, `{computed $x = …}`), when they are `$` or `%` variables.
23210
- * Arguments that do not parse hold none.
23315
+ * (`{unset $x}`, `{computed $x = …}`). Computed members read variables even
23316
+ * when the receiver itself is only included in the complete editor list.
23211
23317
  */
23212
- function scanVariableParameters(token, params, at, emit) {
23318
+ function scanVariableParameters(token, params, at, emit, all) {
23213
23319
  const spans = /* @__PURE__ */ new Map();
23214
23320
  try {
23215
23321
  parseMacroArgs(token.rawArgs, params, spans);
@@ -23220,8 +23326,10 @@ function scanVariableParameters(token, params, at, emit) {
23220
23326
  for (const param of params) {
23221
23327
  const span = spans.get(param);
23222
23328
  if (param.type !== "variable" || !span) continue;
23223
- const ref = termReferenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
23224
- if (ref) emit(ref);
23329
+ const start = token.argsStart + span[0];
23330
+ scanCode(token.rawArgs.slice(span[0], span[1]), (i) => at(start + i), (ref) => {
23331
+ if (all || ref.start !== at(start)) emit(ref);
23332
+ });
23225
23333
  }
23226
23334
  }
23227
23335
  /** Report the references in the selectors of a token, which are interpolated. */
@@ -23315,7 +23423,10 @@ function collectTokenRefs(content, tokens, at, emit, options) {
23315
23423
  */
23316
23424
  function collectVariableReferences(content, options) {
23317
23425
  const found = [];
23318
- withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), options));
23426
+ withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), {
23427
+ ...options,
23428
+ expansionBudget: new MarkupExpansionBudget(content.length)
23429
+ }));
23319
23430
  return found.sort((a, b) => a.start - b.start);
23320
23431
  }
23321
23432
  /**
@@ -24229,10 +24340,11 @@ var UNSET = Symbol("unset");
24229
24340
  function assignmentArgs(rawArgs, args) {
24230
24341
  if (!args["="]) throw new Error(`{computed}: expected "target = expression", got "${rawArgs}"`);
24231
24342
  const { target = "", expression: expr = "" } = args;
24232
- if (!target.match(/^[$_@]\w+$/)) throw new Error(`{computed}: target must be $name, _name, or @name, got "${target}"`);
24233
- checkVariableName(target.slice(1), target);
24343
+ const path = parseReferencePath(target);
24344
+ if (!path || path.nested || path.sigil === "%") throw new Error(`{computed}: target must be $name, _name, or @name, got "${target}"`);
24345
+ checkVariableName(path.name, target);
24234
24346
  return {
24235
- target,
24347
+ target: path.sigil + path.name,
24236
24348
  expr
24237
24349
  };
24238
24350
  }
@@ -26014,6 +26126,7 @@ defineMacro({
26014
26126
  defineMacro({
26015
26127
  name: "cycle",
26016
26128
  block: true,
26129
+ subMacros: ["option"],
26017
26130
  interpolate: true,
26018
26131
  storeVar: true,
26019
26132
  parameters: [VARIABLE_PARAMETER],