@rohal12/spindle 0.62.6 → 0.62.8

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.
@@ -30,6 +30,12 @@ var NameMap = class extends Map {
30
30
  return super.delete(name.toLowerCase());
31
31
  }
32
32
  };
33
+ /** The latest definition of each name, using runtime replacement precedence. */
34
+ function effectiveNamedDefinitions(definitions) {
35
+ const latest = new NameMap();
36
+ for (const definition of definitions) latest.set(definition.name, definition);
37
+ return [...latest.values()];
38
+ }
33
39
  /** A set of macro or widget names (see NameMap). */
34
40
  var NameSet = class {
35
41
  constructor(names = []) {
@@ -3630,6 +3636,98 @@ function peg$parse(input, options) {
3630
3636
  if (peg$success) return peg$result;
3631
3637
  else peg$throw();
3632
3638
  }
3639
+ new NameMap();
3640
+ new NameMap();
3641
+ new NameSet();
3642
+ /**
3643
+ * How a macro argument is read (see components/macros/macro-args.ts). Every
3644
+ * declared parameter names one: there is no default.
3645
+ * Quoted strings accept `\"`, `\'` and `\\` escapes.
3646
+ * - `expression`: code, as written.
3647
+ * - `statements`: code run as statements (`{set}`), as written.
3648
+ * - `passage`: a passage name: a quoted string or an expression, as written.
3649
+ * - `variable`: a variable reference such as `$name` or `"$name"`, as written.
3650
+ * - `string`: one quoted string; anything else leaves the argument unset.
3651
+ * - `text`: one quoted string, or text with any loose quotes stripped.
3652
+ * - `names`: a comma-separated list of names (`@item, @i`).
3653
+ * - `delay`: a duration (`2s`, `500ms`, `300`) in milliseconds.
3654
+ * - `number`: a number.
3655
+ * - `flag`: a keyword, the parameter's name, at the start or end; a boolean.
3656
+ * - `separator`: a word (`of`) or `=` separating the parameters before it
3657
+ * from those after it; a boolean.
3658
+ * - `options`: keywords, the names of its `parameters`, each followed by a
3659
+ * quoted string or a number unless it is a flag.
3660
+ */
3661
+ var PARAMETER_TYPES = [
3662
+ "expression",
3663
+ "statements",
3664
+ "passage",
3665
+ "variable",
3666
+ "string",
3667
+ "text",
3668
+ "names",
3669
+ "delay",
3670
+ "number",
3671
+ "flag",
3672
+ "separator",
3673
+ "options"
3674
+ ];
3675
+ /**
3676
+ * What the value of a `string` or `text` argument holds, for the check at
3677
+ * story start and for tooling (see code-check.ts):
3678
+ * - `markup`: markup the macro renders (`{button}`'s label): its markup
3679
+ * is checked.
3680
+ * - `text`: plain text the macro uses as written (`{checkbox}`'s label).
3681
+ * - `passage`: a passage name (`{watch}`'s `goto`): the passage must exist.
3682
+ * - `expression`, `statements`: code (`{watch}`'s condition and `run`): it
3683
+ * is checked as code, and its variable references against the schema.
3684
+ *
3685
+ * Without it, the argument of a macro with `interpolate` holds `markup`,
3686
+ * any other `text`.
3687
+ */
3688
+ var STRING_HOLDS = [
3689
+ "markup",
3690
+ "text",
3691
+ "passage",
3692
+ "expression",
3693
+ "statements"
3694
+ ];
3695
+ /**
3696
+ * Throw if a parameter `macro` declares (or an option of one) has no type,
3697
+ * or one that isn't a ParameterType: arguments are read by their type, and
3698
+ * there is no default. Throw too if it declares what it `holds` wrongly.
3699
+ */
3700
+ function checkParameterTypes(macro, parameters) {
3701
+ const holdsFix = `Give a \`string\` or \`text\` parameter one of ${STRING_HOLDS.join(", ")} to hold (see docs/custom-macros.md#what-a-string-holds).`;
3702
+ for (const param of parameters) {
3703
+ const type = param.type;
3704
+ if (!PARAMETER_TYPES.includes(type)) throw parameterError(macro, param, type === void 0 ? "has no type" : `has the unknown type ${JSON.stringify(type)}`, `Give it one of the types ${PARAMETER_TYPES.join(", ")} (see docs/custom-macros.md#parameter-types), or declare no parameters and read props.rawArgs.`);
3705
+ const holds = param.holds;
3706
+ if (holds !== void 0 && type !== "string" && type !== "text") throw parameterError(macro, param, `is of the type ${type}, which holds what it is`, holdsFix);
3707
+ if (holds !== void 0 && !STRING_HOLDS.includes(holds)) throw parameterError(macro, param, `holds the unknown ${JSON.stringify(holds)}`, holdsFix);
3708
+ if (param.parameters) checkParameterTypes(macro, param.parameters);
3709
+ }
3710
+ }
3711
+ /** The error for the parameter `param` of `macro`: what is wrong, and the fix. */
3712
+ function parameterError(macro, param, problem, fix) {
3713
+ return /* @__PURE__ */ new Error(`spindle: The parameter "${param.name}" of the macro {${macro}} ${problem}. ${fix}`);
3714
+ }
3715
+ var metadataRegistry = new NameMap();
3716
+ /** Indexed at registration, so parsing each tag does not scan every macro. */
3717
+ var companionParents = new NameMap();
3718
+ /** The parents declaring a branching companion (listbox options are values). */
3719
+ function branchParents(name, macros) {
3720
+ if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox");
3721
+ return effectiveNamedDefinitions(macros).filter((macro) => macro.name.toLowerCase() !== "listbox" && macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase())).map((macro) => macro.name.toLowerCase());
3722
+ }
3723
+ /** The declared parameters of the macro `name`, if it declares any. */
3724
+ function getMacroParameters(name) {
3725
+ return metadataRegistry.get(name)?.parameters;
3726
+ }
3727
+ getMacroParameters.source = (name) => metadataRegistry.get(name)?.source;
3728
+ function getMacroRegistry() {
3729
+ return Array.from(metadataRegistry.values());
3730
+ }
3633
3731
  //#endregion
3634
3732
  //#region src/markup/ast.ts
3635
3733
  /**
@@ -3726,7 +3824,7 @@ function astNode({ token, body }) {
3726
3824
  };
3727
3825
  if (!body) return withSelectors$1(node, token);
3728
3826
  const children = buildAst(body.children);
3729
- const branching = BRANCHING.has(name) && !WIDGETS.has(name);
3827
+ const branching = BRANCHING.has(name) && !WIDGETS.has(name) && getMacroParameters.source(name) !== "user";
3730
3828
  if (!branching && body.branches.length === 0) {
3731
3829
  node.children = children;
3732
3830
  return withSelectors$1(node, token);
@@ -3741,97 +3839,18 @@ function astNode({ token, body }) {
3741
3839
  }
3742
3840
  }
3743
3841
  }
3744
- new NameMap();
3745
- new NameMap();
3746
- new NameSet();
3747
- /**
3748
- * How a macro argument is read (see components/macros/macro-args.ts). Every
3749
- * declared parameter names one: there is no default.
3750
- * Quoted strings accept `\"`, `\'` and `\\` escapes.
3751
- * - `expression`: code, as written.
3752
- * - `statements`: code run as statements (`{set}`), as written.
3753
- * - `passage`: a passage name: a quoted string or an expression, as written.
3754
- * - `variable`: a variable reference such as `$name` or `"$name"`, as written.
3755
- * - `string`: one quoted string; anything else leaves the argument unset.
3756
- * - `text`: one quoted string, or text with any loose quotes stripped.
3757
- * - `names`: a comma-separated list of names (`@item, @i`).
3758
- * - `delay`: a duration (`2s`, `500ms`, `300`) in milliseconds.
3759
- * - `number`: a number.
3760
- * - `flag`: a keyword, the parameter's name, at the start or end; a boolean.
3761
- * - `separator`: a word (`of`) or `=` separating the parameters before it
3762
- * from those after it; a boolean.
3763
- * - `options`: keywords, the names of its `parameters`, each followed by a
3764
- * quoted string or a number unless it is a flag.
3765
- */
3766
- var PARAMETER_TYPES = [
3767
- "expression",
3768
- "statements",
3769
- "passage",
3770
- "variable",
3771
- "string",
3772
- "text",
3773
- "names",
3774
- "delay",
3775
- "number",
3776
- "flag",
3777
- "separator",
3778
- "options"
3779
- ];
3780
- /**
3781
- * What the value of a `string` or `text` argument holds, for the check at
3782
- * story start and for tooling (see code-check.ts):
3783
- * - `markup`: markup the macro renders (`{button}`'s label): its markup
3784
- * is checked.
3785
- * - `text`: plain text the macro uses as written (`{checkbox}`'s label).
3786
- * - `passage`: a passage name (`{watch}`'s `goto`): the passage must exist.
3787
- * - `expression`, `statements`: code (`{watch}`'s condition and `run`): it
3788
- * is checked as code, and its variable references against the schema.
3789
- *
3790
- * Without it, the argument of a macro with `interpolate` holds `markup`,
3791
- * any other `text`.
3792
- */
3793
- var STRING_HOLDS = [
3794
- "markup",
3795
- "text",
3796
- "passage",
3797
- "expression",
3798
- "statements"
3799
- ];
3800
- /**
3801
- * Throw if a parameter `macro` declares (or an option of one) has no type,
3802
- * or one that isn't a ParameterType: arguments are read by their type, and
3803
- * there is no default. Throw too if it declares what it `holds` wrongly.
3804
- */
3805
- function checkParameterTypes(macro, parameters) {
3806
- const holdsFix = `Give a \`string\` or \`text\` parameter one of ${STRING_HOLDS.join(", ")} to hold (see docs/custom-macros.md#what-a-string-holds).`;
3807
- for (const param of parameters) {
3808
- const type = param.type;
3809
- if (!PARAMETER_TYPES.includes(type)) throw parameterError(macro, param, type === void 0 ? "has no type" : `has the unknown type ${JSON.stringify(type)}`, `Give it one of the types ${PARAMETER_TYPES.join(", ")} (see docs/custom-macros.md#parameter-types), or declare no parameters and read props.rawArgs.`);
3810
- const holds = param.holds;
3811
- if (holds !== void 0 && type !== "string" && type !== "text") throw parameterError(macro, param, `is of the type ${type}, which holds what it is`, holdsFix);
3812
- if (holds !== void 0 && !STRING_HOLDS.includes(holds)) throw parameterError(macro, param, `holds the unknown ${JSON.stringify(holds)}`, holdsFix);
3813
- if (param.parameters) checkParameterTypes(macro, param.parameters);
3814
- }
3815
- }
3816
- /** The error for the parameter `param` of `macro`: what is wrong, and the fix. */
3817
- function parameterError(macro, param, problem, fix) {
3818
- return /* @__PURE__ */ new Error(`spindle: The parameter "${param.name}" of the macro {${macro}} ${problem}. ${fix}`);
3819
- }
3820
- var metadataRegistry = new NameMap();
3821
- /** Indexed at registration, so parsing each tag does not scan every macro. */
3822
- var companionParents = new NameMap();
3823
- /** The parents declaring a branching companion (listbox options are values). */
3824
- function branchParents(name, macros) {
3825
- if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox");
3826
- return macros.filter((macro) => macro.name.toLowerCase() !== "listbox" && macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase())).map((macro) => macro.name.toLowerCase());
3827
- }
3828
- /** The declared parameters of the macro `name`, if it declares any. */
3829
- function getMacroParameters(name) {
3830
- return metadataRegistry.get(name)?.parameters;
3831
- }
3832
- getMacroParameters.source = (name) => metadataRegistry.get(name)?.source;
3833
- function getMacroRegistry() {
3834
- return Array.from(metadataRegistry.values());
3842
+ //#endregion
3843
+ //#region src/utils/sorted.ts
3844
+ /** Index of the first sorted value greater than `value` (or the length). */
3845
+ function upperBound(sorted, value) {
3846
+ let low = 0;
3847
+ let high = sorted.length;
3848
+ while (low < high) {
3849
+ const mid = low + high >>> 1;
3850
+ if (sorted[mid] <= value) low = mid + 1;
3851
+ else high = mid;
3852
+ }
3853
+ return low;
3835
3854
  }
3836
3855
  //#endregion
3837
3856
  //#region src/markup/line-column.ts
@@ -3854,14 +3873,7 @@ function sourcePositions(text) {
3854
3873
  const starts = [0];
3855
3874
  for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
3856
3875
  return (offset) => {
3857
- let low = 0;
3858
- let high = starts.length;
3859
- while (low < high) {
3860
- const mid = low + high >>> 1;
3861
- if (starts[mid] <= offset) low = mid + 1;
3862
- else high = mid;
3863
- }
3864
- const line = Math.max(1, low);
3876
+ const line = Math.max(1, upperBound(starts, offset));
3865
3877
  return {
3866
3878
  line,
3867
3879
  column: offset - starts[line - 1] + 1
@@ -9572,6 +9584,39 @@ function parseWithAst(src, goal) {
9572
9584
  }
9573
9585
  }
9574
9586
  /**
9587
+ * Read `src` as a reference path: a variable with any number of `.name` and
9588
+ * `[expression]` members after it (`$data["field"]`, `@list[_i].x`), and
9589
+ * nothing else. Returns null for any other code (`$a + 1`, `$a.b()`, `$a,
9590
+ * $b`, `$a = 1`), and throws a `CodeSyntaxError` for code that is not
9591
+ * well-formed.
9592
+ */
9593
+ function parseReferencePath(src) {
9594
+ const { ast } = parseWithAst(src, "expression");
9595
+ let node = ast.type === "ChainExpression" ? ast.expression : ast;
9596
+ let nested = false;
9597
+ while (node.type === "MemberExpression") {
9598
+ node = node.object;
9599
+ nested = true;
9600
+ }
9601
+ if (node.type !== "Identifier") return null;
9602
+ const sigil = sigilOf(node, src);
9603
+ if (!sigil || node.start !== 0) return null;
9604
+ return {
9605
+ sigil: sigil[0],
9606
+ name: sigil[1],
9607
+ nested
9608
+ };
9609
+ }
9610
+ /** Decode one dot-member identifier, including keywords and Unicode names. */
9611
+ function parseMemberIdentifier(src) {
9612
+ const { ast } = parseWithAst(`x.${src}`, "expression");
9613
+ if (ast.type !== "MemberExpression" || ast.computed) return null;
9614
+ const object = ast.object;
9615
+ const property = ast.property;
9616
+ if (object.type !== "Identifier" || object.start !== 0 || object.end !== 1 || property.type !== "Identifier" || property.start !== 2 || property.end !== src.length + 2) return null;
9617
+ return property.name;
9618
+ }
9619
+ /**
9575
9620
  * Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
9576
9621
  * noting where it read a transient in `transientsRead`.
9577
9622
  */
@@ -10281,7 +10326,7 @@ function isCodeAttribute(name) {
10281
10326
  * Split a code attribute value into literal text and its `{…}` blocks that
10282
10327
  * start with a sigil. Braces inside strings don't close a block; an
10283
10328
  * unclosed block, any other brace and backslashes are text. A block whose
10284
- * sigil is not followed by a word character (`{$(…)}`) is code, kept
10329
+ * sigil is not followed by an identifier (`{$(…)}`) is code, kept
10285
10330
  * verbatim: not resolved, and not decoded like text.
10286
10331
  */
10287
10332
  function splitSigilTemplate(template, incomplete = false) {
@@ -10306,7 +10351,11 @@ function splitSigilTemplate(template, incomplete = false) {
10306
10351
  if (text) parts.push({ text });
10307
10352
  text = "";
10308
10353
  const block = template.slice(i, end);
10309
- parts.push(/^.\w/.test(block) || incomplete && block.length === 1 && end === template.length ? { expr: block } : { verbatim: `{${block}}` });
10354
+ let reference = /^.\w/.test(block);
10355
+ if (!reference && block[1] === "\\") lexJs(block, { variable(_sigil, _name, start) {
10356
+ if (start === 0) reference = true;
10357
+ } });
10358
+ parts.push(reference || incomplete && block.length === 1 && end === template.length ? { expr: block } : { verbatim: `{${block}}` });
10310
10359
  i = end + 1;
10311
10360
  }
10312
10361
  if (text) parts.push({ text });
@@ -10388,7 +10437,12 @@ function analyzeMarkup(source, options = {}) {
10388
10437
  nodes: paired.nodes,
10389
10438
  errors
10390
10439
  };
10391
- const inDamage = (start) => errors.some((e, i) => start >= damage[i] && start <= e.offset);
10440
+ const damageEnds = [];
10441
+ for (const e of errors) damageEnds.push(Math.max(damageEnds[damageEnds.length - 1] ?? -1, e.offset));
10442
+ const inDamage = (start) => {
10443
+ const index = upperBound(damage, start) - 1;
10444
+ return index >= 0 && start <= damageEnds[index];
10445
+ };
10392
10446
  const noticed = errors.map((e, i) => [damage[i] + .5, e]);
10393
10447
  const position = paired.errors.length ? sourcePositions(source) : void 0;
10394
10448
  for (const error of paired.errors) if (!inDamage(error.start)) noticed.push([error.noticedAt, pairingError(position, error)]);
@@ -10601,6 +10655,39 @@ function noPassageError(name, from) {
10601
10655
  }
10602
10656
  listeners.subscribe;
10603
10657
  //#endregion
10658
+ //#region src/utils/namespace.ts
10659
+ /** The variable name no namespace can hold. */
10660
+ var RESERVED_NAME = "__proto__";
10661
+ /**
10662
+ * Why `name` (without its sigil) cannot be a variable name, or undefined if
10663
+ * it can. `label` is the name as the author wrote it (e.g. `$__proto__`).
10664
+ */
10665
+ function variableNameError(name, label = name) {
10666
+ return name === "__proto__" ? `"${label}" cannot be used as a variable name (${RESERVED_NAME} is reserved)` : void 0;
10667
+ }
10668
+ /** Whether a property key is an array index (`"0"`, `"12"`; not `"01"`). */
10669
+ var isArrayIndex = (key) => /^(?:0|[1-9]\d*)$/.test(key);
10670
+ /** Whether `obj` holds `key` as an own property. */
10671
+ var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
10672
+ /**
10673
+ * A record with no prototype holding the own entries of `sources`, or only
10674
+ * those whose value passes `keep`.
10675
+ */
10676
+ function ownEntries(sources, keep = () => true) {
10677
+ const record = Object.create(null);
10678
+ for (const source of sources) {
10679
+ if (!source) continue;
10680
+ for (const key of Object.keys(source)) {
10681
+ const value = source[key];
10682
+ if (keep(value)) record[key] = value;
10683
+ }
10684
+ }
10685
+ return record;
10686
+ }
10687
+ /** A namespace with no prototype holding the own entries of `sources`. */
10688
+ var createNamespace = (...sources) => ownEntries(sources);
10689
+ Object.freeze(createNamespace());
10690
+ //#endregion
10604
10691
  //#region src/components/macros/arg-utils.ts
10605
10692
  /**
10606
10693
  * Shared helpers for macros that split or read their raw argument text by
@@ -11085,6 +11172,62 @@ function evaluatePassageName(expr, evaluate, { storyData, currentPassage }) {
11085
11172
  return name;
11086
11173
  }
11087
11174
  /**
11175
+ * The variable a `storeVar` macro binds: its first term, as written. Custom
11176
+ * macros may bind one without declaring parameters.
11177
+ */
11178
+ function readBoundVariable(rawArgs) {
11179
+ const src = rawArgs.trim();
11180
+ const first = terms(src)[0];
11181
+ return first ? slice(src, first) : "";
11182
+ }
11183
+ /**
11184
+ * Read the first term as the runtime's story-variable binding. Quotes are
11185
+ * stripped, but this is an identifier path, not a JavaScript string literal:
11186
+ * only identifier escapes are decoded. Returns null for a missing binding;
11187
+ * throws for rejected namespaces, invalid escapes and reserved path names.
11188
+ * The full span excludes quotes and includes the sigil when written.
11189
+ */
11190
+ function parseBoundVariable(rawArgs) {
11191
+ const term = readBoundVariable(rawArgs);
11192
+ if (!term) return null;
11193
+ const lead = rawArgs.length - rawArgs.trimStart().length;
11194
+ const offsets = [];
11195
+ for (let i = 0; i < term.length; i++) if (term[i] !== "\"" && term[i] !== "'") offsets.push(lead + i);
11196
+ const firstToken = term.replace(/["']/g, "");
11197
+ const kind = {
11198
+ "%": "transient variables",
11199
+ _: "temporary variables",
11200
+ "@": "locals"
11201
+ }[firstToken.charAt(0)];
11202
+ if (kind) throw new Error(`${kind} (${firstToken}) cannot be bound to input macros`);
11203
+ const explicitSigil = firstToken.startsWith("$");
11204
+ if (!explicitSigil && firstToken.split(".")[0].includes("\\")) throw new Error("Escaped binding identifiers require a literal $ story-variable sigil");
11205
+ const segments = firstToken.replace(/^\$/, "").split(".").map((segment, index) => {
11206
+ if (!segment.includes("\\")) return segment;
11207
+ if (index > 0) {
11208
+ const name = parseMemberIdentifier(segment);
11209
+ if (name === null) throw new Error("Invalid bound identifier");
11210
+ return name;
11211
+ }
11212
+ const reference = parseReferencePath(`$${segment}`);
11213
+ if (!reference || reference.nested) throw new Error("Invalid bound identifier");
11214
+ return reference.name;
11215
+ });
11216
+ if (segments.includes("__proto__")) throw new Error(`"$${segments.join(".")}" cannot be bound: ${RESERVED_NAME} is reserved`);
11217
+ const rootStart = explicitSigil ? 1 : 0;
11218
+ const rootEnd = firstToken.indexOf(".", rootStart);
11219
+ const nameEnd = rootEnd < 0 ? firstToken.length : rootEnd;
11220
+ return {
11221
+ name: segments[0],
11222
+ path: segments.slice(1),
11223
+ explicitSigil,
11224
+ start: offsets[0] ?? lead,
11225
+ end: offsets.length ? offsets[offsets.length - 1] + 1 : lead,
11226
+ nameStart: offsets[rootStart] ?? lead + rootStart,
11227
+ nameEnd: offsets[nameEnd - 1] === void 0 ? lead : offsets[nameEnd - 1] + 1
11228
+ };
11229
+ }
11230
+ /**
11088
11231
  * The runtime's argument grouping, tolerant of missing or unclosed strings.
11089
11232
  * Includes quotes, flags, separators and option keywords; offsets are into
11090
11233
  * rawArgs. Absent arguments have no span. Options also have their enclosing
@@ -11124,39 +11267,6 @@ function subMacroParameters(name) {
11124
11267
  return SUB_MACRO_PARAMETERS.get(name.toLowerCase());
11125
11268
  }
11126
11269
  //#endregion
11127
- //#region src/utils/namespace.ts
11128
- /** The variable name no namespace can hold. */
11129
- var RESERVED_NAME = "__proto__";
11130
- /**
11131
- * Why `name` (without its sigil) cannot be a variable name, or undefined if
11132
- * it can. `label` is the name as the author wrote it (e.g. `$__proto__`).
11133
- */
11134
- function variableNameError(name, label = name) {
11135
- return name === "__proto__" ? `"${label}" cannot be used as a variable name (${RESERVED_NAME} is reserved)` : void 0;
11136
- }
11137
- /** Whether a property key is an array index (`"0"`, `"12"`; not `"01"`). */
11138
- var isArrayIndex = (key) => /^(?:0|[1-9]\d*)$/.test(key);
11139
- /** Whether `obj` holds `key` as an own property. */
11140
- var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
11141
- /**
11142
- * A record with no prototype holding the own entries of `sources`, or only
11143
- * those whose value passes `keep`.
11144
- */
11145
- function ownEntries(sources, keep = () => true) {
11146
- const record = Object.create(null);
11147
- for (const source of sources) {
11148
- if (!source) continue;
11149
- for (const key of Object.keys(source)) {
11150
- const value = source[key];
11151
- if (keep(value)) record[key] = value;
11152
- }
11153
- }
11154
- return record;
11155
- }
11156
- /** A namespace with no prototype holding the own entries of `sources`. */
11157
- var createNamespace = (...sources) => ownEntries(sources);
11158
- Object.freeze(createNamespace());
11159
- //#endregion
11160
11270
  //#region src/code-check.ts
11161
11271
  /** While a pass runs: the code it parsed so far, by goal and source. */
11162
11272
  var parses = null;
@@ -12704,8 +12814,6 @@ function declarationRegex(sigil) {
12704
12814
  }
12705
12815
  /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
12706
12816
  var VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
12707
- /** Quoted first argument of an input macro naming a story variable. */
12708
- var QUOTED_VAR_ARG_RE = /^["']\$(\w+(?:\.\w+)*)["']?$/;
12709
12817
  var VALID_VAR_TYPES = /* @__PURE__ */ new Set([
12710
12818
  "number",
12711
12819
  "string",
@@ -13072,6 +13180,30 @@ function scanSelectors(content, token, at, emit, options) {
13072
13180
  storeVarMacros: NO_STORE_VAR_MACROS
13073
13181
  });
13074
13182
  }
13183
+ /** Read a runtime binding and map its editable spans into the passage. */
13184
+ function boundReference(token, at, all) {
13185
+ try {
13186
+ const binding = parseBoundVariable(token.rawArgs);
13187
+ if (!binding || !all && !binding.explicitSigil) return void 0;
13188
+ const mapped = {
13189
+ ...binding,
13190
+ start: at(token.argsStart + binding.start),
13191
+ end: at(token.argsStart + binding.end),
13192
+ nameStart: at(token.argsStart + binding.nameStart),
13193
+ nameEnd: at(token.argsStart + binding.nameEnd)
13194
+ };
13195
+ return {
13196
+ sigil: "$",
13197
+ name: binding.name,
13198
+ path: binding.path,
13199
+ start: mapped.start,
13200
+ end: mapped.end,
13201
+ binding: mapped
13202
+ };
13203
+ } catch {
13204
+ return;
13205
+ }
13206
+ }
13075
13207
  /** Report the `$var` references in the tokens of `content`. */
13076
13208
  function collectTokenRefs(content, tokens, at, emit, options) {
13077
13209
  const { storeVarMacros, parametersOf } = options;
@@ -13100,24 +13232,12 @@ function collectTokenRefs(content, tokens, at, emit, options) {
13100
13232
  else scanInterpolations(value, valueIn, emit, options);
13101
13233
  }
13102
13234
  else if (token.type === "macro" && !token.isClose) {
13103
- scanArgs(token, parametersOf, at, emit, options);
13235
+ const binding = storeVarMacros.has(token.name.toLowerCase()) && !parametersOf.widget?.(token.name) ? boundReference(token, at, options.all) : void 0;
13236
+ scanArgs(token, parametersOf, at, (ref) => {
13237
+ if (!binding || ref.start < binding.start || ref.start >= binding.end) emit(ref);
13238
+ }, options);
13104
13239
  scanSelectors(content, token, at, emit, options);
13105
- if (storeVarMacros.has(token.name.toLowerCase()) && !parametersOf.widget?.(token.name)) {
13106
- const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
13107
- const first = token.rawArgs.trim().split(/\s+/)[0] ?? "";
13108
- const quoted = QUOTED_VAR_ARG_RE.exec(first);
13109
- if (quoted) {
13110
- const [name, ...path] = quoted[1].split(".");
13111
- const start = token.argsStart + lead + 1;
13112
- emit({
13113
- sigil: "$",
13114
- name,
13115
- path,
13116
- start: at(start),
13117
- end: at(start + 1 + quoted[1].length)
13118
- });
13119
- } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
13120
- }
13240
+ if (binding) emit(binding);
13121
13241
  if (executesRawBody(token.name, parametersOf)) {
13122
13242
  let close = t + 1;
13123
13243
  while (close < tokens.length) {
@@ -25674,9 +25794,14 @@ var transformCache = /* @__PURE__ */ new Map();
25674
25794
  * validator, with no Preact or DOM dependencies. pkg/tooling.js re-exports
25675
25795
  * them, binding the validator to its macro metadata.
25676
25796
  */
25797
+ /** Widgets take precedence over macros regardless of metadata input order. */
25798
+ function effectiveToolingMacros(macros) {
25799
+ const list = [...macros];
25800
+ return effectiveNamedDefinitions([...list.filter((m) => !m.widget), ...list.filter((m) => m.widget)]);
25801
+ }
25677
25802
  function tokenizationOptions(options) {
25678
25803
  if (!options.macros) return options;
25679
- const macros = [...options.macros];
25804
+ const macros = effectiveToolingMacros(options.macros);
25680
25805
  const parametersOf = parameterLookup(macros);
25681
25806
  return {
25682
25807
  ...options,
@@ -25704,7 +25829,7 @@ function tokenizeMarkupTolerant(source, options = {}) {
25704
25829
  */
25705
25830
  function validateStoryMarkup(passages, macros, options = {}) {
25706
25831
  const list = [...passages];
25707
- const all = [...macros];
25832
+ const all = effectiveToolingMacros(macros);
25708
25833
  const known = /* @__PURE__ */ new Set();
25709
25834
  const widgets = effectiveWidgetDefinitions(widgetDefinitions$1(list, parameterLookup(all)));
25710
25835
  const blocks = new Set(widgets.filter((def) => def.block).map((def) => def.name.toLowerCase()));
@@ -25749,7 +25874,7 @@ function blockLookup(macros) {
25749
25874
  * The macros are those the markup may use, built-in and user-defined.
25750
25875
  */
25751
25876
  function passagePieces(source, macros = []) {
25752
- const all = [...macros];
25877
+ const all = effectiveToolingMacros(macros);
25753
25878
  const parametersOf = parameterLookup(all);
25754
25879
  return passagePiecesOfTokens(source, all, tokenizeMarkupTolerant(source, { hooks: { isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0) } }).tokens);
25755
25880
  }
@@ -25759,7 +25884,7 @@ function passagePieces(source, macros = []) {
25759
25884
  * part of the published tooling API.
25760
25885
  */
25761
25886
  function passagePiecesOfTokens(source, macros, tokens) {
25762
- const all = [...macros];
25887
+ const all = effectiveToolingMacros(macros);
25763
25888
  return [...passagePiecesOf(source, tokens, parameterLookup(all), { isBlock: blockLookup(all) })];
25764
25889
  }
25765
25890
  /**
@@ -25806,13 +25931,15 @@ function referenceOptions(macros, all = false, passages = []) {
25806
25931
  * in source order, with the dotted path of fields accessed and where each is
25807
25932
  * written (offsets into `source`, UTF-16): `{$var}` displays, code in
25808
25933
  * expressions, conditions, `{do}` bodies and macro arguments, quoted names
25809
- * bound by input macros, and the markup in labels and HTML attributes. Prose
25934
+ * bound by input macros, and the markup in labels and HTML attributes. Input
25935
+ * bindings include decoded root/path names and editable `binding` spans. Prose
25810
25936
  * is literal text. Malformed tags are skipped, so it reads half-typed markup.
25811
25937
  * The macros are those the markup may use, built-in and user-defined.
25812
25938
  *
25813
25939
  * These are the references the story start checks. With `all: true`, the
25814
25940
  * list is complete (the checked ones are among it, in source order): it also
25815
- * has the variable a macro names in a `variable` parameter, such as the
25941
+ * has sigilless input bindings (`{textbox "name"}`), the variable a macro
25942
+ * names in a `variable` parameter, such as the
25816
25943
  * target of `{unset}` and `{computed}`, and the `{$name}` in the selectors of
25817
25944
  * a link, display or expression (`[[.c{$name} Go->T]]`). A rename or a find
25818
25945
  * of references needs these too.
@@ -25832,4 +25959,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
25832
25959
  return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
25833
25960
  }
25834
25961
  //#endregion
25835
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, lexJs, lexTemplate, macroArgumentSpans, pairMarkup, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
25962
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, lexJs, lexTemplate, macroArgumentSpans, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
@@ -20,6 +20,7 @@ export {
20
20
  formatDiagnostic,
21
21
  parseCode,
22
22
  macroArgumentSpans,
23
+ parseBoundVariable,
23
24
  effectiveWidgetDefinitions,
24
25
  findCodeEnd,
25
26
  lexJs,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.6",
3
+ "version": "0.62.8",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,4 +1,5 @@
1
1
  import { isReaderVisible } from './utils/element-visibility';
2
+ import { readOnlyValue } from './execute-mutation';
2
3
  import { emit } from './event-emitter';
3
4
  import {
4
5
  checkFields,
@@ -250,7 +251,7 @@ export async function settleRunningActions(): Promise<void> {
250
251
  }
251
252
 
252
253
  export function getActions(): StoryAction[] {
253
- return Array.from(actions.values(), listed);
254
+ return readOnlyValue(Array.from(actions.values(), listed));
254
255
  }
255
256
 
256
257
  /**
@@ -258,15 +259,17 @@ export function getActions(): StoryAction[] {
258
259
  * function, see registerAction), its nested dialogs' left out.
259
260
  */
260
261
  export function getDialogActions(dialog: () => void): StoryAction[] {
261
- return Array.from(actions.values())
262
- .map((entries) => entries[entries.length - 1]!)
263
- .filter((entry) => entry.dialog === dialog)
264
- .map((entry) => effectiveAction(entry.action));
262
+ return readOnlyValue(
263
+ Array.from(actions.values())
264
+ .map((entries) => entries[entries.length - 1]!)
265
+ .filter((entry) => entry.dialog === dialog)
266
+ .map((entry) => effectiveAction(entry.action)),
267
+ );
265
268
  }
266
269
 
267
270
  export function getAction(id: string): StoryAction | undefined {
268
271
  const entries = actions.get(id);
269
- return entries && listed(entries);
272
+ return entries && readOnlyValue(listed(entries));
270
273
  }
271
274
 
272
275
  function listed(entries: Entry[]): StoryAction {