@rohal12/spindle 0.64.29 → 0.64.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.
@@ -10516,12 +10516,13 @@ function jsCodeEnd(onOpenEnd) {
10516
10516
  var defaultCodeEnd = jsCodeEnd();
10517
10517
  /**
10518
10518
  * Index possible brace ends for repeated recovery attempts in one template.
10519
- * Within plain code, nested braces must close first. At a quote, slash or
10520
- * escape we stop making lexical assumptions, but the remaining raw `}`s
10521
- * still bound how many pending braces could close. Indexing visits each
10522
- * opener once, so unmatched plain-code openers can skip suffix scans.
10519
+ * Within plain code, nested braces must close first. At a quote, slash,
10520
+ * escape or HTML-style comment we stop making lexical assumptions, but the
10521
+ * remaining raw `}`s still bound how many pending braces could close.
10522
+ * Indexing visits each opener once, so unmatched plain-code openers can
10523
+ * skip suffix scans.
10523
10524
  */
10524
- function indexCodeEnds(input) {
10525
+ function indexCodeEnds(input, closeBrace = defaultCodeEnd.closeBrace) {
10525
10526
  const possible = /* @__PURE__ */ new Set();
10526
10527
  const pending = [];
10527
10528
  let remaining = 0;
@@ -10541,17 +10542,39 @@ function indexCodeEnds(input) {
10541
10542
  remaining--;
10542
10543
  const open = pending.pop();
10543
10544
  if (open !== void 0) possible.add(open);
10544
- } else if (/['"`/\\]/.test(c)) uncertain();
10545
+ } else if (/['"`/\\]/.test(c) || input.startsWith("<!--", i) || input.startsWith("-->", i)) uncertain();
10545
10546
  }
10546
10547
  return (start, codeStart = start, limit = input.length) => {
10547
10548
  if (start > lastBrace || codeStart >= limit) return -1;
10548
10549
  const source = limit === input.length ? input : input.slice(0, limit);
10549
- if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return defaultCodeEnd.closeBrace(source, codeStart, start);
10550
+ if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return closeBrace(source, codeStart, start);
10550
10551
  const base = Math.max(0, codeStart - 1);
10551
10552
  const end = parsedCodeEnd(source.slice(base), codeStart - base, "expression");
10552
10553
  return end < 0 ? -1 : base + end;
10553
10554
  };
10554
10555
  }
10556
+ /**
10557
+ * Reusable strict expression-boundary queries over one immutable source.
10558
+ * Results match `findCodeEnd(input, start)`, without markup's lenient
10559
+ * fallback. The shared brace index prunes unmatched plain-code prefixes;
10560
+ * each queried start is cached independently, including failed queries.
10561
+ */
10562
+ function indexStrictCodeEnds(input) {
10563
+ const read = indexCodeEnds(input, (source, start) => {
10564
+ const base = Math.max(0, start - 1);
10565
+ const end = findCodeEnd(source.slice(base), start - base);
10566
+ return end < 0 ? -1 : base + end;
10567
+ });
10568
+ const ends = /* @__PURE__ */ new Map();
10569
+ return (start) => {
10570
+ let end = ends.get(start);
10571
+ if (end === void 0) {
10572
+ end = read(start);
10573
+ ends.set(start, end);
10574
+ }
10575
+ return end;
10576
+ };
10577
+ }
10555
10578
  // src/markup/code-attributes.ts
10556
10579
  /**
10557
10580
  * Attributes whose value is code with braces of its own, not text: event
@@ -12288,9 +12311,8 @@ function readCompletion(source, cursor, macros, full, sourceLength = source.leng
12288
12311
  return read(source, (i) => i);
12289
12312
  }
12290
12313
  // src/widgets/ast-scanner.ts
12291
- /** The declared parameters of the macros registered so far. */
12292
- var registeredParameters = (name) => parameterLookup(getMacroRegistry())(name);
12293
- registeredParameters.source = getMacroParameters.source;
12314
+ /** Snapshot effective macro metadata once per scan. */
12315
+ var registeredParameters = () => parameterLookup(getMacroRegistry());
12294
12316
  /**
12295
12317
  * Whether the text of an attribute value or macro label renders a
12296
12318
  * `{@children}`: it is markup, parsed as the renderer parses it.
@@ -12317,7 +12339,7 @@ function textContainsChildren(text, parametersOf, hooks, budget = new MarkupExpa
12317
12339
  * are read from it); a token made from an AST has none. Discovery hooks
12318
12340
  * also apply inside these texts, before widgets have been registered.
12319
12341
  */
12320
- function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "", hooks, budget) {
12342
+ function tokenTextContainsChildren(token, parametersOf = registeredParameters(), src = "", hooks, budget) {
12321
12343
  for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf, hooks, budget)) return true;
12322
12344
  return false;
12323
12345
  }
@@ -12328,7 +12350,7 @@ function tokenTextContainsChildren(token, parametersOf = registeredParameters, s
12328
12350
  * entered: its slot belongs to the innermost widget (as widgetDefinitions
12329
12351
  * reads it), and a definition renders nothing of its own.
12330
12352
  */
12331
- function astContainsChildren(nodes, parametersOf = registeredParameters, hooks, budget) {
12353
+ function astContainsChildren(nodes, parametersOf = registeredParameters(), hooks, budget) {
12332
12354
  const pending = [...nodes];
12333
12355
  while (pending.length) {
12334
12356
  const node = pending.pop();
@@ -12429,7 +12451,7 @@ function nameSpan(rawArgs) {
12429
12451
  * here as it is to the parser, and does not make a block widget (#387). In
12430
12452
  * nested definitions, it belongs to the innermost.
12431
12453
  */
12432
- function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
12454
+ function widgetDefinitions$1(passages, parametersOf = registeredParameters()) {
12433
12455
  const list = [...passages];
12434
12456
  const scan = (replacesDo) => {
12435
12457
  const found = [];
@@ -13655,17 +13677,28 @@ function checkVariableReferences(passages, declared, options) {
13655
13677
  return diagnostics;
13656
13678
  }
13657
13679
  // src/js-bindings.ts
13658
- /**
13659
- * Which declaration a variable names where it is used in JavaScript, read
13660
- * from the text without running it (see discoverMacros): the scope the use is
13661
- * in, the declarations of the name that scope can see, and the innermost one.
13662
- *
13663
- * It reads the shape of the code (brackets, and the words before and after a
13664
- * name) in text whose strings, comments and regexes are blanked, so it needs
13665
- * no syntax tree and goes on through code that is not complete. What it
13666
- * cannot place, it counts as a declaration of unknown value: a parameter, a
13667
- * pattern, an assignment. Better no answer than another declaration's.
13668
- */
13680
+ /** Search arbitrary (also recovered, overlapping) bracket intervals. */
13681
+ var GroupIndex = class {
13682
+ constructor(groups) {
13683
+ this.groups = groups;
13684
+ let size = 1;
13685
+ while (size < groups.length) size *= 2;
13686
+ this.size = size;
13687
+ this.ends = new Array(size * 2).fill(-1);
13688
+ for (let i = 0; i < groups.length; i++) this.ends[size + i] = groups[i].close;
13689
+ for (let i = size - 1; i > 0; i--) this.ends[i] = Math.max(this.ends[i * 2], this.ends[i * 2 + 1]);
13690
+ }
13691
+ /** Latest opener before `at` whose closer follows it, in logarithmic time. */
13692
+ containing(at) {
13693
+ const find = (node, start, end) => {
13694
+ if (start >= this.groups.length || this.groups[start].open >= at || this.ends[node] <= at) return void 0;
13695
+ if (end - start === 1) return this.groups[start];
13696
+ const mid = start + end >>> 1;
13697
+ return find(node * 2 + 1, mid, end) ?? find(node * 2, start, mid);
13698
+ };
13699
+ return find(1, 0, this.size);
13700
+ }
13701
+ };
13669
13702
  var CLOSERS = {
13670
13703
  "}": "{",
13671
13704
  ")": "(",
@@ -13718,7 +13751,9 @@ var isWordChar = (c) => !!c && /[\w$]/.test(c);
13718
13751
  var Bindings = class {
13719
13752
  constructor(code) {
13720
13753
  this.code = code;
13754
+ this.identifiers = /* @__PURE__ */ new Map();
13721
13755
  this.groups = [];
13756
+ this.groupIndexes = /* @__PURE__ */ new Map();
13722
13757
  this.byOpen = /* @__PURE__ */ new Map();
13723
13758
  this.byClose = /* @__PURE__ */ new Map();
13724
13759
  this.functions = /* @__PURE__ */ new Map();
@@ -13729,6 +13764,17 @@ var Bindings = class {
13729
13764
  end: Infinity
13730
13765
  };
13731
13766
  this.readGroups();
13767
+ for (const kind of [
13768
+ void 0,
13769
+ "{",
13770
+ "(",
13771
+ "["
13772
+ ]) this.groupIndexes.set(kind, new GroupIndex(kind === void 0 ? this.groups : this.groups.filter((g) => g.kind === kind)));
13773
+ for (const match of code.matchAll(/[\w$]+/g)) {
13774
+ const positions = this.identifiers.get(match[0]) ?? [];
13775
+ positions.push(match.index);
13776
+ this.identifiers.set(match[0], positions);
13777
+ }
13732
13778
  }
13733
13779
  /**
13734
13780
  * The `{` of the object literal that `name`, used at `at`, is declared as
@@ -13751,11 +13797,9 @@ var Bindings = class {
13751
13797
  }
13752
13798
  /** Declaration and write facts are immutable for this source and property set. */
13753
13799
  readBindings(name, properties) {
13754
- const { code } = this;
13755
- const escaped = escapeRegExp(name);
13756
13800
  const bindings = [];
13757
- for (const m of code.matchAll(new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`, "g"))) {
13758
- const binding = this.bindingAt(m.index, name.length, properties);
13801
+ for (const at of this.identifiers.get(name) ?? []) {
13802
+ const binding = this.bindingAt(at, name.length, properties);
13759
13803
  if (binding) bindings.push(binding);
13760
13804
  }
13761
13805
  const declarations = bindings.filter((b) => !b.write);
@@ -13807,11 +13851,7 @@ var Bindings = class {
13807
13851
  }
13808
13852
  /** The innermost group that has `index` inside it, of this kind if given. */
13809
13853
  innermost(index, kind) {
13810
- const { groups } = this;
13811
- for (let k = groups.length - 1; k >= 0; k--) {
13812
- const g = groups[k];
13813
- if (g.open < index && index < g.close && (!kind || g.kind === kind)) return g;
13814
- }
13854
+ return this.groupIndexes.get(kind).containing(index);
13815
13855
  }
13816
13856
  /**
13817
13857
  * The word before a `(` group (`if`, `for`, `catch`, a function's name…);
@@ -14141,7 +14181,12 @@ var Bindings = class {
14141
14181
  /** `Object.assign(x, …)` and the like: the name is the first argument. */
14142
14182
  isMutatedArgument(before, end) {
14143
14183
  const group = this.byOpen.get(before);
14144
- return group?.kind === "(" && ",)".includes(this.code.charAt(end)) && MUTATING_CALL_RE.test(this.code.slice(0, group.open));
14184
+ if (group?.kind !== "(" || !",)".includes(this.code.charAt(end))) return false;
14185
+ const method = this.wordBefore(this.backFrom(group.open) + 1);
14186
+ const dot = this.backFrom(method.start);
14187
+ if (this.code.charAt(dot) !== ".") return false;
14188
+ const owner = this.wordBefore(this.backFrom(dot) + 1);
14189
+ return MUTATING_CALL_RE.test(this.code.slice(owner.start, group.open));
14145
14190
  }
14146
14191
  };
14147
14192
  // src/macro-discovery.ts
@@ -26535,4 +26580,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
26535
26580
  const list = [...passages];
26536
26581
  return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
26537
26582
  }
26538
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, completionTarget, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, isSpecialPassage, lexJs, lexTemplate, macroArgumentSpans, macroCallAt, macroCalls, 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 };
26583
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, completionTarget, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, indexStrictCodeEnds, isBlockMacro, isSigil, isSpecialPassage, lexJs, lexTemplate, macroArgumentSpans, macroCallAt, macroCalls, 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 };
@@ -27,6 +27,7 @@ export {
27
27
  parseBoundVariable,
28
28
  effectiveWidgetDefinitions,
29
29
  findCodeEnd,
30
+ indexStrictCodeEnds,
30
31
  lexJs,
31
32
  lexTemplate,
32
33
  scanStringLiteral,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.64.29",
3
+ "version": "0.64.31",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,8 +1,9 @@
1
1
  import { actionAttributes, useControlAction } from '../../hooks/use-action';
2
2
  import { useState } from 'preact/hooks';
3
+ import { useSyncExternalStore } from 'preact/compat';
3
4
  import { useStoryStore } from '../../store';
4
5
  import { useStoryFields } from '../../hooks/use-story-fields';
5
- import { settings } from '../../settings';
6
+ import { settings, subscribeSettings } from '../../settings';
6
7
  import { quickLoad, quickSave } from '../../quick-actions';
7
8
  import { defineMacro } from '../../define-macro';
8
9
  import { PassageDialog } from '../PassageDialog';
@@ -15,7 +16,7 @@ interface MenubarActionConfig {
15
16
  actionType: ActionType;
16
17
  title?: string;
17
18
  confirm?: string;
18
- hidden?: () => boolean;
19
+ useHidden?: () => boolean;
19
20
  setup?: () => {
20
21
  perform: () => void | Promise<void>;
21
22
  disabled?: boolean;
@@ -34,62 +35,69 @@ function hotkeyTitle(label: string, key: string | null): string {
34
35
  }
35
36
 
36
37
  export function defineMenubarAction(config: MenubarActionConfig) {
38
+ // Visibility can change after mount. Keep the button's hooks and action
39
+ // registration in a child whose lifetime follows that visibility.
40
+ function Button({ className, id }: { className?: string; id?: string }) {
41
+ const [dialogOpen, setDialogOpen] = useState(false);
42
+
43
+ const setup = config.setup?.() ?? { perform: () => {} };
44
+ const { disabled, title = config.title } = setup;
45
+
46
+ const cls = className ? `menubar-button ${className}` : 'menubar-button';
47
+
48
+ const perform = config.dialog
49
+ ? () => setDialogOpen(true)
50
+ : config.confirm
51
+ ? () => {
52
+ if (confirm(config.confirm!)) setup.perform();
53
+ }
54
+ : setup.perform;
55
+
56
+ const action = useControlAction({
57
+ type: config.actionType,
58
+ key: config.name,
59
+ authorId: id,
60
+ label: typeof config.label === 'string' ? config.label : config.name,
61
+ disabled,
62
+ perform: config.dialog ? () => setDialogOpen(true) : setup.perform,
63
+ });
64
+
65
+ return (
66
+ <>
67
+ <button
68
+ type="button"
69
+ {...actionAttributes(action, { id, cls })}
70
+ onClick={perform}
71
+ disabled={disabled}
72
+ title={title}
73
+ >
74
+ {config.label}
75
+ </button>
76
+ {config.dialog && dialogOpen && (
77
+ <PassageDialog
78
+ passageName={config.dialog.passageName}
79
+ fallbackMarkup={config.dialog.fallbackMarkup}
80
+ panelClass={config.dialog.panelClass}
81
+ label={
82
+ typeof config.label === 'string' ? config.label : config.name
83
+ }
84
+ onClose={() => setDialogOpen(false)}
85
+ showCloseButton={config.dialog.showCloseButton}
86
+ />
87
+ )}
88
+ </>
89
+ );
90
+ }
91
+
37
92
  defineMacro({
38
93
  name: config.name,
39
94
  interpolate: true,
40
95
  render(_, ctx) {
41
- if (config.hidden?.()) return null;
42
-
43
- const [dialogOpen, setDialogOpen] = useState(false);
44
-
45
- const setup = config.setup?.() ?? { perform: () => {} };
46
- const { disabled, title = config.title } = setup;
47
-
48
- const cls = ctx.className
49
- ? `menubar-button ${ctx.className}`
50
- : 'menubar-button';
51
-
52
- const perform = config.dialog
53
- ? () => setDialogOpen(true)
54
- : config.confirm
55
- ? () => {
56
- if (confirm(config.confirm!)) setup.perform();
57
- }
58
- : setup.perform;
59
-
60
- const action = useControlAction({
61
- type: config.actionType,
62
- key: config.name,
63
- authorId: ctx.id,
64
- label: typeof config.label === 'string' ? config.label : config.name,
65
- disabled,
66
- perform: config.dialog ? () => setDialogOpen(true) : setup.perform,
67
- });
68
-
69
- return (
70
- <>
71
- <button
72
- type="button"
73
- {...actionAttributes(action, { id: ctx.id, cls })}
74
- onClick={perform}
75
- disabled={disabled}
76
- title={title}
77
- >
78
- {config.label}
79
- </button>
80
- {config.dialog && dialogOpen && (
81
- <PassageDialog
82
- passageName={config.dialog.passageName}
83
- fallbackMarkup={config.dialog.fallbackMarkup}
84
- panelClass={config.dialog.panelClass}
85
- label={
86
- typeof config.label === 'string' ? config.label : config.name
87
- }
88
- onClose={() => setDialogOpen(false)}
89
- showCloseButton={config.dialog.showCloseButton}
90
- />
91
- )}
92
- </>
96
+ return config.useHidden?.() ? null : (
97
+ <Button
98
+ className={ctx.className}
99
+ id={ctx.id}
100
+ />
93
101
  );
94
102
  },
95
103
  });
@@ -173,7 +181,7 @@ defineMenubarAction({
173
181
  name: 'settings',
174
182
  label: 'Settings',
175
183
  actionType: 'dialog',
176
- hidden: () => !settings.hasAny(),
184
+ useHidden: () => !useSyncExternalStore(subscribeSettings, settings.hasAny),
177
185
  dialog: {
178
186
  passageName: 'Settings',
179
187
  fallbackMarkup: '{settings-controls}',
@@ -15,6 +15,7 @@ import { Passage, renderPassageContent, type PassageProps } from '../Passage';
15
15
  import { defineMacro } from '../../define-macro';
16
16
  import { resolveTransition, type ResolvedTransition } from '../../transition';
17
17
  import { skipString } from './arg-utils';
18
+ import { InterfaceContext } from '../../markup/render';
18
19
 
19
20
  /** Input types whose `value` is not what the user sees or edits. */
20
21
  const VALUELESS_INPUTS = new Set([
@@ -1107,7 +1108,9 @@ defineMacro({
1107
1108
  key={`ready-${navigationId}`}
1108
1109
  hidden
1109
1110
  >
1110
- {renderPassageContent(readyPassage)}
1111
+ <InterfaceContext.Provider value={false}>
1112
+ {renderPassageContent(readyPassage)}
1113
+ </InterfaceContext.Provider>
1111
1114
  </div>
1112
1115
  )}
1113
1116
  <div
@@ -1,5 +1,11 @@
1
1
  import { useEffect, useId, useState } from 'preact/hooks';
2
- import { settings, subscribeSettings, type SettingDef } from '../../settings';
2
+ import { useSyncExternalStore } from 'preact/compat';
3
+ import {
4
+ settings,
5
+ subscribeSettings,
6
+ getSettingsRevision,
7
+ type SettingDef,
8
+ } from '../../settings';
3
9
  import { defineMacro } from '../../define-macro';
4
10
 
5
11
  function SettingRow({
@@ -117,6 +123,7 @@ function SettingsControlsContent({
117
123
  className?: string;
118
124
  id?: string;
119
125
  }) {
126
+ useSyncExternalStore(subscribeSettings, getSettingsRevision);
120
127
  const defs = settings.getDefinitions();
121
128
 
122
129
  return (
@@ -14,7 +14,7 @@ import {
14
14
  import { useInterpolate } from './hooks/use-interpolate';
15
15
  import {
16
16
  ItemEditContext,
17
- noteControlEdit,
17
+ runAsControlEdit,
18
18
  runAsItemEdit,
19
19
  } from './utils/control-edits';
20
20
  import { useMergedLocals } from './hooks/use-merged-locals';
@@ -254,13 +254,14 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
254
254
  ctx.setValue = displayOnly
255
255
  ? refuse
256
256
  : (value: unknown) => {
257
- noteControlEdit(segments);
258
257
  // The commit mutation code uses, which keeps the references among
259
258
  // variables: a write to a draft copies only the path written, and
260
259
  // other variables sharing the object would keep the old one.
261
- mutateState((work, adopt) => {
262
- setByPath(work.variables, segments, adopt(value), {
263
- createMissing: true,
260
+ runAsControlEdit(segments, () => {
261
+ mutateState((work, adopt) => {
262
+ setByPath(work.variables, segments, adopt(value), {
263
+ createMissing: true,
264
+ });
264
265
  });
265
266
  });
266
267
  };
@@ -28,6 +28,10 @@ const FOCUSABLE = [
28
28
  */
29
29
  function isAvailable(el: HTMLElement): boolean {
30
30
  if (!isRendered(el)) return false;
31
+ // Boxless containers can render focusable children, but cannot take focus
32
+ // themselves. Keep traversing their descendants in focusables().
33
+ const view = el.ownerDocument.defaultView ?? window;
34
+ if (view.getComputedStyle(el).display === 'contents') return false;
31
35
  // Rendered visibility includes CSS overrides of hidden, until-found
32
36
  // contents, closed details and shadow trees. Inertness is independent.
33
37
  for (let at: Element | null = el; at; at = composedParent(at)) {
@@ -9,7 +9,6 @@
9
9
  * cannot place, it counts as a declaration of unknown value: a parameter, a
10
10
  * pattern, an assignment. Better no answer than another declaration's.
11
11
  */
12
- import { escapeRegExp } from './components/macros/arg-utils';
13
12
 
14
13
  type Kind = '{' | '(' | '[';
15
14
 
@@ -21,6 +20,44 @@ interface Group {
21
20
  parent: Group | undefined;
22
21
  }
23
22
 
23
+ /** Search arbitrary (also recovered, overlapping) bracket intervals. */
24
+ class GroupIndex {
25
+ private readonly size: number;
26
+ private readonly ends: number[];
27
+
28
+ constructor(private readonly groups: readonly Group[]) {
29
+ let size = 1;
30
+ while (size < groups.length) size *= 2;
31
+ this.size = size;
32
+ this.ends = new Array<number>(size * 2).fill(-1);
33
+ for (let i = 0; i < groups.length; i++)
34
+ this.ends[size + i] = groups[i]!.close;
35
+ for (let i = size - 1; i > 0; i--) {
36
+ this.ends[i] = Math.max(this.ends[i * 2]!, this.ends[i * 2 + 1]!);
37
+ }
38
+ }
39
+
40
+ /** Latest opener before `at` whose closer follows it, in logarithmic time. */
41
+ containing(at: number): Group | undefined {
42
+ const find = (
43
+ node: number,
44
+ start: number,
45
+ end: number,
46
+ ): Group | undefined => {
47
+ if (
48
+ start >= this.groups.length ||
49
+ this.groups[start]!.open >= at ||
50
+ this.ends[node]! <= at
51
+ )
52
+ return undefined;
53
+ if (end - start === 1) return this.groups[start];
54
+ const mid = (start + end) >>> 1;
55
+ return find(node * 2 + 1, mid, end) ?? find(node * 2, start, mid);
56
+ };
57
+ return find(1, 0, this.size);
58
+ }
59
+ }
60
+
24
61
  /** The text a name is visible in: `[start, end)`. */
25
62
  interface Scope {
26
63
  start: number;
@@ -75,7 +112,9 @@ const isWordChar = (c: string | undefined) => !!c && /[\w$]/.test(c);
75
112
 
76
113
  /** Resolve the declaration of variables in `code` (see blankedCode in macro-discovery). */
77
114
  export class Bindings {
115
+ private readonly identifiers = new Map<string, number[]>();
78
116
  private readonly groups: Group[] = [];
117
+ private readonly groupIndexes = new Map<Kind | undefined, GroupIndex>();
79
118
  private readonly byOpen = new Map<number, Group>();
80
119
  private readonly byClose = new Map<number, Group>();
81
120
  private readonly functions = new Map<Group, boolean>();
@@ -88,6 +127,23 @@ export class Bindings {
88
127
 
89
128
  constructor(private readonly code: string) {
90
129
  this.readGroups();
130
+ for (const kind of [undefined, '{', '(', '['] as const) {
131
+ this.groupIndexes.set(
132
+ kind,
133
+ new GroupIndex(
134
+ kind === undefined
135
+ ? this.groups
136
+ : this.groups.filter((g) => g.kind === kind),
137
+ ),
138
+ );
139
+ }
140
+ // One source scan serves every config name, including distinct names.
141
+ // Keep the same word boundaries as the binding reader (also for `$`).
142
+ for (const match of code.matchAll(/[\w$]+/g)) {
143
+ const positions = this.identifiers.get(match[0]) ?? [];
144
+ positions.push(match.index);
145
+ this.identifiers.set(match[0], positions);
146
+ }
91
147
  }
92
148
 
93
149
  /**
@@ -119,13 +175,9 @@ export class Bindings {
119
175
  name: string,
120
176
  properties: ReadonlySet<string>,
121
177
  ): Binding[] {
122
- const { code } = this;
123
- const escaped = escapeRegExp(name);
124
178
  const bindings: Binding[] = [];
125
- for (const m of code.matchAll(
126
- new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`, 'g'),
127
- )) {
128
- const binding = this.bindingAt(m.index, name.length, properties);
179
+ for (const at of this.identifiers.get(name) ?? []) {
180
+ const binding = this.bindingAt(at, name.length, properties);
129
181
  if (binding) bindings.push(binding);
130
182
  }
131
183
  // A write is to the declaration it sees: in the scope of that one
@@ -194,14 +246,7 @@ export class Bindings {
194
246
 
195
247
  /** The innermost group that has `index` inside it, of this kind if given. */
196
248
  private innermost(index: number, kind?: Kind): Group | undefined {
197
- const { groups } = this;
198
- for (let k = groups.length - 1; k >= 0; k--) {
199
- const g = groups[k]!;
200
- if (g.open < index && index < g.close && (!kind || g.kind === kind)) {
201
- return g;
202
- }
203
- }
204
- return undefined;
249
+ return this.groupIndexes.get(kind)!.containing(index);
205
250
  }
206
251
 
207
252
  /**
@@ -618,10 +663,13 @@ export class Bindings {
618
663
  /** `Object.assign(x, …)` and the like: the name is the first argument. */
619
664
  private isMutatedArgument(before: number, end: number): boolean {
620
665
  const group = this.byOpen.get(before);
621
- return (
622
- group?.kind === '(' &&
623
- ',)'.includes(this.code.charAt(end)) &&
624
- MUTATING_CALL_RE.test(this.code.slice(0, group.open))
625
- );
666
+ if (group?.kind !== '(' || !',)'.includes(this.code.charAt(end)))
667
+ return false;
668
+ // The regexp only needs the callee, not every preceding statement.
669
+ const method = this.wordBefore(this.backFrom(group.open) + 1);
670
+ const dot = this.backFrom(method.start);
671
+ if (this.code.charAt(dot) !== '.') return false;
672
+ const owner = this.wordBefore(this.backFrom(dot) + 1);
673
+ return MUTATING_CALL_RE.test(this.code.slice(owner.start, group.open));
626
674
  }
627
675
  }