@rohal12/spindle 0.59.29 → 0.59.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +1 -0
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +947 -351
  4. package/dist/pkg/macro-registry.js +19 -0
  5. package/dist/pkg/macro-registry.json +19 -0
  6. package/dist/pkg/story-variables.js +780 -107
  7. package/package.json +1 -1
  8. package/src/action-registry.ts +59 -5
  9. package/src/automation/load-yaml.ts +111 -20
  10. package/src/automation/runner.ts +19 -13
  11. package/src/automation/types.ts +7 -5
  12. package/src/class-registry.ts +8 -5
  13. package/src/code-check.ts +87 -20
  14. package/src/components/macros/Checkbox.tsx +5 -2
  15. package/src/components/macros/Cycle.tsx +1 -0
  16. package/src/components/macros/For.tsx +1 -7
  17. package/src/components/macros/Listbox.tsx +1 -0
  18. package/src/components/macros/MenubarButtons.tsx +6 -1
  19. package/src/components/macros/Nobr.tsx +1 -0
  20. package/src/components/macros/PassageDisplay.tsx +136 -10
  21. package/src/components/macros/Radiobutton.tsx +1 -0
  22. package/src/components/macros/Repeat.tsx +4 -2
  23. package/src/components/macros/SaveManager.tsx +30 -8
  24. package/src/components/macros/SettingsControls.tsx +19 -4
  25. package/src/components/macros/Span.tsx +1 -0
  26. package/src/components/macros/StoryTitle.tsx +1 -0
  27. package/src/components/macros/Unset.tsx +26 -13
  28. package/src/components/macros/VarDisplay.tsx +2 -3
  29. package/src/components/macros/WidgetInvocation.tsx +5 -6
  30. package/src/components/macros/input-macro.ts +1 -0
  31. package/src/components/macros/locals-scope.tsx +19 -8
  32. package/src/components/macros/macro-args.ts +11 -3
  33. package/src/expression.ts +34 -18
  34. package/src/hooks/use-merged-locals.ts +17 -2
  35. package/src/hooks/use-modal-focus.ts +247 -133
  36. package/src/index.tsx +32 -21
  37. package/src/js-bindings.ts +594 -0
  38. package/src/js-lexer.ts +76 -14
  39. package/src/macro-discovery.ts +83 -32
  40. package/src/markup/ast.ts +22 -1
  41. package/src/markup/render.tsx +44 -15
  42. package/src/parser.ts +41 -10
  43. package/src/prng.ts +24 -1
  44. package/src/saves/save-manager.ts +36 -9
  45. package/src/static-literal.ts +87 -16
  46. package/src/store.ts +83 -6
  47. package/src/story-api.ts +23 -6
  48. package/src/story-variables.ts +91 -28
  49. package/src/structural.ts +26 -15
  50. package/src/tooling.ts +24 -10
  51. package/src/transform.ts +22 -7
  52. package/src/utils/macro-names.ts +4 -0
  53. package/src/utils/namespace.ts +15 -2
  54. package/src/utils/object-path.ts +2 -2
  55. package/src/utils/stable-key.ts +17 -6
  56. package/src/utils/value-kinds.ts +38 -1
  57. package/src/widgets/ast-scanner.ts +4 -1
  58. package/src/widgets/register-widget-def.ts +2 -3
  59. package/src/widgets/widget-def.ts +36 -6
  60. package/src/widgets/widget-registry.ts +6 -2
  61. package/types/index.d.ts +12 -5
  62. package/types/tooling.d.ts +12 -2
@@ -3333,6 +3333,9 @@ var NameSet = class {
3333
3333
  delete(name) {
3334
3334
  this.names.delete(name);
3335
3335
  }
3336
+ clear() {
3337
+ this.names.clear();
3338
+ }
3336
3339
  };
3337
3340
  //#endregion
3338
3341
  //#region src/markup/ast.ts
@@ -3357,6 +3360,12 @@ var BLOCK_MACROS = new NameSet([
3357
3360
  "span",
3358
3361
  "nobr"
3359
3362
  ]);
3363
+ /**
3364
+ * The block widgets (those whose body renders `{@children}`), kept apart from
3365
+ * BLOCK_MACROS: a widget is redefined, so it is a block only while its latest
3366
+ * definition is, whereas the macros in BLOCK_MACROS stay blocks.
3367
+ */
3368
+ var BLOCK_WIDGETS = new NameSet();
3360
3369
  /** Macros whose body is JavaScript source, kept verbatim. */
3361
3370
  var RAW_BODY_MACROS = /* @__PURE__ */ new Set(["do"]);
3362
3371
  /** Whether a macro's body is JavaScript, kept verbatim (`{do}`). */
@@ -3365,7 +3374,7 @@ function isRawMacro(name) {
3365
3374
  }
3366
3375
  /** Whether a macro takes a body closed by `{/name}`. */
3367
3376
  function isBlockMacro(name) {
3368
- return BLOCK_MACROS.has(name);
3377
+ return BLOCK_MACROS.has(name) || BLOCK_WIDGETS.has(name);
3369
3378
  }
3370
3379
  /** Macros whose branches render as one: the node holds one per branch. */
3371
3380
  var BRANCHING = /* @__PURE__ */ new Set([
@@ -8950,15 +8959,15 @@ var SigilParser = class extends Parser {
8950
8959
  }
8951
8960
  const self = this;
8952
8961
  const prevType = self.type;
8953
- this.prevValue = self.value;
8954
- const property = type.keyword !== void 0 && (prevType === types$1.dot || prevType === types$1.questionDot) || (type === types$1._function || type === types$1._class) && notABody(self.input, self.pos);
8962
+ this.prevValue = isMemberDot(this.typeBeforeLast) ? void 0 : self.value;
8963
+ const property = type.keyword !== void 0 && isMemberDot(prevType) || (type === types$1._function || type === types$1._class) && notABody(self.input, self.pos);
8955
8964
  if (!property && (type === types$1._function || type === types$1._class)) {
8956
8965
  const before = type === types$1._function && prevType === types$1.name && this.prevValue === "async" && !this.breakHere ? this.typeBeforeLast : prevType;
8957
8966
  self.type = before === types$1.colon && this.colonEndsTernary ? types$1.parenL : before;
8958
8967
  }
8959
8968
  this.typeBeforeLast = prevType;
8960
8969
  super.finishToken(property ? types$1.name : type, value);
8961
- if (type === types$1.name && value === "of" && (prevType === types$1._const || prevType === types$1._var || this.prevValue === "let")) self.exprAllowed = false;
8970
+ if (type === types$1.name && (isMemberDot(prevType) || value === "of" && (prevType === types$1._const || prevType === types$1._var || this.prevValue === "let"))) self.exprAllowed = false;
8962
8971
  }
8963
8972
  braceIsBlock(prevType) {
8964
8973
  if (prevType === types$1.colon && this.colonEndsTernary) return false;
@@ -8989,7 +8998,7 @@ function transientAssignment(p, end) {
8989
8998
  if (t === types$1.eof) return false;
8990
8999
  if (depth > 0) {
8991
9000
  if (OPENERS.has(t)) depth++;
8992
- else if (CLOSERS.has(t)) depth--;
9001
+ else if (CLOSERS$1.has(t)) depth--;
8993
9002
  } else if (t === types$1.bracketL) depth = 1;
8994
9003
  else if (t === types$1.dot) {
8995
9004
  q.nextToken();
@@ -9000,13 +9009,17 @@ function transientAssignment(p, end) {
9000
9009
  return false;
9001
9010
  }
9002
9011
  }
9012
+ /** Is `type` the `.` or `?.` of a member access? */
9013
+ function isMemberDot(type) {
9014
+ return type === types$1.dot || type === types$1.questionDot;
9015
+ }
9003
9016
  var OPENERS = /* @__PURE__ */ new Set([
9004
9017
  types$1.parenL,
9005
9018
  types$1.bracketL,
9006
9019
  types$1.braceL,
9007
9020
  types$1.dollarBraceL
9008
9021
  ]);
9009
- var CLOSERS = /* @__PURE__ */ new Set([
9022
+ var CLOSERS$1 = /* @__PURE__ */ new Set([
9010
9023
  types$1.parenR,
9011
9024
  types$1.bracketR,
9012
9025
  types$1.braceR
@@ -9135,6 +9148,10 @@ function bracketsBefore(src, pos) {
9135
9148
  * sigil variable declared (`let _x`) or used as a property name (`a.@x`).
9136
9149
  */
9137
9150
  function parseCode(src, goal = "expression") {
9151
+ return parseWithAst(src, goal).out;
9152
+ }
9153
+ /** What parseCode finds in `src`, and the syntax tree it is in. */
9154
+ function parseWithAst(src, goal) {
9138
9155
  const percentAt = /* @__PURE__ */ new Map();
9139
9156
  for (;;) {
9140
9157
  const transientsRead = /* @__PURE__ */ new Set();
@@ -9146,7 +9163,10 @@ function parseCode(src, goal = "expression") {
9146
9163
  };
9147
9164
  walk(ast, src, out, false, false);
9148
9165
  out.refs.sort((a, b) => a.start - b.start);
9149
- return out;
9166
+ return {
9167
+ out,
9168
+ ast
9169
+ };
9150
9170
  } catch (error) {
9151
9171
  const pos = error.pos ?? -1;
9152
9172
  if (!(error instanceof SyntaxError) || percentAt.has(pos)) throw error;
@@ -9550,7 +9570,7 @@ function walkTokens(src, from, handlers, nesting, goal, oneTemplate) {
9550
9570
  if (t === types$1.name) {
9551
9571
  const sigil = sigilAt(src, tok.start, tok.value);
9552
9572
  const property = prev === types$1.dot || prev === types$1.questionDot || (sigil === "$" || sigil === "_") && keyPosition(src, tok.end, prev);
9553
- if (sigil && !property) handlers.variable?.(sigil, src.slice(tok.start + 1, tok.end), tok.start, nesting);
9573
+ if (sigil && !property) handlers.variable?.(sigil, tok.value.slice(1), tok.start, nesting, tok.end);
9554
9574
  else code(tok.start, tok.end);
9555
9575
  } else if (t === types$1.string || t === types$1.regexp || t === types$1.template || t === types$1.invalidTemplate) literal(tok.start, tok.end);
9556
9576
  else if (t === types$1.backQuote) {
@@ -10364,10 +10384,12 @@ var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
10364
10384
  * Where the rest of `src` is without the flag `word` as its last or first
10365
10385
  * term, or `null` if it has no such flag. Next to a binary operator the
10366
10386
  * word is an operand (`"a" + inline`), not a flag; the closing `/` of a
10367
- * regex literal is not one.
10387
+ * regex literal is not one. A word with nothing else beside it is the flag
10388
+ * only when `alone` says no argument is waiting for it (#499).
10368
10389
  */
10369
- function takeFlag(src, word) {
10390
+ function takeFlag(src, word, alone) {
10370
10391
  const spans = terms(src);
10392
+ if (spans.length === 1) return alone && slice(src, spans[0]) === word ? [src.length, src.length] : null;
10371
10393
  if (spans.length < 2) return null;
10372
10394
  if (slice(src, spans[spans.length - 1]) === word) {
10373
10395
  const rest = [0, spans[spans.length - 2][1]];
@@ -10414,8 +10436,9 @@ function trimmed(src, at) {
10414
10436
  */
10415
10437
  function readGroup(params, src, args, { at: srcAt, spans }) {
10416
10438
  let [text, at] = trimmed(src ?? "", srcAt);
10439
+ const alone = !params.some((p) => p.type !== "flag" && p.required);
10417
10440
  for (const flag of params.filter((p) => p.type === "flag")) {
10418
- const rest = src === null ? null : takeFlag(text, flag.name);
10441
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
10419
10442
  args[flag.name] = rest !== null;
10420
10443
  if (rest) [text, at] = trimmed(slice(text, rest), at + rest[0]);
10421
10444
  }
@@ -10611,6 +10634,8 @@ var RESERVED_NAME = "__proto__";
10611
10634
  function variableNameError(name, label = name) {
10612
10635
  return name === "__proto__" ? `"${label}" cannot be used as a variable name (${RESERVED_NAME} is reserved)` : void 0;
10613
10636
  }
10637
+ /** Whether a property key is an array index (`"0"`, `"12"`; not `"01"`). */
10638
+ var isArrayIndex = (key) => /^(?:0|[1-9]\d*)$/.test(key);
10614
10639
  /** Whether `obj` holds `key` as an own property. */
10615
10640
  var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
10616
10641
  /**
@@ -10903,24 +10928,50 @@ function nestedPiece(piece, toRoot, where) {
10903
10928
  ...nested
10904
10929
  };
10905
10930
  }
10931
+ /** An escape sequence of a JavaScript string literal (with its backslash). */
10932
+ var JS_ESCAPE_RE = /\\(?:u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-3][0-7]{0,2}|[4-7][0-7]?|\r\n|[^])/y;
10933
+ /**
10934
+ * The escape written at `raw[i]` (a backslash): how long it is as written and
10935
+ * what it stands for, or none when it is not one under these `escapes`.
10936
+ */
10937
+ function escapeAt(raw, i, escapes) {
10938
+ if (escapes === "quotes") {
10939
+ const next = raw.charAt(i + 1);
10940
+ return /["'\\]/.test(next) ? {
10941
+ length: 2,
10942
+ text: next
10943
+ } : void 0;
10944
+ }
10945
+ JS_ESCAPE_RE.lastIndex = i;
10946
+ const written = JS_ESCAPE_RE.exec(raw)?.[0];
10947
+ const text = written && stringLiteralValue(`"${written}"`);
10948
+ return typeof text === "string" ? {
10949
+ length: written.length,
10950
+ text
10951
+ } : void 0;
10952
+ }
10906
10953
  /**
10907
10954
  * Where each character of `value`, the unescaped text of a quoted string
10908
- * written as `raw` from `at` on (a backslash before a quote or a backslash
10909
- * is dropped), is
10910
- * in the source, and where the text ends. None when the text is where its
10911
- * length says, or is not that string.
10955
+ * written as `raw` from `at` on (its escapes are those of `escapes`), is in
10956
+ * the source, and where the text ends. A character that an escape stands for
10957
+ * is where the escape begins. None when the text is where its length says, or
10958
+ * is not that string.
10912
10959
  */
10913
- function escapeOffsets(raw, at, value) {
10960
+ function escapeOffsets(raw, at, value, escapes) {
10914
10961
  const offsets = [];
10915
10962
  let escaped = false;
10916
10963
  let i = 0;
10917
10964
  while (offsets.length < value.length) {
10918
10965
  if (i >= raw.length) return void 0;
10919
- offsets.push(at + i);
10920
- if (raw[i] === "\\" && /["'\\]/.test(raw.charAt(i + 1))) {
10921
- escaped = true;
10922
- i += 2;
10923
- } else i++;
10966
+ const escape = raw[i] === "\\" ? escapeAt(raw, i, escapes) : void 0;
10967
+ if (!escape) {
10968
+ offsets.push(at + i++);
10969
+ continue;
10970
+ }
10971
+ if (!value.startsWith(escape.text, offsets.length)) return void 0;
10972
+ for (let k = 0; k < escape.text.length; k++) offsets.push(at + i);
10973
+ escaped = true;
10974
+ i += escape.length;
10924
10975
  }
10925
10976
  offsets.push(at + i);
10926
10977
  return escaped ? offsets : void 0;
@@ -10943,7 +10994,7 @@ function* argPieces(args, offset, params, macro, label) {
10943
10994
  };
10944
10995
  return;
10945
10996
  }
10946
- yield* valuePieces(args, offset, params, values, spans, macro, label);
10997
+ yield* valuePieces(args, offset, params, values, spans, macro, label, "quotes");
10947
10998
  }
10948
10999
  /**
10949
11000
  * The code and text in the arguments `args` (at `offset`) of the widget
@@ -10969,13 +11020,14 @@ function* widgetPieces(args, offset, params, macro, label) {
10969
11020
  values[name] = value;
10970
11021
  spans.set(param, span);
10971
11022
  });
10972
- yield* valuePieces(args, offset, declared, values, spans, macro, label);
11023
+ yield* valuePieces(args, offset, declared, values, spans, macro, label, "javascript");
10973
11024
  }
10974
11025
  /**
10975
11026
  * The pieces of the `params` of `macro` with the `values` read from `args`
10976
- * (at `offset`), whose `spans` tell where each was written.
11027
+ * (at `offset`), whose `spans` tell where each was written and whose strings
11028
+ * are unescaped as `escapes` says.
10977
11029
  */
10978
- function* valuePieces(args, offset, params, values, spans, macro, label) {
11030
+ function* valuePieces(args, offset, params, values, spans, macro, label, escapes) {
10979
11031
  const name = macro.toLowerCase();
10980
11032
  /** The pieces of the parameters `list`, with their values in `from`. */
10981
11033
  function* visit(list, from) {
@@ -11023,7 +11075,7 @@ function* valuePieces(args, offset, params, values, spans, macro, label) {
11023
11075
  }
11024
11076
  const at = offset + start + (value !== written && /^["']/.test(written) ? 1 : 0);
11025
11077
  const holds = stringHolds(param);
11026
- const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value);
11078
+ const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value, escapes);
11027
11079
  if (holds === "expression" || holds === "statements") {
11028
11080
  const piece = {
11029
11081
  kind: "code",
@@ -11089,20 +11141,21 @@ function attributeValues(src, token) {
11089
11141
  }
11090
11142
  /**
11091
11143
  * The `{$…}` expressions in the value of a code attribute (`onclick`, see
11092
- * isCodeAttribute), with where each is in the value.
11144
+ * isCodeAttribute), with where each is in the value. The parts of the value
11145
+ * are written out as they are (splitSigilTemplate decodes nothing), so each
11146
+ * starts where the one before it ends: an expression is not found by its
11147
+ * text, which a string of the code may repeat.
11093
11148
  */
11094
11149
  function sigilExpressions(value) {
11095
11150
  const found = [];
11096
11151
  let from = 0;
11097
- for (const part of splitSigilTemplate(value)) {
11098
- if (!("expr" in part)) continue;
11099
- const at = locate(value, part.expr, from);
11100
- from = at + part.expr.length;
11152
+ for (const part of splitSigilTemplate(value)) if ("expr" in part) {
11101
11153
  found.push({
11102
11154
  expr: part.expr,
11103
- at
11155
+ at: from + 1
11104
11156
  });
11105
- }
11157
+ from += part.expr.length + 2;
11158
+ } else from += ("text" in part ? part.text : part.verbatim).length;
11106
11159
  return found;
11107
11160
  }
11108
11161
  /**
@@ -11170,7 +11223,9 @@ function tokenTextContainsChildren(token, parametersOf = registeredParameters, s
11170
11223
  /**
11171
11224
  * Recursively scan an AST node array for a VariableNode
11172
11225
  * with scope 'local' and name 'children' (@children), in the content and in
11173
- * the attributes and labels that render markup.
11226
+ * the attributes and labels that render markup. A nested `{widget}` is not
11227
+ * entered: its slot belongs to the innermost widget (as widgetDefinitions
11228
+ * reads it), and a definition renders nothing of its own.
11174
11229
  */
11175
11230
  function astContainsChildren(nodes, parametersOf = registeredParameters) {
11176
11231
  for (const node of nodes) {
@@ -11188,6 +11243,7 @@ function astContainsChildren(nodes, parametersOf = registeredParameters) {
11188
11243
  }, parametersOf) || astContainsChildren(node.children, parametersOf)) return true;
11189
11244
  }
11190
11245
  if (node.type === "macro") {
11246
+ if (node.name.toLowerCase() === "widget") continue;
11191
11247
  if (tokenTextContainsChildren({
11192
11248
  isClose: false,
11193
11249
  nameStart: 0,
@@ -11313,6 +11369,19 @@ function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
11313
11369
  }
11314
11370
  return found;
11315
11371
  }
11372
+ /**
11373
+ * The definitions the runtime ends up with, one per widget name: the closed
11374
+ * ones, the latest winning as registration replaces a widget. The widget
11375
+ * passages register before StoryInit runs, so StoryInit's definitions come
11376
+ * last whatever the passage order. Read with the flat scanner, so a nested
11377
+ * definition owns its own `{@children}`.
11378
+ */
11379
+ function effectiveWidgetDefinitions(definitions) {
11380
+ const inInit = (def) => def.passage === "StoryInit";
11381
+ const effective = new NameMap();
11382
+ for (const def of [...definitions.filter((def) => !inInit(def)), ...definitions.filter(inInit)]) if (def.closeStart !== void 0) effective.set(def.name, def);
11383
+ return [...effective.values()];
11384
+ }
11316
11385
  //#endregion
11317
11386
  //#region src/markup/validate.ts
11318
11387
  /**
@@ -11526,10 +11595,12 @@ function validateMarkup(passages, options) {
11526
11595
  * an operator, a reference, a spread) is "not static", which is no error: the
11527
11596
  * value is simply not known without running the code.
11528
11597
  */
11529
- var NUMBER_RE = /(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d+)?)(n?)/y;
11598
+ var NUMBER_RE = /(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?)(n?)/y;
11530
11599
  var IDENT_RE = /[A-Za-z_$][\w$]*/y;
11531
11600
  var KEY_RE = /[\w$]+/y;
11532
11601
  var ARROW_RE = /(?:async\s+)?(?:\((?:[^()]|\([^()]*\))*\)|[A-Za-z_$][\w$]*)\s*=>/y;
11602
+ /** The end of a line: the four line terminators of JavaScript. */
11603
+ var LINE_END_RE = /[\n\r\u2028\u2029]/g;
11533
11604
  var ARRAY_INDEX_RE = /^(?:0|[1-9]\d{0,8})$/;
11534
11605
  var UNSUPPORTED_UNDEFINED = {
11535
11606
  unsupported: "undefined",
@@ -11551,6 +11622,22 @@ function entryOrder(keys) {
11551
11622
  const all = [...keys];
11552
11623
  return [...all.filter((key) => ARRAY_INDEX_RE.test(key)).sort((a, b) => Number(a) - Number(b)), ...all.filter((key) => !ARRAY_INDEX_RE.test(key))];
11553
11624
  }
11625
+ /**
11626
+ * Where the regex literals in `src` are, by their start: JavaScript text
11627
+ * cannot tell a regex from a division without the code before it, which the
11628
+ * lexer reads. `handlers` see the same walk.
11629
+ */
11630
+ function regexLiterals(src, goal = "expression", handlers = {}) {
11631
+ const ends = /* @__PURE__ */ new Map();
11632
+ lexJs(src, {
11633
+ ...handlers,
11634
+ literal(text, index, nesting) {
11635
+ if (text.charAt(0) === "/" && !/^\/[/*]/.test(text)) ends.set(index, index + text.length);
11636
+ handlers.literal?.(text, index, nesting);
11637
+ }
11638
+ }, goal);
11639
+ return ends;
11640
+ }
11554
11641
  /** `String(value)` of a BigInt literal's digits, or `undefined` if they are no BigInt. */
11555
11642
  function bigintValue(digits) {
11556
11643
  try {
@@ -11564,9 +11651,15 @@ function bigintValue(digits) {
11564
11651
  * helpers that skip what is not read are shared (see macro-discovery.ts).
11565
11652
  */
11566
11653
  var Reader = class {
11567
- constructor(src) {
11654
+ /**
11655
+ * `regexes` (see regexLiterals) are read from `src` when they are first
11656
+ * needed, unless the caller has them already.
11657
+ */
11658
+ constructor(src, options = {}) {
11568
11659
  this.src = src;
11569
11660
  this.i = 0;
11661
+ this.goal = options.goal ?? "expression";
11662
+ this.regexes = options.regexes;
11570
11663
  }
11571
11664
  /** Skip whitespace and comments. */
11572
11665
  space() {
@@ -11574,8 +11667,8 @@ var Reader = class {
11574
11667
  for (;;) {
11575
11668
  while (/\s/.test(src.charAt(this.i))) this.i++;
11576
11669
  if (src.startsWith("//", this.i)) {
11577
- const end = src.indexOf("\n", this.i);
11578
- this.i = end < 0 ? src.length : end;
11670
+ LINE_END_RE.lastIndex = this.i;
11671
+ this.i = LINE_END_RE.test(src) ? LINE_END_RE.lastIndex - 1 : src.length;
11579
11672
  } else if (src.startsWith("/*", this.i)) {
11580
11673
  const end = src.indexOf("*/", this.i + 2);
11581
11674
  this.i = end < 0 ? src.length : end + 2;
@@ -11634,10 +11727,9 @@ var Reader = class {
11634
11727
  i++;
11635
11728
  while (/\s/.test(src.charAt(i))) i++;
11636
11729
  }
11637
- NUMBER_RE.lastIndex = i;
11638
- const match = NUMBER_RE.exec(src);
11730
+ const match = this.numberAt(i);
11639
11731
  if (match) {
11640
- this.i = NUMBER_RE.lastIndex;
11732
+ this.i = i + match[0].length;
11641
11733
  if (!match[1]) return { shape: { type: "number" } };
11642
11734
  if (sign === "+") return { throws: "Cannot convert a BigInt value to a number" };
11643
11735
  const digits = bigintValue(match[0].slice(0, -1));
@@ -11647,11 +11739,17 @@ var Reader = class {
11647
11739
  };
11648
11740
  }
11649
11741
  IDENT_RE.lastIndex = i;
11650
- if (IDENT_RE.exec(src)?.[0] === "Infinity") {
11742
+ const word = IDENT_RE.exec(src)?.[0];
11743
+ if (word === "Infinity" || word === "NaN") {
11651
11744
  this.i = IDENT_RE.lastIndex;
11652
11745
  return { shape: { type: "number" } };
11653
11746
  }
11654
11747
  }
11748
+ /** The numeric literal (a BigInt's `n` is `match[1]`) at `at`, if there is one. */
11749
+ numberAt(at) {
11750
+ NUMBER_RE.lastIndex = at;
11751
+ return NUMBER_RE.exec(this.src);
11752
+ }
11655
11753
  /** A keyword, a function, or a name (which is not static). */
11656
11754
  word() {
11657
11755
  const { src } = this;
@@ -11671,6 +11769,7 @@ var Reader = class {
11671
11769
  this.i = end;
11672
11770
  return { shape: { type: "null" } };
11673
11771
  case "NaN":
11772
+ case "Infinity":
11674
11773
  this.i = end;
11675
11774
  return { shape: { type: "number" } };
11676
11775
  case "undefined":
@@ -11811,14 +11910,22 @@ var Reader = class {
11811
11910
  const { src } = this;
11812
11911
  const c = src.charAt(this.i);
11813
11912
  if (c === "\"" || c === "'") return this.stringValue();
11913
+ if (/[\d.]/.test(c)) return this.numberKey();
11814
11914
  KEY_RE.lastIndex = this.i;
11815
11915
  const found = KEY_RE.exec(src)?.[0];
11816
11916
  if (found === void 0) return void 0;
11817
11917
  this.i = KEY_RE.lastIndex;
11818
- if (!/^\d/.test(found)) return found;
11819
- const digits = found.replace(/_/g, "");
11918
+ return found;
11919
+ }
11920
+ /** A number as a key: the whole literal, named as the runtime names it. */
11921
+ numberKey() {
11922
+ const match = this.numberAt(this.i);
11923
+ if (!match) return void 0;
11924
+ this.i += match[0].length;
11925
+ if (/[\w$]/.test(this.src.charAt(this.i))) return void 0;
11926
+ const digits = match[0].replace(/_/g, "");
11820
11927
  if (/^0\d/.test(digits)) return void 0;
11821
- if (digits.endsWith("n") && !/^0[xX]/.test(digits)) return bigintValue(digits.slice(0, -1));
11928
+ if (match[1]) return bigintValue(digits.slice(0, -1));
11822
11929
  const value = Number(digits);
11823
11930
  return Number.isNaN(value) ? void 0 : String(value);
11824
11931
  }
@@ -11861,6 +11968,14 @@ var Reader = class {
11861
11968
  this.space();
11862
11969
  return true;
11863
11970
  }
11971
+ if (c === "/") {
11972
+ this.regexes ?? (this.regexes = regexLiterals(src, this.goal));
11973
+ const end = this.regexes.get(this.i);
11974
+ if (end !== void 0) {
11975
+ this.i = end;
11976
+ return true;
11977
+ }
11978
+ }
11864
11979
  if (c === "[" || c === "{" || c === "(") return this.skipBalanced();
11865
11980
  if (c === "]" || c === "}" || c === ")") return false;
11866
11981
  this.i++;
@@ -12115,6 +12230,7 @@ function checkReference(ref, declared) {
12115
12230
  const part = ref.path[i];
12116
12231
  if (current.type === "array") return null;
12117
12232
  if (current.type === "null") return null;
12233
+ if (current.type === "string" && isArrayIndex(part)) continue;
12118
12234
  const sample = PRIMITIVE_SAMPLES[current.type];
12119
12235
  if (sample && part in sample) {
12120
12236
  const memberType = typeof sample[part];
@@ -12131,10 +12247,28 @@ function checkReference(ref, declared) {
12131
12247
  return null;
12132
12248
  }
12133
12249
  var NO_STORE_VAR_MACROS = /* @__PURE__ */ new Set();
12134
- /** A reference written at `index` of `code`, with its dot path. */
12135
- function referenceAt(code, index, at) {
12250
+ /** A `.field` path written right after a reference, which may be empty. */
12251
+ var FIELD_PATH_RE = /(?:\.\w+)*/y;
12252
+ /**
12253
+ * The reference to variable `name`, which JavaScript reads at `[start, end)`
12254
+ * of `code` (the sigil and the name as written, which may be spelled with
12255
+ * escapes), with the dot path written after it.
12256
+ */
12257
+ function referenceAt(code, sigil, name, start, end, at) {
12258
+ FIELD_PATH_RE.lastIndex = end;
12259
+ const fields = FIELD_PATH_RE.exec(code)[0];
12260
+ return {
12261
+ sigil,
12262
+ name,
12263
+ path: fields ? fields.slice(1).split(".") : [],
12264
+ start: at(start),
12265
+ end: at(end + fields.length)
12266
+ };
12267
+ }
12268
+ /** A reference written at `index` of `term`, a `variable` parameter as written. */
12269
+ function termReferenceAt(term, index, at) {
12136
12270
  VAR_PATH_RE.lastIndex = index;
12137
- const match = VAR_PATH_RE.exec(code);
12271
+ const match = VAR_PATH_RE.exec(term);
12138
12272
  if (!match) return void 0;
12139
12273
  const [name, ...path] = match[2].split(".");
12140
12274
  return {
@@ -12179,46 +12313,51 @@ function scanCode(code, at, emit, goal = "expression") {
12179
12313
  }
12180
12314
  for (const ref of parsed.refs) {
12181
12315
  if (ref.sigil !== "$" && ref.sigil !== "%") continue;
12182
- const found = referenceAt(code, ref.start, at);
12183
- if (found) emit(found);
12316
+ emit(referenceAt(code, ref.sigil, ref.name, ref.start, ref.end, at));
12184
12317
  }
12185
12318
  }
12186
12319
  /** `scanCode` for code acorn can't parse: lexed leniently. */
12187
12320
  function scanCodeLeniently(code, at, emit, goal) {
12188
12321
  lexJs(code, {
12189
- variable(sigil, _name, index) {
12322
+ variable(sigil, name, index, _nesting, end) {
12190
12323
  if (sigil !== "$" && sigil !== "%") return;
12191
- const found = referenceAt(code, index, at);
12192
- if (found) emit(found);
12324
+ emit(referenceAt(code, sigil, name, index, end, at));
12193
12325
  },
12194
12326
  literal() {}
12195
12327
  }, goal);
12196
12328
  }
12329
+ /** Report the references in the pieces of code and markup text of arguments. */
12330
+ function scanPieces(pieces, at, emit, options) {
12331
+ for (const piece of pieces) {
12332
+ const pieceAt = (i) => at(pieceOffset(piece, i));
12333
+ if (piece.kind === "code") scanCode(piece.code, pieceAt, emit, piece.goal);
12334
+ else if (piece.kind === "text") scanInterpolations(piece.text, pieceAt, emit, {
12335
+ ...options,
12336
+ storeVarMacros: NO_STORE_VAR_MACROS
12337
+ });
12338
+ }
12339
+ }
12197
12340
  /**
12198
12341
  * Report the references in the arguments of a macro by what its parameters
12199
12342
  * say each holds (see ParameterDef.holds): code is scanned as code and
12200
12343
  * markup as markup, but literal text (a placeholder, a passage name) holds
12201
12344
  * none. A macro without declared parameters, or arguments that do not
12202
- * parse, are scanned as code.
12345
+ * parse, are scanned as code. The arguments of a widget that declares what
12346
+ * some parameters hold are also read by those (see widgetPieces).
12203
12347
  */
12204
- function scanArgs(token, params, at, emit, options) {
12348
+ function scanArgs(token, parametersOf, at, emit, options) {
12205
12349
  if (!token.rawArgs) return;
12350
+ const params = parametersOf(token.name);
12351
+ let byParameters = false;
12206
12352
  if (params) {
12207
12353
  if (options.all && !options.storeVarMacros.has(token.name.toLowerCase())) scanVariableParameters(token, params, at, emit);
12208
12354
  const pieces = [...argPieces(token.rawArgs, token.argsStart, params, token.name, "")];
12209
- if (!pieces.some((piece) => piece.kind === "argument-error")) {
12210
- for (const piece of pieces) {
12211
- const pieceAt = (i) => at(pieceOffset(piece, i));
12212
- if (piece.kind === "code") scanCode(piece.code, pieceAt, emit, piece.goal);
12213
- else if (piece.kind === "text") scanInterpolations(piece.text, pieceAt, emit, {
12214
- ...options,
12215
- storeVarMacros: NO_STORE_VAR_MACROS
12216
- });
12217
- }
12218
- return;
12219
- }
12355
+ byParameters = !pieces.some((piece) => piece.kind === "argument-error");
12356
+ if (byParameters) scanPieces(pieces, at, emit, options);
12220
12357
  }
12221
- scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
12358
+ if (!byParameters) scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
12359
+ const widget = parametersOf.widget?.(token.name);
12360
+ if (widget) scanPieces(widgetPieces(token.rawArgs, token.argsStart, widget, token.name, ""), at, emit, options);
12222
12361
  }
12223
12362
  /**
12224
12363
  * Report the variables the `variable` parameters of a macro name
@@ -12236,7 +12375,7 @@ function scanVariableParameters(token, params, at, emit) {
12236
12375
  for (const param of params) {
12237
12376
  const span = spans.get(param);
12238
12377
  if (param.type !== "variable" || !span) continue;
12239
- const ref = referenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
12378
+ const ref = termReferenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
12240
12379
  if (ref) emit(ref);
12241
12380
  }
12242
12381
  }
@@ -12277,7 +12416,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
12277
12416
  else scanInterpolations(value, valueIn, emit, options);
12278
12417
  }
12279
12418
  else if (token.type === "macro" && !token.isClose) {
12280
- scanArgs(token, parametersOf(token.name), at, emit, options);
12419
+ scanArgs(token, parametersOf, at, emit, options);
12281
12420
  scanSelectors(content, token, at, emit, options);
12282
12421
  if (storeVarMacros.has(token.name.toLowerCase())) {
12283
12422
  const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
@@ -12320,7 +12459,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
12320
12459
  function collectVariableReferences(content, options) {
12321
12460
  const found = [];
12322
12461
  withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), options));
12323
- return found;
12462
+ return found.sort((a, b) => a.start - b.start);
12324
12463
  }
12325
12464
  /**
12326
12465
  * The invalid variable references of the passages, against what is declared,
@@ -12348,6 +12487,461 @@ function checkVariableReferences(passages, declared, options) {
12348
12487
  return diagnostics;
12349
12488
  }
12350
12489
  //#endregion
12490
+ //#region src/js-bindings.ts
12491
+ var CLOSERS = {
12492
+ "}": "{",
12493
+ ")": "(",
12494
+ "]": "["
12495
+ };
12496
+ /** What `(…) {` is when a word like this is before the `(`: a block. */
12497
+ var BLOCK_WORDS = /* @__PURE__ */ new Set([
12498
+ "if",
12499
+ "for",
12500
+ "while",
12501
+ "switch",
12502
+ "with",
12503
+ "catch"
12504
+ ]);
12505
+ var NOT_PARAMETERS = /* @__PURE__ */ new Set([
12506
+ "if",
12507
+ "for",
12508
+ "while",
12509
+ "switch",
12510
+ "with"
12511
+ ]);
12512
+ var DECLARATIONS = /* @__PURE__ */ new Set([
12513
+ "const",
12514
+ "let",
12515
+ "var"
12516
+ ]);
12517
+ /** After a name: `=`, `+=`, `&&=`, `++` and the other ways to give it a value. */
12518
+ var WRITE_RE = /(?:(?:\*\*|<<|>>>?|&&|\|\||\?\?|[-+*/%&|^])=(?!=)|=(?![=>])|\+\+|--)/y;
12519
+ /** A call of these on `x.list` changes `x`; as does one of these on `x` itself. */
12520
+ var MUTATORS = /* @__PURE__ */ new Set([
12521
+ "push",
12522
+ "pop",
12523
+ "shift",
12524
+ "unshift",
12525
+ "splice",
12526
+ "sort",
12527
+ "reverse",
12528
+ "fill",
12529
+ "copyWithin"
12530
+ ]);
12531
+ var MUTATING_CALL_RE = /(?:Object|Reflect)\s*\.\s*(?:assign|defineProperty|defineProperties|setPrototypeOf|set|deleteProperty)\s*$/;
12532
+ /** Before a name in a pattern or parameter list, by the group around it. */
12533
+ var BEFORE_BINDING = {
12534
+ "{": "{,:",
12535
+ "[": "[,",
12536
+ "(": "(,"
12537
+ };
12538
+ var isWordChar = (c) => !!c && /[\w$]/.test(c);
12539
+ /** Resolve the declaration of variables in `code` (see blankedCode in macro-discovery). */
12540
+ var Bindings = class {
12541
+ constructor(code) {
12542
+ this.code = code;
12543
+ this.groups = [];
12544
+ this.byOpen = /* @__PURE__ */ new Map();
12545
+ this.byClose = /* @__PURE__ */ new Map();
12546
+ this.functions = /* @__PURE__ */ new Map();
12547
+ this.top = {
12548
+ start: -1,
12549
+ end: Infinity
12550
+ };
12551
+ this.readGroups();
12552
+ }
12553
+ /**
12554
+ * The `{` of the object literal that `name`, used at `at`, is declared as
12555
+ * (`const`, `let` or `var`), when that is the declaration it names: the
12556
+ * innermost one in the scope of the use, that comes before it unless the
12557
+ * use is in a function of its own. `undefined` if it names another value,
12558
+ * more than one declaration is the innermost, or the value is written to
12559
+ * (given another, or one of its `properties` set) where the use can follow.
12560
+ */
12561
+ objectOf(name, at, properties) {
12562
+ const { code } = this;
12563
+ const escaped = name.replace(/\$/g, "\\$");
12564
+ const bindings = [];
12565
+ for (const m of code.matchAll(new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`, "g"))) {
12566
+ const binding = this.bindingAt(m.index, name.length, properties);
12567
+ if (binding) bindings.push(binding);
12568
+ }
12569
+ const declarations = bindings.filter((b) => !b.write);
12570
+ for (const b of bindings) if (b.write) b.scope = this.innermostVisible(declarations, b.at)[0]?.scope ?? this.top;
12571
+ const found = this.innermostVisible(bindings, at);
12572
+ return found.length === 1 ? found[0].object : void 0;
12573
+ }
12574
+ /**
12575
+ * Of the `bindings` the use at `at` can see, those in the innermost scope:
12576
+ * the scope is the use's, and a binding comes before it, unless the use is
12577
+ * in a function of its own.
12578
+ */
12579
+ innermostVisible(bindings, at) {
12580
+ const useFunction = this.functionStart(at);
12581
+ const visible = bindings.filter((b) => b.scope.start <= at && at < b.scope.end && (!b.ordered || b.at < at || this.functionStart(b.at) !== useFunction));
12582
+ const innermost = Math.max(...visible.map((b) => b.scope.start));
12583
+ return visible.filter((b) => b.scope.start === innermost);
12584
+ }
12585
+ readGroups() {
12586
+ const { code, groups } = this;
12587
+ const stack = [];
12588
+ for (let i = 0; i < code.length; i++) {
12589
+ const c = code.charAt(i);
12590
+ if (c === "{" || c === "(" || c === "[") {
12591
+ const group = {
12592
+ kind: c,
12593
+ open: i,
12594
+ close: code.length,
12595
+ parent: stack[stack.length - 1]
12596
+ };
12597
+ groups.push(group);
12598
+ stack.push(group);
12599
+ this.byOpen.set(i, group);
12600
+ } else if (CLOSERS[c]) {
12601
+ let k = stack.length - 1;
12602
+ while (k >= 0 && stack[k].kind !== CLOSERS[c]) k--;
12603
+ if (k >= 0) {
12604
+ stack[k].close = i;
12605
+ this.byClose.set(i, stack[k]);
12606
+ stack.length = k;
12607
+ }
12608
+ }
12609
+ }
12610
+ }
12611
+ /** The innermost group that has `index` inside it, of this kind if given. */
12612
+ innermost(index, kind) {
12613
+ const { groups } = this;
12614
+ for (let k = groups.length - 1; k >= 0; k--) {
12615
+ const g = groups[k];
12616
+ if (g.open < index && index < g.close && (!kind || g.kind === kind)) return g;
12617
+ }
12618
+ }
12619
+ /**
12620
+ * The word before a `(` group (`if`, `for`, `catch`, a function's name…);
12621
+ * `for await` is `for`.
12622
+ */
12623
+ ownerWord(paren) {
12624
+ const word = this.wordBefore(this.backFrom(paren.open) + 1);
12625
+ if (word.text !== "await") return word.text;
12626
+ const before = this.wordBefore(this.backFrom(word.start) + 1).text;
12627
+ return before === "for" ? before : word.text;
12628
+ }
12629
+ /**
12630
+ * Whether the `{` group is the body of a function (or method), or of a
12631
+ * class static block, which has the scope of a `var` of its own.
12632
+ */
12633
+ isFunctionBody(group) {
12634
+ if (group.kind !== "{") return false;
12635
+ let known = this.functions.get(group);
12636
+ if (known === void 0) {
12637
+ const before = this.backFrom(group.open);
12638
+ const { code } = this;
12639
+ if (code.charAt(before) === ")") {
12640
+ const params = this.byClose.get(before);
12641
+ known = !!params && !BLOCK_WORDS.has(this.ownerWord(params));
12642
+ } else known = code.slice(before - 1, before + 1) === "=>" || this.wordBefore(before + 1).text === "static";
12643
+ this.functions.set(group, known);
12644
+ }
12645
+ return known;
12646
+ }
12647
+ /** The start of the function that has `index` in its body, or -1. */
12648
+ functionStart(index) {
12649
+ for (let g = this.innermost(index, "{"); g; g = g.parent) if (g.kind === "{" && this.isFunctionBody(g)) return g.open;
12650
+ return -1;
12651
+ }
12652
+ scopeOf(group) {
12653
+ return group ? {
12654
+ start: group.open,
12655
+ end: group.close
12656
+ } : this.top;
12657
+ }
12658
+ /** The block `index` is in: what `let` and `const` declare for. */
12659
+ blockAt(index) {
12660
+ return this.scopeOf(this.innermost(index, "{"));
12661
+ }
12662
+ /** The function (or the whole text) `index` is in: what `var` declares for. */
12663
+ functionAt(index) {
12664
+ const start = this.functionStart(index);
12665
+ return start < 0 ? this.top : this.scopeOf(this.byOpen.get(start));
12666
+ }
12667
+ /**
12668
+ * What the declaration keyword `word` (`var`, `let`, `const`) declares for:
12669
+ * the function for `var`, the block for the others, or the `for` statement,
12670
+ * header and body, when the declaration is in its header.
12671
+ */
12672
+ declaredIn(word) {
12673
+ if (word.text === "var") return this.functionAt(word.start);
12674
+ const group = this.innermost(word.start);
12675
+ if (group?.kind === "(" && this.ownerWord(group) === "for") return {
12676
+ start: group.open,
12677
+ end: this.statementEnd(group.close + 1)
12678
+ };
12679
+ return this.blockAt(word.start);
12680
+ }
12681
+ /**
12682
+ * Where the statement that starts at `from` ends: a block, the body of an
12683
+ * `if`, `for`, `while` or `with` (and the `else` of an `if`), or else up to
12684
+ * a `;`, the closer of the group it is in, or a line break that is followed
12685
+ * by a statement of its own.
12686
+ */
12687
+ statementEnd(from) {
12688
+ const { code } = this;
12689
+ const start = this.forward(from);
12690
+ const block = this.byOpen.get(start);
12691
+ if (block?.kind === "{") return Math.min(block.close + 1, code.length);
12692
+ const word = this.wordAt(start);
12693
+ if (/^(?:if|for|while|with)$/.test(word)) {
12694
+ let paren = this.forward(start + word.length);
12695
+ if (word === "for" && this.wordAt(paren) === "await") paren = this.forward(paren + 5);
12696
+ const header = this.byOpen.get(paren);
12697
+ if (header) {
12698
+ const end = this.statementEnd(header.close + 1);
12699
+ const next = this.forward(end);
12700
+ return word === "if" && this.wordAt(next) === "else" ? this.statementEnd(next + 4) : end;
12701
+ }
12702
+ }
12703
+ for (let end = start; end < code.length; end++) {
12704
+ const c = code.charAt(end);
12705
+ if (c === ";") return end + 1;
12706
+ if (CLOSERS[c]) return end;
12707
+ const group = this.byOpen.get(end);
12708
+ if (group) end = group.close;
12709
+ else if (c === "\n" && this.startsStatement(end)) return end;
12710
+ }
12711
+ return code.length;
12712
+ }
12713
+ /** Whether the line break at `index` ends a statement, and one follows. */
12714
+ startsStatement(index) {
12715
+ const next = this.forward(index);
12716
+ return /[\w$)\]}]/.test(this.code.charAt(this.backFrom(index))) && isWordChar(this.code.charAt(next)) && !/^(?:in|of|instanceof|else)$/.test(this.wordAt(next));
12717
+ }
12718
+ /** What a parameter list, whose `)` is `close`, is the scope of: the body. */
12719
+ bodyAfter(close) {
12720
+ const next = this.forward(close + 1);
12721
+ if (this.code.charAt(next) === "{") return this.scopeOf(this.byOpen.get(next));
12722
+ return this.code.startsWith("=>", next) ? this.arrowBody(next + 2) : void 0;
12723
+ }
12724
+ /** The body of an arrow function, whose `=>` ends before `from`. */
12725
+ arrowBody(from) {
12726
+ const { code } = this;
12727
+ const start = this.forward(from);
12728
+ if (code.charAt(start) === "{") return this.scopeOf(this.byOpen.get(start));
12729
+ let end = start;
12730
+ while (end < code.length && !",;)]}".includes(code.charAt(end))) {
12731
+ end = this.byOpen.get(end)?.close ?? end;
12732
+ end++;
12733
+ }
12734
+ return {
12735
+ start,
12736
+ end
12737
+ };
12738
+ }
12739
+ /** The index of the last character that is no space before `index`, or -1. */
12740
+ backFrom(index) {
12741
+ let i = index - 1;
12742
+ while (i >= 0 && /\s/.test(this.code.charAt(i))) i--;
12743
+ return i;
12744
+ }
12745
+ /** The index of the first character that is no space from `index` on. */
12746
+ forward(index) {
12747
+ let i = index;
12748
+ while (i < this.code.length && /\s/.test(this.code.charAt(i))) i++;
12749
+ return i;
12750
+ }
12751
+ /** The word that starts at `index` (empty if there is none). */
12752
+ wordAt(index) {
12753
+ return this.code.slice(index, this.nameEnd(index));
12754
+ }
12755
+ /** The word that ends before `end`, and where it starts. */
12756
+ wordBefore(end) {
12757
+ let start = end;
12758
+ while (start > 0 && isWordChar(this.code.charAt(start - 1))) start--;
12759
+ return {
12760
+ text: this.code.slice(start, end),
12761
+ start
12762
+ };
12763
+ }
12764
+ /**
12765
+ * What the name of `length` characters at `at` declares, or writes to, if it
12766
+ * does. A write to a `properties` of it counts, one to another does not.
12767
+ */
12768
+ bindingAt(at, length, properties) {
12769
+ const { code } = this;
12770
+ let before = this.backFrom(at);
12771
+ const spread = code.slice(before - 2, before + 1) === "...";
12772
+ if (code.charAt(before) === "." && !spread) return void 0;
12773
+ if (spread) before = this.backFrom(before - 2);
12774
+ const after = this.forward(at + length);
12775
+ return this.declarationAt(at, before, spread) ?? this.patternAt(at, before, after) ?? this.arrowParameterAt(at, after) ?? (spread ? void 0 : this.writeAt(at, before, after, properties));
12776
+ }
12777
+ /** `const x`, `let x`, `var x`, a later `y` of `let x, y`, `function x`, `class x`. */
12778
+ declarationAt(at, before, spread) {
12779
+ if (spread) return void 0;
12780
+ const word = this.code.charAt(before) === "," ? this.listKeyword(before) : this.wordBefore(before + 1);
12781
+ if (!word || this.code.charAt(word.start - 1) === ".") return void 0;
12782
+ if (DECLARATIONS.has(word.text)) {
12783
+ const scope = this.declaredIn(word);
12784
+ const init = /\s*=\s*(?=\{)/y;
12785
+ init.lastIndex = this.nameEnd(at);
12786
+ return {
12787
+ scope,
12788
+ at,
12789
+ ordered: true,
12790
+ object: init.test(this.code) ? init.lastIndex : void 0
12791
+ };
12792
+ }
12793
+ if (word.text === "function" || word.text === "class") return {
12794
+ scope: this.blockAt(word.start),
12795
+ at,
12796
+ ordered: word.text === "class"
12797
+ };
12798
+ }
12799
+ /**
12800
+ * The `const`, `let` or `var` of the declaration list that the `,` at
12801
+ * `comma` is in (`let a = 1, b`, also in a `for` header): the nearest one
12802
+ * before it in the same brackets, that no `;` is between.
12803
+ */
12804
+ listKeyword(comma) {
12805
+ const { code } = this;
12806
+ const floor = this.innermost(comma)?.open ?? -1;
12807
+ for (let i = comma - 1; i > floor; i--) {
12808
+ const c = code.charAt(i);
12809
+ if (c === ";") return void 0;
12810
+ const group = CLOSERS[c] ? this.byClose.get(i) : void 0;
12811
+ if (group) i = group.open;
12812
+ else if (isWordChar(c)) {
12813
+ const word = this.wordBefore(i + 1);
12814
+ if (DECLARATIONS.has(word.text) && code.charAt(word.start - 1) !== ".") return word;
12815
+ i = word.start;
12816
+ }
12817
+ }
12818
+ }
12819
+ nameEnd(at) {
12820
+ let end = at;
12821
+ while (isWordChar(this.code.charAt(end))) end++;
12822
+ return end;
12823
+ }
12824
+ /**
12825
+ * A name in a pattern (`const { x } = …`) or a parameter list; or one a
12826
+ * pattern assigns to (`({ x } = …)`).
12827
+ */
12828
+ patternAt(at, before, after) {
12829
+ const { code } = this;
12830
+ const inner = this.innermost(at);
12831
+ if (!inner || !BEFORE_BINDING[inner.kind].includes(code.charAt(before))) return;
12832
+ if (inner.kind === "{" && code.charAt(after) === ":") return void 0;
12833
+ let pattern;
12834
+ for (let group = inner; group; group = group.parent) {
12835
+ if (group.kind === "(") {
12836
+ const scope = NOT_PARAMETERS.has(this.ownerWord(group)) ? void 0 : this.bodyAfter(group.close);
12837
+ return scope ? {
12838
+ scope,
12839
+ at,
12840
+ ordered: false
12841
+ } : this.patternWriteAt(at, pattern);
12842
+ }
12843
+ pattern = group;
12844
+ const open = this.backFrom(group.open);
12845
+ const word = code.charAt(open) === "," ? this.listKeyword(open) : this.wordBefore(open + 1);
12846
+ if (word && DECLARATIONS.has(word.text)) return {
12847
+ scope: this.declaredIn(word),
12848
+ at,
12849
+ ordered: true
12850
+ };
12851
+ if (!"({[,:".includes(code.charAt(open))) break;
12852
+ }
12853
+ return this.patternWriteAt(at, pattern);
12854
+ }
12855
+ /** `[x] = …`, `({ x } = …)`, `for ({ x } of …)`: a name that is assigned to. */
12856
+ patternWriteAt(at, pattern) {
12857
+ if (!pattern) return void 0;
12858
+ const { code } = this;
12859
+ const open = this.backFrom(pattern.open);
12860
+ if (/[\w$)\]]/.test(code.charAt(open))) return void 0;
12861
+ const next = this.forward(pattern.close + 1);
12862
+ return pattern.parent?.kind === "(" && this.ownerWord(pattern.parent) === "for" && /^(?:of|in)(?![\w$])/.test(code.slice(next)) || this.isWriteOperator(next) ? {
12863
+ scope: this.top,
12864
+ at,
12865
+ ordered: true,
12866
+ write: true
12867
+ } : void 0;
12868
+ }
12869
+ /** `x => …`. */
12870
+ arrowParameterAt(at, after) {
12871
+ return this.code.startsWith("=>", after) ? {
12872
+ scope: this.arrowBody(after + 2),
12873
+ at,
12874
+ ordered: false
12875
+ } : void 0;
12876
+ }
12877
+ /** Whether an assignment, `++` or `--` operator is at `index`. */
12878
+ isWriteOperator(index) {
12879
+ WRITE_RE.lastIndex = index;
12880
+ return WRITE_RE.test(this.code);
12881
+ }
12882
+ /**
12883
+ * `x = …`, `x += …`, `x++`, `for (x of …)`, and the writes to what it
12884
+ * holds that change the config it is (`x.name = …`, `delete x.name`,
12885
+ * `x.parameters.push(…)`, `Object.assign(x, …)`): a value not known.
12886
+ */
12887
+ writeAt(at, before, after, properties) {
12888
+ const { code } = this;
12889
+ if (this.isClassBody(this.innermost(at))) return void 0;
12890
+ const { keys, end } = this.memberChain(after);
12891
+ const written = ["++", "--"].includes(code.slice(before - 1, before + 1)) || this.isWriteOperator(end) || keys.length > 0 && (this.wordBefore(before + 1).text === "delete" || keys.length > 1 && code.charAt(end) === "(" && MUTATORS.has(keys[keys.length - 1])) || keys.length === 0 && this.isForTarget(before, end) || keys.length === 0 && this.isMutatedArgument(before, end);
12892
+ const first = keys[0];
12893
+ if (!written || first && !properties.has(first)) return void 0;
12894
+ return {
12895
+ scope: this.top,
12896
+ at,
12897
+ ordered: true,
12898
+ write: true
12899
+ };
12900
+ }
12901
+ /** Whether the group is the body of a class: its members are its own. */
12902
+ isClassBody(group) {
12903
+ if (group?.kind !== "{") return false;
12904
+ let start = group.open;
12905
+ while (start > 0 && !"{};".includes(this.code.charAt(start - 1))) start--;
12906
+ return /(?<![\w$.])class(?![\w$])/.test(this.code.slice(start, group.open));
12907
+ }
12908
+ /**
12909
+ * The properties read from a name at `from` (`.a.b[c]`, a key is null if
12910
+ * computed), and where the chain ends.
12911
+ */
12912
+ memberChain(from) {
12913
+ const { code } = this;
12914
+ const keys = [];
12915
+ let end = from;
12916
+ for (;;) {
12917
+ let i = end;
12918
+ if (code.startsWith("?.", i)) i += 2;
12919
+ else if (code.charAt(i) === "." && code.charAt(i + 1) !== ".") i++;
12920
+ else if (code.charAt(i) !== "[") break;
12921
+ i = this.forward(i);
12922
+ const bracket = code.charAt(i) === "[" ? this.byOpen.get(i) : void 0;
12923
+ const key = bracket ? "" : this.wordAt(i);
12924
+ if (!bracket && !key) break;
12925
+ keys.push(bracket ? null : key);
12926
+ end = this.forward(bracket ? bracket.close + 1 : i + key.length);
12927
+ }
12928
+ return {
12929
+ keys,
12930
+ end
12931
+ };
12932
+ }
12933
+ /** `for (x of …)`: the name is assigned each item. */
12934
+ isForTarget(before, end) {
12935
+ const group = this.byOpen.get(before);
12936
+ return group?.kind === "(" && this.ownerWord(group) === "for" && /^(?:of|in)(?![\w$])/.test(this.code.slice(end));
12937
+ }
12938
+ /** `Object.assign(x, …)` and the like: the name is the first argument. */
12939
+ isMutatedArgument(before, end) {
12940
+ const group = this.byOpen.get(before);
12941
+ return group?.kind === "(" && ",)".includes(this.code.charAt(end)) && MUTATING_CALL_RE.test(this.code.slice(0, group.open));
12942
+ }
12943
+ };
12944
+ //#endregion
12351
12945
  //#region src/macro-discovery.ts
12352
12946
  /**
12353
12947
  * What `defineMacro({ … })` calls in JavaScript declare, read from the text
@@ -12358,6 +12952,20 @@ function checkVariableReferences(passages, declared, options) {
12358
12952
  var CALL_RE = /(?<![\w$])defineMacro\s*\(\s*/g;
12359
12953
  var IDENTIFIER_ARGUMENT_RE = /^([A-Za-z_$][\w$]*)\s*[,)]/;
12360
12954
  var WORD_RE = /[A-Za-z_]+/y;
12955
+ /** Before the key of a member that is an accessor, an async method or a generator. */
12956
+ var MODIFIER_RE = /^(?:get|set|async)?$/;
12957
+ var KEY_START_RE = /[\w$'"[.*]/;
12958
+ /** The properties of a config that its macro is read from. */
12959
+ var CONFIG_KEYS = /* @__PURE__ */ new Set([
12960
+ "name",
12961
+ "block",
12962
+ "subMacros",
12963
+ "parameters",
12964
+ "interpolate",
12965
+ "storeVar",
12966
+ "merged",
12967
+ "description"
12968
+ ]);
12361
12969
  /** The literals of a config object, read to the end of what is static. */
12362
12970
  var ConfigReader = class extends Reader {
12363
12971
  constructor(..._args) {
@@ -12457,30 +13065,65 @@ var ConfigReader = class extends Reader {
12457
13065
  }
12458
13066
  record() {
12459
13067
  const props = /* @__PURE__ */ new Map();
12460
- return this.elements("}", () => {
12461
- const key = this.key();
12462
- this.space();
12463
- if (key !== void 0 && this.src.charAt(this.i) === ":") {
12464
- this.i++;
12465
- props.set(key, this.member());
12466
- } else if (!this.skipMember()) this.fail();
12467
- }) ? {
13068
+ return this.elements("}", () => this.property(props)) ? {
12468
13069
  type: "object",
12469
13070
  props
12470
13071
  } : void 0;
12471
13072
  }
13073
+ /**
13074
+ * A member: what it sets replaces an earlier member of the key. One that is
13075
+ * not a literal (a method, an accessor, a shorthand) sets its key to a
13076
+ * value not known; a spread of an object literal sets the members of it, a
13077
+ * spread of anything else or a computed key can set any key.
13078
+ */
13079
+ property(props) {
13080
+ const { src } = this;
13081
+ if (src.startsWith("...", this.i)) {
13082
+ this.i += 3;
13083
+ this.space();
13084
+ const spread = src.charAt(this.i) === "{" ? this.record() : void 0;
13085
+ this.space();
13086
+ if (spread?.type === "object" && this.atElementEnd()) {
13087
+ for (const [key, value] of spread.props) props.set(key, value);
13088
+ return;
13089
+ }
13090
+ props.clear();
13091
+ } else {
13092
+ let key = this.key();
13093
+ this.space();
13094
+ if (key !== void 0 && src.charAt(this.i) === ":") {
13095
+ this.i++;
13096
+ props.set(key, this.member());
13097
+ return;
13098
+ }
13099
+ if (MODIFIER_RE.test(key ?? "") && KEY_START_RE.test(src.charAt(this.i))) {
13100
+ if (src.charAt(this.i) === "*") this.i++;
13101
+ this.space();
13102
+ key = this.key();
13103
+ }
13104
+ if (key === void 0) props.clear();
13105
+ else props.set(key, void 0);
13106
+ }
13107
+ if (!this.skipMember()) this.fail();
13108
+ }
12472
13109
  /** Stop reading: the text cannot be skipped through. */
12473
13110
  fail() {
12474
13111
  this.failed = true;
12475
13112
  }
12476
13113
  };
12477
- /** The text with everything but code (strings, comments, regexes) blanked. */
13114
+ /**
13115
+ * The text with everything but code (strings, comments, regexes) blanked, and
13116
+ * where its regex literals are.
13117
+ */
12478
13118
  function codeOnly(source) {
12479
13119
  const chars = Array.from({ length: source.length }, () => " ");
12480
- lexJs(source, { code(ch, index) {
13120
+ const regexes = regexLiterals(source, "statements", { code(ch, index) {
12481
13121
  for (let k = 0; k < ch.length; k++) chars[index + k] = ch[k];
12482
- } }, "statements");
12483
- return chars.join("");
13122
+ } });
13123
+ return {
13124
+ code: chars.join(""),
13125
+ regexes
13126
+ };
12484
13127
  }
12485
13128
  var stringOf = (d) => d?.type === "string" ? d : void 0;
12486
13129
  var booleanOf = (d) => d?.type === "boolean" ? d.value : void 0;
@@ -12554,29 +13197,37 @@ function macroOf(config) {
12554
13197
  * `source` (JavaScript: a script passage, the body of a `{do}`, a project
12555
13198
  * file) declare, in source order, read from the text without running it. A
12556
13199
  * call whose config is an object literal (or a variable declared as one with
12557
- * `const`, `let` or `var`) and whose `name` is a string is found, wherever it
12558
- * is, even inside a function. Only what is written out is read: a `block`,
13200
+ * `const`, `let` or `var` that the call sees, see Bindings: not a parameter, a
13201
+ * pattern or an assignment of the name, or a write to a property the macro
13202
+ * is read from) and whose `name` is a string is found,
13203
+ * wherever it is, even inside a function. Only what is written out is read: a `block`,
12559
13204
  * `interpolate`, `storeVar` or `merged` that is a boolean literal, the
12560
13205
  * strings of `subMacros`, and `parameters` when every one is an object
12561
13206
  * literal with a string `name` and `type` (and `holds`, `required`,
12562
13207
  * `description` and nested `parameters` of options when written out as such);
12563
- * a list with a parameter that is not, or that `defineMacro` would refuse,
12564
- * declares none. It is tolerant: text it cannot read is skipped, and it
13208
+ * a later member that sets one of these again (a spread, a method, an
13209
+ * accessor, a computed key) replaces it; a list with a parameter that is not,
13210
+ * or that `defineMacro` would refuse, declares none. It is tolerant: text it cannot read is skipped, and it
12565
13211
  * throws for none.
12566
13212
  */
12567
13213
  function discoverMacros(source) {
12568
- const code = codeOnly(source);
13214
+ const { code, regexes } = codeOnly(source);
12569
13215
  const found = [];
13216
+ let bindings;
12570
13217
  for (const call of code.matchAll(CALL_RE)) {
12571
13218
  let at = call.index + call[0].length;
12572
13219
  if (code.charAt(at) !== "{") {
12573
13220
  const variable = IDENTIFIER_ARGUMENT_RE.exec(code.slice(at))?.[1];
12574
13221
  if (!variable) continue;
12575
- const declaration = new RegExp(`(?<![\\w$.])(?:const|let|var)\\s+${variable.replace(/\$/g, "\\$")}\\s*=\\s*(?=\\{)`).exec(code);
12576
- if (!declaration) continue;
12577
- at = declaration.index + declaration[0].length;
13222
+ bindings ?? (bindings = new Bindings(code));
13223
+ const object = bindings.objectOf(variable, call.index, CONFIG_KEYS);
13224
+ if (object === void 0) continue;
13225
+ at = object;
12578
13226
  }
12579
- const reader = new ConfigReader(source);
13227
+ const reader = new ConfigReader(source, {
13228
+ goal: "statements",
13229
+ regexes
13230
+ });
12580
13231
  reader.i = at;
12581
13232
  const config = reader.datum();
12582
13233
  const macro = config && macroOf(config);
@@ -12619,17 +13270,29 @@ function splitIncludeFlag(rawArgs) {
12619
13270
  * (see src/tooling.ts).
12620
13271
  */
12621
13272
  var TRANSFORM_CACHE_MAX = 500;
12622
- var NAMESPACES = {
12623
- $: "variables",
12624
- _: "temporary",
12625
- "@": "locals",
12626
- "%": "transient"
13273
+ /**
13274
+ * The identifiers generated code reads the namespaces through, and the
13275
+ * compiled function takes them under (see src/expression.ts). Authored
13276
+ * JavaScript may declare identifiers of its own (`const variables = {}` in
13277
+ * a helper), so these are ones it cannot: an identifier that starts with
13278
+ * `_` or `$` and has more word characters after it is a sigil reference,
13279
+ * and the lexer refuses to declare one (`__variables` is the temporary
13280
+ * variable `_variables`, rewritten like any other). No declaration or
13281
+ * parameter of the author's can then capture a reference or clash with the
13282
+ * generated bindings.
13283
+ */
13284
+ var BINDINGS = {
13285
+ $: "__variables",
13286
+ _: "__temporary",
13287
+ "@": "__locals",
13288
+ "%": "__transient"
12627
13289
  };
12628
13290
  /** Ends with an identifier character. */
12629
13291
  var IDENT_END_RE = /[\p{ID_Continue}$\u200c\u200d]$/u;
12630
13292
  /**
12631
13293
  * Transform expression: $var → variables["var"], _var → temporary["var"],
12632
- * @var → locals["var"], %var → transient["var"].
13294
+ * @var → locals["var"], %var → transient["var"], where `variables` and the
13295
+ * others stand for the generated names in BINDINGS.
12633
13296
  * The lexer (`lexJs`) finds the references: only in code (string, template
12634
13297
  * and regex literal text and comments are left untouched), only where an
12635
13298
  * identifier starts (not in `a$b`, nor as the property name in `obj._x`),
@@ -12652,7 +13315,7 @@ function transform(expr, goal = "expression") {
12652
13315
  result += expr.slice(at, ref.start);
12653
13316
  if (ref.shorthand) result += `${ref.name}: `;
12654
13317
  else if (IDENT_END_RE.test(result.slice(-2))) result += " ";
12655
- result += `${NAMESPACES[ref.sigil]}["${ref.name}"]`;
13318
+ result += `${BINDINGS[ref.sigil]}["${ref.name}"]`;
12656
13319
  at = ref.end;
12657
13320
  }
12658
13321
  result += expr.slice(at);
@@ -12681,11 +13344,8 @@ function validateStoryMarkup(passages, macros, options = {}) {
12681
13344
  const all = [...macros];
12682
13345
  const known = /* @__PURE__ */ new Set();
12683
13346
  const widgets = widgetDefinitions$1(list, parameterLookup(all));
12684
- const blocks = new Set(widgets.filter((def) => def.block && def.closeStart !== void 0).map((def) => def.name.toLowerCase()));
12685
- const parametersOf = parameterLookup([...all, ...widgets.map((widget) => ({
12686
- name: widget.name,
12687
- widget
12688
- }))]);
13347
+ const blocks = new Set(effectiveWidgetDefinitions(widgets).filter((def) => def.block).map((def) => def.name.toLowerCase()));
13348
+ const parametersOf = parameterLookup([...all, ...definedWidgetMacros(widgets)]);
12689
13349
  for (const macro of all) {
12690
13350
  const name = macro.name.toLowerCase();
12691
13351
  known.add(name);
@@ -12701,6 +13361,13 @@ function validateStoryMarkup(passages, macros, options = {}) {
12701
13361
  tolerant: options.tolerant
12702
13362
  });
12703
13363
  }
13364
+ /** The widgets as macros that declare what their parameters hold. */
13365
+ function definedWidgetMacros(widgets) {
13366
+ return widgets.map((widget) => ({
13367
+ name: widget.name,
13368
+ widget
13369
+ }));
13370
+ }
12704
13371
  /** Whether a macro takes a body, among `macros` and the built-in ones. */
12705
13372
  function blockLookup(macros) {
12706
13373
  const blocks = new Set(macros.filter((m) => m.block).map((m) => m.name.toLowerCase()));
@@ -12744,13 +13411,18 @@ function widgetDefinitions(passages, macros = []) {
12744
13411
  }
12745
13412
  /** Passages tagged so hold code or styles, not markup. */
12746
13413
  var NOT_MARKUP_TAGS = ["script", "stylesheet"];
12747
- /** What reading the variable references of markup depends on. */
12748
- function referenceOptions(macros, all = false) {
13414
+ /**
13415
+ * What reading the variable references of markup depends on: the `macros`,
13416
+ * and the widgets of the `passages` that are given (the calls of those that
13417
+ * declare what their parameters hold are read by them).
13418
+ */
13419
+ function referenceOptions(macros, all = false, passages = []) {
12749
13420
  const list = [...macros];
13421
+ const widgets = widgetDefinitions$1(passages, parameterLookup(list));
12750
13422
  return {
12751
13423
  all,
12752
13424
  storeVarMacros: new Set(list.filter((m) => m.storeVar).map((m) => m.name.toLowerCase())),
12753
- parametersOf: parameterLookup(list),
13425
+ parametersOf: parameterLookup([...list, ...definedWidgetMacros(widgets)]),
12754
13426
  tolerant: true
12755
13427
  };
12756
13428
  }
@@ -12781,7 +13453,8 @@ function variableReferences(source, macros = [], options = {}) {
12781
13453
  * tolerant of half-typed markup, and it evaluates no project code.
12782
13454
  */
12783
13455
  function validateVariableReferences(passages, declarations, macros = []) {
12784
- return checkVariableReferences([...passages].filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros));
13456
+ const list = [...passages];
13457
+ return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
12785
13458
  }
12786
13459
  //#endregion
12787
13460
  export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, discoverMacros, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, isBlockMacro, isSigil, lexJs, lexTemplate, pairMarkup, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };