@rohal12/spindle 0.59.26 → 0.59.27

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.
@@ -8820,6 +8820,9 @@ Parser.acorn = {
8820
8820
  lineBreakG,
8821
8821
  nonASCIIwhitespace
8822
8822
  };
8823
+ function parse(input, options) {
8824
+ return Parser.parse(input, options);
8825
+ }
8823
8826
  //#endregion
8824
8827
  //#region src/js-lexer.ts
8825
8828
  /**
@@ -9296,7 +9299,7 @@ function walk(node, src, out, binding, shorthand) {
9296
9299
  }
9297
9300
  }
9298
9301
  /** The rest of a word, after a number (`2s`). */
9299
- var WORD_RE$1 = /[\p{ID_Continue}$.]*/uy;
9302
+ var WORD_RE$2 = /[\p{ID_Continue}$.]*/uy;
9300
9303
  /** The flags after a regex literal, whatever they are. */
9301
9304
  var FLAGS_RE = /[\p{ID_Continue}$]*/uy;
9302
9305
  /** Words a string may follow with no space between (`of'x'`, `get"y"`). */
@@ -9456,9 +9459,9 @@ function* tokens(src, start, goal, options = {}) {
9456
9459
  continue;
9457
9460
  }
9458
9461
  } else if (!unterminated && p.start <= pos && /[\d.]/.test(first) && /\d/.test(src.slice(p.start, p.start + 2))) {
9459
- WORD_RE$1.lastIndex = p.start;
9460
- WORD_RE$1.test(src);
9461
- yield operand(types$1.num, p.start, WORD_RE$1.lastIndex);
9462
+ WORD_RE$2.lastIndex = p.start;
9463
+ WORD_RE$2.test(src);
9464
+ yield operand(types$1.num, p.start, WORD_RE$2.lastIndex);
9462
9465
  continue;
9463
9466
  }
9464
9467
  yield {
@@ -10285,7 +10288,7 @@ function unset(param) {
10285
10288
  if (param.type === "flag" || param.type === "separator") return false;
10286
10289
  return param.type === "options" ? {} : void 0;
10287
10290
  }
10288
- var WORD_RE = /\w+/y;
10291
+ var WORD_RE$1 = /\w+/y;
10289
10292
  var NUMBER_RE$1 = /[-+]?(?:\d+\.?\d*|\.\d+)/y;
10290
10293
  var WORD_OR_PUNCT_RE = /\S+/y;
10291
10294
  /** Match the sticky regex `re` at `pos`, returning the matched text. */
@@ -10305,7 +10308,7 @@ function readOptions(params, src, { at, spans }) {
10305
10308
  const options = {};
10306
10309
  let i = 0;
10307
10310
  while (i < src.length) {
10308
- const key = matchAt(WORD_RE, src, i);
10311
+ const key = matchAt(WORD_RE$1, src, i);
10309
10312
  if (!key) {
10310
10313
  i = readQuoted(src, i)?.end ?? i + 1;
10311
10314
  continue;
@@ -11048,9 +11051,11 @@ function textContainsChildren(text, parametersOf) {
11048
11051
  * Whether a tag renders a `{@children}` in an attribute value or a macro
11049
11052
  * argument that holds markup (`<span title="{@children}">`,
11050
11053
  * `{button "{@children}"}`). Literal arguments and code are not markup.
11054
+ * `src` is the text a flat token's offsets index into (its attribute values
11055
+ * are read from it); a token made from an AST has none.
11051
11056
  */
11052
- function tokenTextContainsChildren(token, parametersOf = registeredParameters) {
11053
- for (const piece of codeAndText("", [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf)) return true;
11057
+ function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "") {
11058
+ for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf)) return true;
11054
11059
  return false;
11055
11060
  }
11056
11061
  /**
@@ -11110,13 +11115,14 @@ var WIDGET_PARAMETERS = [{
11110
11115
  }];
11111
11116
  /**
11112
11117
  * The widget a {widget} definition's arguments declare: its name and its
11113
- * parameters, the words after it that start with `@` (docs/widgets.md).
11114
- * Other words, such as `$name`, are not parameters.
11118
+ * parameters, the words after it that start with `@` (docs/widgets.md),
11119
+ * separated by spaces or commas (`@a, @b`). Other words, such as `$name`, are
11120
+ * not parameters.
11115
11121
  */
11116
11122
  function widgetDef({ name = "", parameters = "" }) {
11117
11123
  return {
11118
11124
  name,
11119
- params: parameters.split(/\s+/).filter((word) => word.startsWith("@"))
11125
+ params: parameters.split(/[\s,]+/).filter((word) => word.startsWith("@"))
11120
11126
  };
11121
11127
  }
11122
11128
  /** Read the arguments of a {widget} definition (see widgetDef). */
@@ -11160,7 +11166,7 @@ function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
11160
11166
  closeStart: token.start
11161
11167
  });
11162
11168
  }
11163
- } else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf))) open[open.length - 1].isBlock = true;
11169
+ } else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf, passage.content))) open[open.length - 1].isBlock = true;
11164
11170
  done.push(...open);
11165
11171
  const defs = [];
11166
11172
  for (const { token, isBlock, closeStart } of done) try {
@@ -11291,19 +11297,30 @@ function validateMarkup(passages, options) {
11291
11297
  const parsed = [];
11292
11298
  const widgets = /* @__PURE__ */ new Set();
11293
11299
  const passageNames = /* @__PURE__ */ new Set();
11300
+ const addWidgets = (tokens) => {
11301
+ for (const token of tokens) {
11302
+ if (token.type !== "macro" || token.isClose) continue;
11303
+ if (token.name.toLowerCase() !== "widget") continue;
11304
+ const name = widgetName(token.rawArgs);
11305
+ if (name) widgets.add(name);
11306
+ }
11307
+ };
11294
11308
  for (const passage of passages) {
11295
11309
  passageNames.add(passage.name);
11296
11310
  if (NOT_MARKUP.has(passage.name)) continue;
11297
11311
  if (passage.tags?.some((tag) => NOT_MARKUP_TAGS$1.includes(tag))) continue;
11298
11312
  const reported = !options.only || options.only(passage);
11313
+ if (options.tolerant) {
11314
+ const { tokens, errors } = analyzeMarkup(passage.content, { hooks });
11315
+ addWidgets(tokens);
11316
+ if (!reported) continue;
11317
+ for (const err of errors) reportError(passage, err, "");
11318
+ parsed.push([passage, tokens]);
11319
+ continue;
11320
+ }
11299
11321
  try {
11300
11322
  const tokens = tokenizeMarkup(passage.content);
11301
- for (const token of tokens) {
11302
- if (token.type !== "macro" || token.isClose) continue;
11303
- if (token.name.toLowerCase() !== "widget") continue;
11304
- const name = widgetName(token.rawArgs);
11305
- if (name) widgets.add(name);
11306
- }
11323
+ addWidgets(tokens);
11307
11324
  if (!reported) continue;
11308
11325
  parseMarkup(passage.content, { hooks });
11309
11326
  parsed.push([passage, tokens]);
@@ -11422,7 +11439,13 @@ Object.freeze(createNamespace());
11422
11439
  */
11423
11440
  var NUMBER_RE = /(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d+)?)(n?)/y;
11424
11441
  var IDENT_RE = /[A-Za-z_$][\w$]*/y;
11442
+ var KEY_RE = /[\w$]+/y;
11425
11443
  var ARROW_RE = /(?:async\s+)?(?:\((?:[^()]|\([^()]*\))*\)|[A-Za-z_$][\w$]*)\s*=>/y;
11444
+ var ARRAY_INDEX_RE = /^(?:0|[1-9]\d{0,8})$/;
11445
+ var UNSUPPORTED_UNDEFINED = {
11446
+ unsupported: "undefined",
11447
+ value: "undefined"
11448
+ };
11426
11449
  /** Read `src`, one literal and nothing else. */
11427
11450
  function staticLiteral(src) {
11428
11451
  const reader = new Reader(src);
@@ -11430,6 +11453,27 @@ function staticLiteral(src) {
11430
11453
  reader.space();
11431
11454
  return reader.i === src.length ? value : void 0;
11432
11455
  }
11456
+ /**
11457
+ * The keys of an object in the order `Object.entries` lists them (array
11458
+ * indices first, ascending, then the others as they were added): the order
11459
+ * the runtime meets the members in.
11460
+ */
11461
+ function entryOrder(keys) {
11462
+ const all = [...keys];
11463
+ return [...all.filter((key) => ARRAY_INDEX_RE.test(key)).sort((a, b) => Number(a) - Number(b)), ...all.filter((key) => !ARRAY_INDEX_RE.test(key))];
11464
+ }
11465
+ /** `String(value)` of a BigInt literal's digits, or `undefined` if they are no BigInt. */
11466
+ function bigintValue(digits) {
11467
+ try {
11468
+ return BigInt(digits.replace(/_/g, "")).toString();
11469
+ } catch {
11470
+ return;
11471
+ }
11472
+ }
11473
+ /**
11474
+ * The cursor over a JavaScript text that the literal reader moves: the
11475
+ * helpers that skip what is not read are shared (see macro-discovery.ts).
11476
+ */
11433
11477
  var Reader = class {
11434
11478
  constructor(src) {
11435
11479
  this.src = src;
@@ -11471,6 +11515,15 @@ var Reader = class {
11471
11515
  closed
11472
11516
  };
11473
11517
  }
11518
+ /**
11519
+ * Skip the string literal at the cursor and read its value, or `undefined`
11520
+ * if it is not closed or not well-formed.
11521
+ */
11522
+ stringValue() {
11523
+ const at = this.i;
11524
+ const { closed } = this.string();
11525
+ return closed ? stringLiteralValue(this.src.slice(at, this.i)) ?? void 0 : void 0;
11526
+ }
11474
11527
  /** A template literal: a string, but for `${}`. */
11475
11528
  template() {
11476
11529
  const { src } = this;
@@ -11487,7 +11540,8 @@ var Reader = class {
11487
11540
  number() {
11488
11541
  const { src } = this;
11489
11542
  let i = this.i;
11490
- if (src.charAt(i) === "+" || src.charAt(i) === "-") {
11543
+ const sign = src.charAt(i);
11544
+ if (sign === "+" || sign === "-") {
11491
11545
  i++;
11492
11546
  while (/\s/.test(src.charAt(i))) i++;
11493
11547
  }
@@ -11495,7 +11549,13 @@ var Reader = class {
11495
11549
  const match = NUMBER_RE.exec(src);
11496
11550
  if (match) {
11497
11551
  this.i = NUMBER_RE.lastIndex;
11498
- return match[1] ? { unsupported: "bigint" } : { shape: { type: "number" } };
11552
+ if (!match[1]) return { shape: { type: "number" } };
11553
+ if (sign === "+") return { throws: "Cannot convert a BigInt value to a number" };
11554
+ const digits = bigintValue(match[0].slice(0, -1));
11555
+ return digits === void 0 ? void 0 : {
11556
+ unsupported: "bigint",
11557
+ value: sign === "-" && digits !== "0" ? `-${digits}` : digits
11558
+ };
11499
11559
  }
11500
11560
  IDENT_RE.lastIndex = i;
11501
11561
  if (IDENT_RE.exec(src)?.[0] === "Infinity") {
@@ -11506,8 +11566,9 @@ var Reader = class {
11506
11566
  /** A keyword, a function, or a name (which is not static). */
11507
11567
  word() {
11508
11568
  const { src } = this;
11509
- ARROW_RE.lastIndex = this.i;
11510
- if (ARROW_RE.test(src)) return this.function();
11569
+ const start = this.i;
11570
+ const arrow = this.arrow();
11571
+ if (arrow !== void 0) return arrow ? this.functionFrom(start) : void 0;
11511
11572
  IDENT_RE.lastIndex = this.i;
11512
11573
  const word = IDENT_RE.exec(src)?.[0];
11513
11574
  if (word === void 0) return void 0;
@@ -11525,72 +11586,152 @@ var Reader = class {
11525
11586
  return { shape: { type: "number" } };
11526
11587
  case "undefined":
11527
11588
  this.i = end;
11528
- return { unsupported: "undefined" };
11589
+ return UNSUPPORTED_UNDEFINED;
11590
+ case "void": {
11591
+ this.i = end;
11592
+ const operand = this.value();
11593
+ return operand && !("throws" in operand) ? UNSUPPORTED_UNDEFINED : operand;
11594
+ }
11529
11595
  case "function":
11530
11596
  case "class":
11531
- case "async": return this.function();
11597
+ case "async": return this.skipDeclaration(word) ? this.functionFrom(start) : void 0;
11532
11598
  }
11533
11599
  }
11534
- /** A function (or class): the rest is its body, which is not read. */
11535
- function() {
11536
- return this.unsupported({ unsupported: "function" });
11600
+ /** The function (or class) that was skipped since `start`. */
11601
+ functionFrom(start) {
11602
+ return {
11603
+ unsupported: "function",
11604
+ value: this.src.slice(start, this.i).trimEnd()
11605
+ };
11537
11606
  }
11538
- /** `value`, which makes the whole literal unsupported: the rest is not read. */
11539
- unsupported(value) {
11540
- this.i = this.src.length;
11541
- return value;
11607
+ /**
11608
+ * Skip the parameters of an arrow function and its body, which ends at a
11609
+ * `,` or `}` outside brackets, or at the end of the text. `undefined` if the
11610
+ * text at the cursor is no arrow function, false if it cannot be skipped.
11611
+ */
11612
+ arrow() {
11613
+ const { src } = this;
11614
+ ARROW_RE.lastIndex = this.i;
11615
+ if (!ARROW_RE.test(src)) return void 0;
11616
+ this.i = ARROW_RE.lastIndex;
11617
+ this.space();
11618
+ if (src.charAt(this.i) === "{") return this.skipBalanced();
11619
+ while (this.i < src.length && !",}".includes(src.charAt(this.i))) if (!this.skipOne()) break;
11620
+ return true;
11621
+ }
11622
+ /**
11623
+ * Skip a `function`, `async function` or `class` (its keyword `word` is at
11624
+ * the cursor), up to the end of its body.
11625
+ */
11626
+ skipDeclaration(word) {
11627
+ const { src } = this;
11628
+ this.i += word.length;
11629
+ this.space();
11630
+ if (word === "async") {
11631
+ IDENT_RE.lastIndex = this.i;
11632
+ if (IDENT_RE.exec(src)?.[0] !== "function") return false;
11633
+ return this.skipDeclaration("function");
11634
+ }
11635
+ if (word === "function") {
11636
+ if (src.charAt(this.i) === "*") this.i++;
11637
+ this.space();
11638
+ IDENT_RE.lastIndex = this.i;
11639
+ if (IDENT_RE.test(src)) this.i = IDENT_RE.lastIndex;
11640
+ this.space();
11641
+ if (src.charAt(this.i) !== "(" || !this.skipBalanced()) return false;
11642
+ this.space();
11643
+ } else while (this.i < src.length && src.charAt(this.i) !== "{") if (!this.skipOne()) return false;
11644
+ return src.charAt(this.i) === "{" && this.skipBalanced();
11542
11645
  }
11543
11646
  /** An object literal: the members that are static. */
11544
11647
  object() {
11545
11648
  const { src } = this;
11546
- const fields = /* @__PURE__ */ new Map();
11649
+ const members = /* @__PURE__ */ new Map();
11650
+ let thrown;
11547
11651
  this.i++;
11548
11652
  for (;;) {
11549
11653
  this.space();
11550
11654
  const c = src.charAt(this.i);
11551
11655
  if (c === "}") {
11552
11656
  this.i++;
11553
- return { shape: {
11554
- type: "object",
11555
- fields
11556
- } };
11657
+ return thrown === void 0 ? this.objectOf(members) : { throws: thrown };
11557
11658
  }
11558
11659
  if (c === ",") {
11559
11660
  this.i++;
11560
11661
  continue;
11561
11662
  }
11562
11663
  if (this.i >= src.length) return void 0;
11664
+ const start = this.i;
11563
11665
  const key = this.key();
11666
+ if (key === "__proto__") return void 0;
11564
11667
  this.space();
11565
- if (key !== void 0 && src.charAt(this.i) === ":") {
11668
+ const next = src.charAt(this.i);
11669
+ if (key !== void 0 && next === ":") {
11566
11670
  this.i++;
11567
11671
  const at = this.i;
11568
11672
  const value = this.value();
11569
11673
  this.space();
11570
- if (value && "unsupported" in value) return this.unsupported(value);
11571
- if (value && ",}".includes(src.charAt(this.i))) {
11572
- fields.set(key, value.shape);
11674
+ if (value && this.atMemberEnd()) {
11675
+ if ("throws" in value) thrown ?? (thrown = value.throws);
11676
+ else members.set(key, "shape" in value ? value.shape : value);
11573
11677
  continue;
11574
11678
  }
11679
+ members.set(key, null);
11575
11680
  this.i = at;
11576
- } else if (key !== void 0 && src.charAt(this.i) === "(") return this.unsupported({ unsupported: "function" });
11681
+ } else if (key !== void 0 && next === "(") {
11682
+ if (!this.skipBalanced()) return void 0;
11683
+ this.space();
11684
+ if (src.charAt(this.i) === "{" && this.skipBalanced()) {
11685
+ members.set(key, {
11686
+ unsupported: "function",
11687
+ value: src.slice(start, this.i)
11688
+ });
11689
+ continue;
11690
+ }
11691
+ return;
11692
+ } else if (key !== void 0 && (next === "," || next === "}")) {
11693
+ members.set(key, null);
11694
+ continue;
11695
+ } else members.clear();
11577
11696
  if (!this.skipMember()) return void 0;
11578
11697
  }
11579
11698
  }
11699
+ /** Whether a member ends at the cursor. */
11700
+ atMemberEnd() {
11701
+ return this.i < this.src.length && ",}".includes(this.src.charAt(this.i));
11702
+ }
11703
+ /**
11704
+ * The object literal with these members: a value no variable can hold
11705
+ * anywhere in it (the first the runtime meets) is what it reads as.
11706
+ */
11707
+ objectOf(members) {
11708
+ const fields = /* @__PURE__ */ new Map();
11709
+ for (const key of entryOrder(members.keys())) {
11710
+ const member = members.get(key);
11711
+ if (!member) continue;
11712
+ if ("unsupported" in member) return member;
11713
+ fields.set(key, member);
11714
+ }
11715
+ return { shape: {
11716
+ type: "object",
11717
+ fields
11718
+ } };
11719
+ }
11580
11720
  /** The key of a member (a name, a string or a number), if it has one. */
11581
11721
  key() {
11582
11722
  const { src } = this;
11583
11723
  const c = src.charAt(this.i);
11584
- if (c === "\"" || c === "'") {
11585
- const { body, closed } = this.string();
11586
- return closed ? body : void 0;
11587
- }
11588
- const word = /[\w$]+/y;
11589
- word.lastIndex = this.i;
11590
- const found = word.exec(src)?.[0];
11724
+ if (c === "\"" || c === "'") return this.stringValue();
11725
+ KEY_RE.lastIndex = this.i;
11726
+ const found = KEY_RE.exec(src)?.[0];
11591
11727
  if (found === void 0) return void 0;
11592
- this.i = word.lastIndex;
11593
- return found;
11728
+ this.i = KEY_RE.lastIndex;
11729
+ if (!/^\d/.test(found)) return found;
11730
+ const digits = found.replace(/_/g, "");
11731
+ if (/^0\d/.test(digits)) return void 0;
11732
+ if (digits.endsWith("n") && !/^0[xX]/.test(digits)) return bigintValue(digits.slice(0, -1));
11733
+ const value = Number(digits);
11734
+ return Number.isNaN(value) ? void 0 : String(value);
11594
11735
  }
11595
11736
  /** Skip to the `,` or `}` that ends a member, balancing what is inside. */
11596
11737
  skipMember() {
@@ -11724,6 +11865,27 @@ function shapeSchema(shape) {
11724
11865
  };
11725
11866
  }
11726
11867
  /**
11868
+ * What is wrong with the syntax of an initializer, as it is evaluated
11869
+ * (`return (expr)` in a function body), or `undefined`. `pos` is where, as an
11870
+ * index into `expr` (it may be past its end, for an unexpected end).
11871
+ */
11872
+ function initializerSyntaxError(expr) {
11873
+ const prefix = "return (";
11874
+ try {
11875
+ parse(prefix + expr + ")", {
11876
+ ecmaVersion: "latest",
11877
+ allowReturnOutsideFunction: true
11878
+ });
11879
+ } catch (err) {
11880
+ if (!(err instanceof SyntaxError)) throw err;
11881
+ const { pos } = err;
11882
+ return {
11883
+ message: err.message.replace(/ \(\d+:\d+\)$/, ""),
11884
+ pos: Math.max(0, pos - 8)
11885
+ };
11886
+ }
11887
+ }
11888
+ /**
11727
11889
  * Read the declarations of a StoryVariables (`$name = value`) or
11728
11890
  * StoryTransients (`%name = value`) passage, without evaluating them and
11729
11891
  * without throwing: every valid declaration, and every invalid line as an
@@ -11731,9 +11893,10 @@ function shapeSchema(shape) {
11731
11893
  *
11732
11894
  * A declaration is a line of the form `$name = expression`; blank lines are
11733
11895
  * skipped. A line that is not, and a name that cannot be a variable, are
11734
- * errors. So is an initializer that no variable can hold (a function,
11735
- * `undefined`), when it is a literal; whether any other initializer can only
11736
- * be known by running it. A name declared again is an error too, but both
11896
+ * errors. So is an initializer with a syntax error, and one that no variable
11897
+ * can hold (a function, `undefined`) when it is a literal, or one that throws
11898
+ * when it is a literal (`+1n`); whether any other initializer can only be
11899
+ * known by running it. A name declared again is an error too, but both
11737
11900
  * declarations are returned (the later wins when evaluated).
11738
11901
  */
11739
11902
  function parseDeclarations(content, sigil = "$") {
@@ -11776,10 +11939,19 @@ function parseDeclarations(content, sigil = "$") {
11776
11939
  };
11777
11940
  if (seen.has(name)) error("duplicate-declaration", nameStart, nameEnd, `Duplicate declaration of ${sigil}${name}`);
11778
11941
  seen.add(name);
11779
- const literal = staticLiteral(expr);
11780
- if (literal && "shape" in literal) declaration.schema = shapeSchema(literal.shape);
11781
- else if (literal) error("unsupported-value", declaration.valueStart, valueEnd, `Unsupported type "${literal.unsupported}" for value ${expr}. ${UNSUPPORTED_TYPE}`);
11782
11942
  declarations.push(declaration);
11943
+ const failed = `Failed to evaluate "${sigil}${name} = ${expr}"`;
11944
+ const syntax = initializerSyntaxError(expr);
11945
+ if (syntax) {
11946
+ const at = Math.min(syntax.pos, expr.length - 1);
11947
+ error("syntax", declaration.valueStart + at, declaration.valueStart + at + 1, `${failed}: ${syntax.message}`);
11948
+ continue;
11949
+ }
11950
+ const literal = staticLiteral(expr);
11951
+ if (!literal) continue;
11952
+ if ("shape" in literal) declaration.schema = shapeSchema(literal.shape);
11953
+ else if ("throws" in literal) error("unsupported-value", declaration.valueStart, valueEnd, `${failed}: ${literal.throws}`);
11954
+ else error("unsupported-value", declaration.valueStart, valueEnd, `Unsupported type "${literal.unsupported}" for value ${literal.value}. ${UNSUPPORTED_TYPE}`);
11783
11955
  }
11784
11956
  return {
11785
11957
  declarations,
@@ -11943,6 +12115,7 @@ function scanCodeLeniently(code, at, emit, goal) {
11943
12115
  function scanArgs(token, params, at, emit, options) {
11944
12116
  if (!token.rawArgs) return;
11945
12117
  if (params) {
12118
+ if (options.all && !options.storeVarMacros.has(token.name.toLowerCase())) scanVariableParameters(token, params, at, emit);
11946
12119
  const pieces = [...argPieces(token.rawArgs, token.argsStart, params, token.name, "")];
11947
12120
  if (!pieces.some((piece) => piece.kind === "argument-error")) {
11948
12121
  for (const piece of pieces) {
@@ -11958,11 +12131,41 @@ function scanArgs(token, params, at, emit, options) {
11958
12131
  }
11959
12132
  scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
11960
12133
  }
12134
+ /**
12135
+ * Report the variables the `variable` parameters of a macro name
12136
+ * (`{unset $x}`, `{computed $x = …}`), when they are `$` or `%` variables.
12137
+ * Arguments that do not parse hold none.
12138
+ */
12139
+ function scanVariableParameters(token, params, at, emit) {
12140
+ const spans = /* @__PURE__ */ new Map();
12141
+ try {
12142
+ parseMacroArgs(token.rawArgs, params, spans);
12143
+ } catch (err) {
12144
+ if (err instanceof MacroArgumentError) return;
12145
+ throw err;
12146
+ }
12147
+ for (const param of params) {
12148
+ const span = spans.get(param);
12149
+ if (param.type !== "variable" || !span) continue;
12150
+ const ref = referenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
12151
+ if (ref) emit(ref);
12152
+ }
12153
+ }
12154
+ /** Report the references in the selectors of a token, which are interpolated. */
12155
+ function scanSelectors(content, token, at, emit, options) {
12156
+ if (!("selectorsStart" in token) || token.selectorsStart === void 0 || token.selectorsEnd === void 0) return;
12157
+ const from = token.selectorsStart;
12158
+ scanInterpolations(content.slice(from, token.selectorsEnd), (i) => at(from + i), emit, {
12159
+ ...options,
12160
+ storeVarMacros: NO_STORE_VAR_MACROS
12161
+ });
12162
+ }
11961
12163
  /** Report the `$var` references in the tokens of `content`. */
11962
12164
  function collectTokenRefs(content, tokens, at, emit, options) {
11963
12165
  const { storeVarMacros, parametersOf } = options;
11964
12166
  for (let t = 0; t < tokens.length; t++) {
11965
12167
  const token = tokens[t];
12168
+ if (options.all && token.type !== "macro" && token.type !== "html" && token.type !== "text") scanSelectors(content, token, at, emit, options);
11966
12169
  if (token.type === "variable") {
11967
12170
  if ((token.scope === "variable" || token.scope === "transient") && token.name) {
11968
12171
  const [name, ...path] = token.name.split(".");
@@ -11986,13 +12189,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
11986
12189
  }
11987
12190
  else if (token.type === "macro" && !token.isClose) {
11988
12191
  scanArgs(token, parametersOf(token.name), at, emit, options);
11989
- if (token.selectorsStart !== void 0 && token.selectorsEnd !== void 0) {
11990
- const from = token.selectorsStart;
11991
- scanInterpolations(content.slice(from, token.selectorsEnd), (i) => at(from + i), emit, {
11992
- ...options,
11993
- storeVarMacros: NO_STORE_VAR_MACROS
11994
- });
11995
- }
12192
+ scanSelectors(content, token, at, emit, options);
11996
12193
  if (storeVarMacros.has(token.name.toLowerCase())) {
11997
12194
  const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
11998
12195
  const first = token.rawArgs.trim().split(/\s+/)[0] ?? "";
@@ -12062,6 +12259,243 @@ function checkVariableReferences(passages, declared, options) {
12062
12259
  return diagnostics;
12063
12260
  }
12064
12261
  //#endregion
12262
+ //#region src/macro-discovery.ts
12263
+ /**
12264
+ * What `defineMacro({ … })` calls in JavaScript declare, read from the text
12265
+ * without running it (see discoverMacros): the literal parts of the config
12266
+ * object, and nothing else.
12267
+ */
12268
+ /** The text of an object config, or the name of the variable that holds it. */
12269
+ var CALL_RE = /(?<![\w$])defineMacro\s*\(\s*/g;
12270
+ var IDENTIFIER_ARGUMENT_RE = /^([A-Za-z_$][\w$]*)\s*[,)]/;
12271
+ var WORD_RE = /[A-Za-z_]+/y;
12272
+ /** The literals of a config object, read to the end of what is static. */
12273
+ var ConfigReader = class extends Reader {
12274
+ constructor(..._args) {
12275
+ super(..._args);
12276
+ this.failed = false;
12277
+ }
12278
+ /** The static value of a member or element, whatever follows is skipped. */
12279
+ member() {
12280
+ const at = this.i;
12281
+ const datum = this.datum();
12282
+ this.space();
12283
+ if (datum && this.atElementEnd()) return datum;
12284
+ this.i = at;
12285
+ while (this.i < this.src.length && !this.atElementEnd()) if (!this.skipOne()) {
12286
+ this.fail();
12287
+ break;
12288
+ }
12289
+ }
12290
+ atElementEnd() {
12291
+ return this.i >= this.src.length || ",]}".includes(this.src.charAt(this.i));
12292
+ }
12293
+ /** The literal at the cursor, if it is a string, boolean, array or object. */
12294
+ datum() {
12295
+ const { src } = this;
12296
+ this.space();
12297
+ const c = src.charAt(this.i);
12298
+ if (c === "\"" || c === "'") {
12299
+ const start = this.i;
12300
+ const value = this.stringValue();
12301
+ return value === void 0 ? void 0 : {
12302
+ type: "string",
12303
+ value,
12304
+ start: start + 1,
12305
+ end: this.i - 1
12306
+ };
12307
+ }
12308
+ if (c === "`") return this.plainTemplate();
12309
+ if (c === "[") return this.array();
12310
+ if (c === "{") return this.record();
12311
+ WORD_RE.lastIndex = this.i;
12312
+ const word = WORD_RE.exec(src)?.[0];
12313
+ if (word === "true" || word === "false") {
12314
+ this.i = WORD_RE.lastIndex;
12315
+ return {
12316
+ type: "boolean",
12317
+ value: word === "true"
12318
+ };
12319
+ }
12320
+ }
12321
+ /** A template literal that has no `${}` and no escapes, as a string. */
12322
+ plainTemplate() {
12323
+ const { src } = this;
12324
+ const start = this.i;
12325
+ for (let i = start + 1; i < src.length; i++) {
12326
+ const c = src.charAt(i);
12327
+ if (c === "`") {
12328
+ this.i = i + 1;
12329
+ return {
12330
+ type: "string",
12331
+ value: src.slice(start + 1, i),
12332
+ start: start + 1,
12333
+ end: i
12334
+ };
12335
+ }
12336
+ if (c === "\\" || c === "$" && src.charAt(i + 1) === "{") break;
12337
+ }
12338
+ }
12339
+ /**
12340
+ * Read the elements up to `close`, each by `read`, which leaves the cursor
12341
+ * after what it read. False if the text ends first, or cannot be read.
12342
+ */
12343
+ elements(close, read) {
12344
+ this.i++;
12345
+ for (;;) {
12346
+ this.space();
12347
+ const c = this.src.charAt(this.i);
12348
+ if (c === close) {
12349
+ this.i++;
12350
+ return true;
12351
+ }
12352
+ if (c === ",") {
12353
+ this.i++;
12354
+ continue;
12355
+ }
12356
+ if (this.failed || this.i >= this.src.length) return false;
12357
+ const before = this.i;
12358
+ read();
12359
+ if (this.i === before) this.fail();
12360
+ }
12361
+ }
12362
+ array() {
12363
+ const items = [];
12364
+ return this.elements("]", () => items.push(this.member())) ? {
12365
+ type: "array",
12366
+ items
12367
+ } : void 0;
12368
+ }
12369
+ record() {
12370
+ const props = /* @__PURE__ */ new Map();
12371
+ return this.elements("}", () => {
12372
+ const key = this.key();
12373
+ this.space();
12374
+ if (key !== void 0 && this.src.charAt(this.i) === ":") {
12375
+ this.i++;
12376
+ props.set(key, this.member());
12377
+ } else if (!this.skipMember()) this.fail();
12378
+ }) ? {
12379
+ type: "object",
12380
+ props
12381
+ } : void 0;
12382
+ }
12383
+ /** Stop reading: the text cannot be skipped through. */
12384
+ fail() {
12385
+ this.failed = true;
12386
+ }
12387
+ };
12388
+ /** The text with everything but code (strings, comments, regexes) blanked. */
12389
+ function codeOnly(source) {
12390
+ const chars = Array.from({ length: source.length }, () => " ");
12391
+ lexJs(source, { code(ch, index) {
12392
+ for (let k = 0; k < ch.length; k++) chars[index + k] = ch[k];
12393
+ } }, "statements");
12394
+ return chars.join("");
12395
+ }
12396
+ var stringOf = (d) => d?.type === "string" ? d : void 0;
12397
+ var booleanOf = (d) => d?.type === "boolean" ? d.value : void 0;
12398
+ var textOf = (d) => stringOf(d)?.value;
12399
+ var stringsOf = (d) => d?.type === "array" ? d.items.flatMap((item) => stringOf(item)?.value ?? []) : [];
12400
+ /** `{ [key]: value }` if `read` finds the property `key` written out, else `{}`. */
12401
+ function written(props, key, read) {
12402
+ const value = read(props.get(key));
12403
+ return value === void 0 ? {} : { [key]: value };
12404
+ }
12405
+ /** A declared parameter, if its name and type are written out. */
12406
+ function parameterOf(datum) {
12407
+ if (datum?.type !== "object") return void 0;
12408
+ const { props } = datum;
12409
+ const name = stringOf(props.get("name"));
12410
+ const type = stringOf(props.get("type"));
12411
+ if (!name || !type) return void 0;
12412
+ const param = {
12413
+ name: name.value,
12414
+ type: type.value,
12415
+ ...written(props, "required", booleanOf),
12416
+ ...written(props, "description", textOf),
12417
+ ...written(props, "holds", (d) => textOf(d))
12418
+ };
12419
+ if (props.has("parameters")) {
12420
+ const options = parametersOf(props.get("parameters"));
12421
+ if (!options) return void 0;
12422
+ param.parameters = options;
12423
+ }
12424
+ return param;
12425
+ }
12426
+ /** The parameters of an array literal of them, if every one is written out. */
12427
+ function parametersOf(datum) {
12428
+ if (datum?.type !== "array") return void 0;
12429
+ const params = [];
12430
+ for (const item of datum.items) {
12431
+ const param = parameterOf(item);
12432
+ if (!param) return void 0;
12433
+ params.push(param);
12434
+ }
12435
+ return params;
12436
+ }
12437
+ /** The macro a config object declares, if its name is written out. */
12438
+ function macroOf(config) {
12439
+ if (config.type !== "object") return void 0;
12440
+ const { props } = config;
12441
+ const name = stringOf(props.get("name"));
12442
+ if (!name?.value) return void 0;
12443
+ const subMacros = stringsOf(props.get("subMacros"));
12444
+ const block = booleanOf(props.get("block"));
12445
+ const macro = {
12446
+ name: name.value,
12447
+ block: block === true || block !== false && subMacros.length > 0,
12448
+ subMacros,
12449
+ nameStart: name.start,
12450
+ nameEnd: name.end,
12451
+ ...written(props, "interpolate", booleanOf),
12452
+ ...written(props, "storeVar", booleanOf),
12453
+ ...written(props, "merged", booleanOf),
12454
+ ...written(props, "description", textOf)
12455
+ };
12456
+ const parameters = parametersOf(props.get("parameters"));
12457
+ if (parameters) try {
12458
+ checkParameterTypes(macro.name, parameters);
12459
+ macro.parameters = parameters;
12460
+ } catch {}
12461
+ return macro;
12462
+ }
12463
+ /**
12464
+ * The macros the `defineMacro({ … })` and `Story.defineMacro({ … })` calls in
12465
+ * `source` (JavaScript: a script passage, the body of a `{do}`, a project
12466
+ * file) declare, in source order, read from the text without running it. A
12467
+ * call whose config is an object literal (or a variable declared as one with
12468
+ * `const`, `let` or `var`) and whose `name` is a string is found, wherever it
12469
+ * is, even inside a function. Only what is written out is read: a `block`,
12470
+ * `interpolate`, `storeVar` or `merged` that is a boolean literal, the
12471
+ * strings of `subMacros`, and `parameters` when every one is an object
12472
+ * literal with a string `name` and `type` (and `holds`, `required`,
12473
+ * `description` and nested `parameters` of options when written out as such);
12474
+ * a list with a parameter that is not, or that `defineMacro` would refuse,
12475
+ * declares none. It is tolerant: text it cannot read is skipped, and it
12476
+ * throws for none.
12477
+ */
12478
+ function discoverMacros(source) {
12479
+ const code = codeOnly(source);
12480
+ const found = [];
12481
+ for (const call of code.matchAll(CALL_RE)) {
12482
+ let at = call.index + call[0].length;
12483
+ if (code.charAt(at) !== "{") {
12484
+ const variable = IDENTIFIER_ARGUMENT_RE.exec(code.slice(at))?.[1];
12485
+ if (!variable) continue;
12486
+ const declaration = new RegExp(`(?<![\\w$.])(?:const|let|var)\\s+${variable.replace(/\$/g, "\\$")}\\s*=\\s*(?=\\{)`).exec(code);
12487
+ if (!declaration) continue;
12488
+ at = declaration.index + declaration[0].length;
12489
+ }
12490
+ const reader = new ConfigReader(source);
12491
+ reader.i = at;
12492
+ const config = reader.datum();
12493
+ const macro = config && macroOf(config);
12494
+ if (macro) found.push(macro);
12495
+ }
12496
+ return found;
12497
+ }
12498
+ //#endregion
12065
12499
  //#region src/components/macros/include-args.ts
12066
12500
  /**
12067
12501
  * The parameters of `{include}`. A standalone `inline` flag only counts
@@ -12170,7 +12604,8 @@ function validateStoryMarkup(passages, macros, options = {}) {
12170
12604
  macroNames: known,
12171
12605
  parametersOf,
12172
12606
  isBlockMacro: (name) => blocks.has(name.toLowerCase()) || isBlockMacro(name),
12173
- checkPassageNames: options.checkPassageNames
12607
+ checkPassageNames: options.checkPassageNames,
12608
+ tolerant: options.tolerant
12174
12609
  });
12175
12610
  }
12176
12611
  /** Whether a macro takes a body, among `macros` and the built-in ones. */
@@ -12217,11 +12652,12 @@ function widgetDefinitions(passages, macros = []) {
12217
12652
  /** Passages tagged so hold code or styles, not markup. */
12218
12653
  var NOT_MARKUP_TAGS = ["script", "stylesheet"];
12219
12654
  /** What reading the variable references of markup depends on. */
12220
- function referenceOptions(macros) {
12221
- const all = [...macros];
12655
+ function referenceOptions(macros, all = false) {
12656
+ const list = [...macros];
12222
12657
  return {
12223
- storeVarMacros: new Set(all.filter((m) => m.storeVar).map((m) => m.name.toLowerCase())),
12224
- parametersOf: parameterLookup(all),
12658
+ all,
12659
+ storeVarMacros: new Set(list.filter((m) => m.storeVar).map((m) => m.name.toLowerCase())),
12660
+ parametersOf: parameterLookup(list),
12225
12661
  tolerant: true
12226
12662
  };
12227
12663
  }
@@ -12233,9 +12669,16 @@ function referenceOptions(macros) {
12233
12669
  * bound by input macros, and the markup in labels and HTML attributes. Prose
12234
12670
  * is literal text. Malformed tags are skipped, so it reads half-typed markup.
12235
12671
  * The macros are those the markup may use, built-in and user-defined.
12672
+ *
12673
+ * These are the references the story start checks. With `all: true`, the
12674
+ * list is complete (the checked ones are among it, in source order): it also
12675
+ * has the variable a macro names in a `variable` parameter, such as the
12676
+ * target of `{unset}` and `{computed}`, and the `{$name}` in the selectors of
12677
+ * a link, display or expression (`[[.c{$name} Go->T]]`). A rename or a find
12678
+ * of references needs these too.
12236
12679
  */
12237
- function variableReferences(source, macros = []) {
12238
- return collectVariableReferences(source, referenceOptions(macros));
12680
+ function variableReferences(source, macros = [], options = {}) {
12681
+ return collectVariableReferences(source, referenceOptions(macros, options.all));
12239
12682
  }
12240
12683
  /**
12241
12684
  * The variable references of the passages' markup that are not valid against
@@ -12248,4 +12691,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
12248
12691
  return checkVariableReferences([...passages].filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros));
12249
12692
  }
12250
12693
  //#endregion
12251
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, 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 };
12694
+ 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 };