@rohal12/spindle 0.62.2 → 0.62.3

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.
@@ -471,18 +471,33 @@ export class Reader {
471
471
 
472
472
  /** Skip an array literal (or any bracketed group) at the cursor. */
473
473
  protected skipBalanced(): boolean {
474
+ const close = { '[': ']', '{': '}', '(': ')' }[this.src.charAt(this.i)];
475
+ return close ? this.skipNested(close) : false;
476
+ }
477
+
478
+ /** Skip groups and template interpolations with an explicit stack. */
479
+ private skipNested(close: string): boolean {
474
480
  const { src } = this;
475
- const close = { '[': ']', '{': '}', '(': ')' }[src.charAt(this.i)];
476
- if (!close) return false;
481
+ const stack = [close];
477
482
  this.i++;
478
- while (this.i < src.length) {
479
- if (src.charAt(this.i) === close) {
483
+ while (this.i < src.length && stack.length) {
484
+ const c = src.charAt(this.i);
485
+ const top = stack[stack.length - 1];
486
+ if (c === top) {
487
+ stack.pop();
480
488
  this.i++;
481
- return true;
482
- }
483
- if (!this.skipOne()) return false;
489
+ } else if (top === '`') {
490
+ if (c === '\\') this.i += 2;
491
+ else if (c === '$' && src.charAt(this.i + 1) === '{') {
492
+ stack.push('}');
493
+ this.i += 2;
494
+ } else this.i++;
495
+ } else if (c === '`' || c === '[' || c === '{' || c === '(') {
496
+ stack.push(c === '`' ? '`' : { '[': ']', '{': '}', '(': ')' }[c]!);
497
+ this.i++;
498
+ } else if (!this.skipOne()) return false;
484
499
  }
485
- return false;
500
+ return stack.length === 0;
486
501
  }
487
502
 
488
503
  /** Skip one character, or one string, template, comment or group. */
@@ -512,19 +527,6 @@ export class Reader {
512
527
 
513
528
  /** Skip a template literal, with the expressions in it. */
514
529
  protected skipTemplate(): boolean {
515
- const { src } = this;
516
- this.i++;
517
- while (this.i < src.length) {
518
- const c = src.charAt(this.i);
519
- if (c === '\\') this.i += 2;
520
- else if (c === '`') {
521
- this.i++;
522
- return true;
523
- } else if (c === '$' && src.charAt(this.i + 1) === '{') {
524
- this.i++;
525
- if (!this.skipBalanced()) return false;
526
- } else this.i++;
527
- }
528
- return false;
530
+ return this.skipNested('`');
529
531
  }
530
532
  }
package/src/store.ts CHANGED
@@ -26,6 +26,8 @@ import {
26
26
  assertTrustedWatchers,
27
27
  interfaceMounted,
28
28
  savedMacroWatchers,
29
+ savedReplayWatchers,
30
+ clearReplayWatchers,
29
31
  reinitTriggerState,
30
32
  } from './triggers';
31
33
  import {
@@ -206,6 +208,7 @@ function applyVarPatches(
206
208
  vars: Record<string, unknown>,
207
209
  changes: readonly VarChange[],
208
210
  ): Record<string, unknown> {
211
+ if (changes.length === 0) return vars;
209
212
  const next = Object.create(
210
213
  Object.getPrototypeOf(vars) as object | null,
211
214
  ) as Record<string, unknown>;
@@ -324,6 +327,7 @@ function persistSession(get: () => StoryState): { error: unknown } | undefined {
324
327
  renderCounts,
325
328
  prng: snapshotPRNG(),
326
329
  watchers: savedMacroWatchers(),
330
+ replayWatchers: savedReplayWatchers(),
327
331
  interfaceWatchers: interfaceMounted(),
328
332
  });
329
333
  }
@@ -422,6 +426,9 @@ function finishEnteredMoment(get: StoreGet, set: StoreSet): void {
422
426
  const moment = enteredMoment;
423
427
  enteredMoment = null;
424
428
  if (!moment || get().navigationId !== moment.navigationId) return;
429
+ // Navigation can run inside a macro's render. Its watcher effects are
430
+ // recorded below, so they must not also be replayed as passage effects.
431
+ clearReplayWatchers();
425
432
  if (get().variables !== moment.variables) {
426
433
  rerecordNewestMoment(get().variables);
427
434
  }
@@ -558,6 +565,7 @@ export function recordStoryInitState(): void {
558
565
  if (history.length !== 1 || historyIndex !== 0) return;
559
566
 
560
567
  resetModuleState(variables);
568
+ clearReplayWatchers();
561
569
 
562
570
  const prng = snapshotPRNG();
563
571
  useStoryStore.setState((state) => {
@@ -1817,6 +1825,7 @@ export const useStoryStore = create<StoryState>()(
1817
1825
  renderCounts: { ...renderCounts },
1818
1826
  prng: snapshotPRNG(),
1819
1827
  watchers: savedMacroWatchers(),
1828
+ replayWatchers: savedReplayWatchers(),
1820
1829
  interfaceWatchers: interfaceMounted(),
1821
1830
  };
1822
1831
  },
@@ -1860,6 +1869,7 @@ export const useStoryStore = create<StoryState>()(
1860
1869
  // running game as it is
1861
1870
  assertPassagesExist(get().storyData, payload);
1862
1871
  assertTrustedWatchers(payload.watchers ?? []);
1872
+ assertTrustedWatchers(payload.replayWatchers ?? []);
1863
1873
  applyReplacement(replacement);
1864
1874
 
1865
1875
  leavingPlaythrough = leaving;
@@ -1893,18 +1903,36 @@ export const useStoryStore = create<StoryState>()(
1893
1903
  // Convert full snapshots to patch entries. They are copied in one
1894
1904
  // piece, so values the moments share stay shared, and a transition's
1895
1905
  // patches hold only the variables that changed.
1896
- const snapshots = deepClone(payload.history.map((m) => m.variables)).map(
1897
- (vars) => createNamespace(vars),
1906
+ const index = Math.max(
1907
+ 0,
1908
+ Math.min(payload.historyIndex, payload.history.length - 1),
1909
+ );
1910
+ const start = Math.min(
1911
+ index,
1912
+ Math.max(0, payload.history.length - get().maxHistory),
1913
+ );
1914
+ const retained = payload.history.slice(start, start + get().maxHistory);
1915
+ const namespaces = new Map<Record<string, unknown>, Namespace>();
1916
+ const snapshots = deepClone(retained.map((m) => m.variables)).map(
1917
+ (vars) => {
1918
+ let normalized = namespaces.get(vars);
1919
+ if (!normalized) {
1920
+ normalized = createNamespace(vars);
1921
+ namespaces.set(vars, normalized);
1922
+ }
1923
+ return normalized;
1924
+ },
1898
1925
  );
1899
1926
  variableBase = deepClone(snapshots[0]!);
1900
1927
  patchEntries = snapshots
1901
1928
  .slice(1)
1902
- .map((curr, i) => computeVarPatches(snapshots[i]!, curr));
1903
- // Seed the session cache from the payload's own snapshots, so
1904
- // persistSession does not rebuild them from the live variables.
1905
- sessionMoments = payload.history.map((m, i) =>
1906
- savedMoment(m, snapshots[i]!),
1907
- );
1929
+ .map((curr, i) =>
1930
+ curr === snapshots[i]
1931
+ ? { forward: [] }
1932
+ : computeVarPatches(snapshots[i]!, curr),
1933
+ );
1934
+ // Seed only retained moments; repeated namespaces stay shared.
1935
+ sessionMoments = retained.map((m, i) => savedMoment(m, snapshots[i]!));
1908
1936
 
1909
1937
  set((state) => {
1910
1938
  state.currentPassage = payload.passage;
@@ -1912,17 +1940,12 @@ export const useStoryStore = create<StoryState>()(
1912
1940
  state.variables = createNamespace(
1913
1941
  deepClone(entry?.variables ?? payload.variables),
1914
1942
  );
1915
- state.history = payload.history.map((m) => ({
1943
+ state.history = retained.map((m) => ({
1916
1944
  passage: m.passage,
1917
1945
  timestamp: m.timestamp,
1918
1946
  prng: m.prng,
1919
1947
  }));
1920
- state.historyIndex = Math.max(
1921
- 0,
1922
- Math.min(payload.historyIndex, state.history.length - 1),
1923
- );
1924
- // A save made under a higher limit keeps no more than the limit
1925
- trimHistory(state);
1948
+ state.historyIndex = index - start;
1926
1949
  state.visitCounts = createCounts(payload.visitCounts);
1927
1950
  state.renderCounts = createCounts(payload.renderCounts);
1928
1951
  state.temporary = createNamespace();
@@ -1933,7 +1956,10 @@ export const useStoryStore = create<StoryState>()(
1933
1956
  // older version, leaves the registered ones), then: loaded state is
1934
1957
  // not a change watchers react to
1935
1958
  if (payload.watchers) {
1936
- restoreMacroWatchers(payload.watchers, payload.interfaceWatchers);
1959
+ restoreMacroWatchers(
1960
+ payload.replayWatchers ?? payload.watchers,
1961
+ payload.interfaceWatchers,
1962
+ );
1937
1963
  }
1938
1964
  reinitTriggerState();
1939
1965
 
package/src/tooling.ts CHANGED
@@ -1,3 +1,7 @@
1
+ export {
2
+ completionContext,
3
+ type CompletionContext,
4
+ } from './completion-context';
1
5
  import { branchParents } from './registry';
2
6
  /**
3
7
  * What the tooling entry point (`@rohal12/spindle/tooling`) bundles as
package/src/triggers.ts CHANGED
@@ -5,6 +5,7 @@ import type { StoryData } from './parser';
5
5
  import { evaluate } from './expression';
6
6
  import { executeMutation, readState } from './execute-mutation';
7
7
  import { useStoryStore } from './store';
8
+ import { getRenderedNavigationId } from './passage-render-state';
8
9
  import { createListeners } from './utils/listeners';
9
10
 
10
11
  export interface WatchOptions {
@@ -23,7 +24,10 @@ export interface QueuedDialog {
23
24
  dismissible?: boolean;
24
25
  }
25
26
 
27
+ let registrations = 0;
28
+
26
29
  interface Trigger {
30
+ order: number;
27
31
  name?: string;
28
32
  condition: string;
29
33
  callback?: () => void;
@@ -75,6 +79,7 @@ function registerTrigger(
75
79
  const callback = isCallback ? callbackOrOptions : undefined;
76
80
 
77
81
  const trigger: Trigger = {
82
+ order: registrations++,
78
83
  name: options?.name,
79
84
  condition,
80
85
  callback,
@@ -125,6 +130,97 @@ export interface SavedWatcher {
125
130
  options: WatchOptions;
126
131
  }
127
132
 
133
+ // A passage replays its entry variables on load. Watchers removed by its
134
+ // initial render must replay too; removals after player actions stay removed.
135
+ let macroRenderDepth = 0;
136
+ let entryRenderDepth = 0;
137
+ let replayNavigation = -1;
138
+ const replayRemoved = new Map<
139
+ string,
140
+ { watcher: SavedWatcher; order: number }
141
+ >();
142
+
143
+ /** Entry lifecycle callbacks and deferred initial passage subtrees replay on load. */
144
+ export function duringEntryRender<T>(render: () => T): T {
145
+ entryRenderDepth++;
146
+ try {
147
+ return render();
148
+ } finally {
149
+ entryRenderDepth--;
150
+ }
151
+ }
152
+
153
+ function isEntryRender(): boolean {
154
+ return (
155
+ entryRenderDepth > 0 ||
156
+ (macroRenderDepth > 0 &&
157
+ getRenderedNavigationId() !== useStoryStore.getState().navigationId)
158
+ );
159
+ }
160
+
161
+ export function duringMacroRender<T>(render: () => T): T {
162
+ macroRenderDepth++;
163
+ try {
164
+ return render();
165
+ } finally {
166
+ macroRenderDepth--;
167
+ }
168
+ }
169
+
170
+ /** Forget replay removals whose effects have become part of a recorded entry. */
171
+ export function clearReplayWatchers(): void {
172
+ replayRemoved.clear();
173
+ }
174
+
175
+ function replayRemovals() {
176
+ const navigation = useStoryStore.getState().navigationId;
177
+ if (navigation !== replayNavigation) {
178
+ replayRemoved.clear();
179
+ replayNavigation = navigation;
180
+ }
181
+ return replayRemoved;
182
+ }
183
+
184
+ function rememberRemoval(trigger: Trigger): void {
185
+ const removed = replayRemovals();
186
+ if (!trigger.macroKey || !trigger.options) return;
187
+ if (isEntryRender()) {
188
+ // A once watcher may be re-declared and consumed again in this entry.
189
+ // Replay begins with its first registration, before surviving peers.
190
+ if (removed.has(trigger.macroKey)) return;
191
+ removed.set(trigger.macroKey, {
192
+ watcher: {
193
+ condition: trigger.condition,
194
+ options: { ...trigger.options },
195
+ },
196
+ order: trigger.order,
197
+ });
198
+ } else {
199
+ removed.delete(trigger.macroKey);
200
+ }
201
+ }
202
+
203
+ /** Entry-render removals plus still active watchers, absent when none need replay. */
204
+ export function savedReplayWatchers(): SavedWatcher[] | undefined {
205
+ const removed = replayRemovals();
206
+ if (!removed.size) return undefined;
207
+ const all = new Map(removed);
208
+ for (const trigger of triggers) {
209
+ if (!trigger.macroKey || !trigger.options || all.has(trigger.macroKey))
210
+ continue;
211
+ all.set(trigger.macroKey, {
212
+ watcher: {
213
+ condition: trigger.condition,
214
+ options: { ...trigger.options },
215
+ },
216
+ order: trigger.order,
217
+ });
218
+ }
219
+ return [...all.values()]
220
+ .sort((a, b) => a.order - b.order)
221
+ .map(({ watcher }) => watcher);
222
+ }
223
+
128
224
  /** Canonical identity includes every option, so an imported action cannot change it. */
129
225
  function watcherKey(condition: string, options: WatchOptions): string {
130
226
  const sorted = Object.fromEntries(
@@ -251,6 +347,15 @@ export function restoreMacroWatchers(
251
347
  }
252
348
 
253
349
  export function removeTrigger(name: string): void {
350
+ for (const trigger of triggers) {
351
+ if (trigger.name === name) rememberRemoval(trigger);
352
+ }
353
+ // An explicit later unwatch also removes a consumed entry watcher.
354
+ if (!isEntryRender()) {
355
+ for (const [key, { watcher }] of replayRemovals()) {
356
+ if (watcher.options.name === name) replayRemoved.delete(key);
357
+ }
358
+ }
254
359
  triggers = triggers.filter((t) => t.name !== name);
255
360
  }
256
361
 
@@ -310,6 +415,7 @@ function runCheckLoop(): void {
310
415
  anyFired = true;
311
416
 
312
417
  if (trigger.options?.once) {
418
+ rememberRemoval(trigger);
313
419
  triggers = triggers.filter((t) => t !== trigger);
314
420
  }
315
421
 
@@ -406,6 +512,7 @@ export function reinitTriggerState(): void {
406
512
  */
407
513
  export function resetTriggers(): void {
408
514
  triggers = [];
515
+ replayRemoved.clear();
409
516
  resets++;
410
517
  closeAllOpenDialogs();
411
518
  resetListeners.notify();
@@ -1,4 +1,4 @@
1
- import { collectStoryPassageReferences } from '../tooling';
1
+ import { passagePiecesOfTokens } from '../tooling';
2
2
  import { tokenizeMarkupTolerant } from '../markup/parse';
3
3
  import { builtinMacros } from './builtin-macros';
4
4
 
@@ -13,19 +13,17 @@ export function parsePassageText(text: string): string[] {
13
13
  try {
14
14
  // Both `[[…]]` and `{link}` report `macro: 'link'`; only the link token
15
15
  // tells them apart.
16
- const links = tokenizeMarkupTolerant(text).tokens.filter(
17
- (token) => token.type === 'link',
16
+ const tokens = tokenizeMarkupTolerant(text).tokens;
17
+ const bracketTargets = new Set(
18
+ tokens
19
+ .filter((token) => token.type === 'link')
20
+ .map((link) => link.targetStart),
18
21
  );
19
22
  const names = new Set<string>();
20
- for (const ref of collectStoryPassageReferences(text, builtinMacros)) {
21
- if (ref.target.kind !== 'name') continue;
22
- if (
23
- links.some(
24
- (link) => ref.start >= link.targetStart && ref.start < link.targetEnd,
25
- )
26
- )
23
+ for (const piece of passagePiecesOfTokens(text, builtinMacros, tokens)) {
24
+ if (piece.kind !== 'passage' || bracketTargets.has(piece.offset))
27
25
  continue;
28
- names.add(ref.target.name);
26
+ names.add(piece.name);
29
27
  }
30
28
  return [...names];
31
29
  } catch {
@@ -1,7 +1,7 @@
1
1
  import type { ASTNode } from '../markup/ast';
2
2
  import type { Token } from '../markup/tokens';
3
3
  import { codeAndText, parameterLookup, type ParametersOf } from '../code-check';
4
- import { parseMarkup } from '../markup/parse';
4
+ import { parseMarkup, type MarkupHooks } from '../markup/parse';
5
5
  import { getMacroRegistry } from '../registry';
6
6
 
7
7
  /** The declared parameters of the macros registered so far. */
@@ -15,16 +15,17 @@ export const registeredParameters: ParametersOf = (name) =>
15
15
  function textContainsChildren(
16
16
  text: string,
17
17
  parametersOf: ParametersOf,
18
+ hooks?: Partial<MarkupHooks>,
18
19
  ): boolean {
19
20
  if (!text.includes('{')) return false;
20
21
  let nodes: ASTNode[];
21
22
  try {
22
- nodes = parseMarkup(text, { text: true });
23
+ nodes = parseMarkup(text, { text: true, hooks });
23
24
  } catch {
24
25
  // The renderer reports the markup that does not parse
25
26
  return false;
26
27
  }
27
- return astContainsChildren(nodes, parametersOf);
28
+ return astContainsChildren(nodes, parametersOf, hooks);
28
29
  }
29
30
 
30
31
  /**
@@ -32,17 +33,19 @@ function textContainsChildren(
32
33
  * argument that holds markup (`<span title="{@children}">`,
33
34
  * `{button "{@children}"}`). Literal arguments and code are not markup.
34
35
  * `src` is the text a flat token's offsets index into (its attribute values
35
- * are read from it); a token made from an AST has none.
36
+ * are read from it); a token made from an AST has none. Discovery hooks
37
+ * also apply inside these texts, before widgets have been registered.
36
38
  */
37
39
  export function tokenTextContainsChildren(
38
40
  token: Token,
39
41
  parametersOf: ParametersOf = registeredParameters,
40
42
  src = '',
43
+ hooks?: Partial<MarkupHooks>,
41
44
  ): boolean {
42
45
  for (const piece of codeAndText(src, [token], parametersOf)) {
43
46
  if (
44
47
  piece.kind === 'text' &&
45
- textContainsChildren(piece.text, parametersOf)
48
+ textContainsChildren(piece.text, parametersOf, hooks)
46
49
  ) {
47
50
  return true;
48
51
  }
@@ -60,6 +63,7 @@ export function tokenTextContainsChildren(
60
63
  export function astContainsChildren(
61
64
  nodes: ASTNode[],
62
65
  parametersOf: ParametersOf = registeredParameters,
66
+ hooks?: Partial<MarkupHooks>,
63
67
  ): boolean {
64
68
  for (const node of nodes) {
65
69
  if (
@@ -69,46 +73,38 @@ export function astContainsChildren(
69
73
  ) {
70
74
  return true;
71
75
  }
72
- if (node.type === 'html') {
73
- // A token in name only: the scan reads its attribute values
74
- const tag: Token = {
75
- isClose: false,
76
- isSelfClose: false,
77
- tagNameStart: 0,
78
- tagNameEnd: 0,
79
- attributeSpans: [],
80
- ...node,
81
- start: 0,
82
- end: 0,
83
- };
84
- if (
85
- tokenTextContainsChildren(tag, parametersOf) ||
86
- astContainsChildren(node.children, parametersOf)
87
- ) {
88
- return true;
89
- }
76
+ if (node.type !== 'html' && node.type !== 'macro') continue;
77
+ if (node.type === 'macro' && node.name.toLowerCase() === 'widget') continue;
78
+ // A token in name only: the scan reads its label or attribute values.
79
+ const span = { isClose: false, start: 0, end: 0 };
80
+ const tag: Token =
81
+ node.type === 'html'
82
+ ? {
83
+ ...node,
84
+ ...span,
85
+ isSelfClose: false,
86
+ tagNameStart: 0,
87
+ tagNameEnd: 0,
88
+ attributeSpans: [],
89
+ }
90
+ : {
91
+ ...node,
92
+ ...span,
93
+ nameStart: 0,
94
+ nameEnd: 0,
95
+ argsStart: 0,
96
+ argsEnd: 0,
97
+ };
98
+ if (
99
+ tokenTextContainsChildren(tag, parametersOf, '', hooks) ||
100
+ astContainsChildren(node.children, parametersOf, hooks)
101
+ ) {
102
+ return true;
90
103
  }
91
- if (node.type === 'macro') {
92
- if (node.name.toLowerCase() === 'widget') continue;
93
- const tag: Token = {
94
- isClose: false,
95
- nameStart: 0,
96
- nameEnd: 0,
97
- argsStart: 0,
98
- argsEnd: 0,
99
- ...node,
100
- start: 0,
101
- end: 0,
102
- };
103
- if (
104
- tokenTextContainsChildren(tag, parametersOf) ||
105
- astContainsChildren(node.children, parametersOf)
106
- ) {
107
- return true;
108
- }
109
- if (node.branches) {
110
- for (const branch of node.branches) {
111
- if (astContainsChildren(branch.children, parametersOf)) return true;
104
+ if (node.type === 'macro' && node.branches) {
105
+ for (const branch of node.branches) {
106
+ if (astContainsChildren(branch.children, parametersOf, hooks)) {
107
+ return true;
112
108
  }
113
109
  }
114
110
  }
@@ -5,6 +5,7 @@
5
5
  import { parseMacroArgs, type ArgSpans } from '../components/macros/macro-args';
6
6
  import { STRING_HOLDS, type MacroArgs, type StringHolds } from '../registry';
7
7
  import { tokenizeMarkupTolerant } from '../markup/parse';
8
+ import { isRawMacro } from '../markup/ast';
8
9
  import type { MacroToken } from '../markup/tokens';
9
10
  import type { ParametersOf } from '../code-check';
10
11
  import { NameMap } from '../utils/macro-names';
@@ -131,55 +132,83 @@ export function widgetDefinitions(
131
132
  passages: Iterable<WidgetPassage>,
132
133
  parametersOf: ParametersOf = registeredParameters,
133
134
  ): WidgetDefinition[] {
134
- const found: WidgetDefinition[] = [];
135
- for (const passage of passages) {
136
- if (passage.name !== 'StoryInit' && !passage.tags?.includes('widget')) {
137
- continue;
138
- }
139
- // The open definitions: their tags, and whether a slot was seen
140
- const open: { token: MacroToken; isBlock: boolean; closeStart?: number }[] =
141
- [];
142
- const done: typeof open = [];
143
- for (const token of tokenizeMarkupTolerant(passage.content).tokens) {
144
- if (token.type === 'macro' && token.name.toLowerCase() === 'widget') {
145
- if (!token.isClose) {
146
- open.push({ token, isBlock: false });
147
- } else {
148
- const def = open.pop();
149
- if (def) done.push({ ...def, closeStart: token.start });
135
+ const list = [...passages];
136
+ const scan = (replacesDo: boolean): WidgetDefinition[] => {
137
+ const found: WidgetDefinition[] = [];
138
+ const hooks = {
139
+ isRaw: (name: string) =>
140
+ isRawMacro(
141
+ name,
142
+ replacesDo || parametersOf.widget?.(name) !== undefined,
143
+ ),
144
+ };
145
+ for (const passage of list) {
146
+ if (passage.name !== 'StoryInit' && !passage.tags?.includes('widget')) {
147
+ continue;
148
+ }
149
+ // The open definitions: their tags, and whether a slot was seen
150
+ const open: {
151
+ token: MacroToken;
152
+ isBlock: boolean;
153
+ closeStart?: number;
154
+ }[] = [];
155
+ const done: typeof open = [];
156
+ for (const token of tokenizeMarkupTolerant(passage.content, { hooks })
157
+ .tokens) {
158
+ if (token.type === 'macro' && token.name.toLowerCase() === 'widget') {
159
+ if (!token.isClose) {
160
+ open.push({ token, isBlock: false });
161
+ } else {
162
+ const def = open.pop();
163
+ if (def) done.push({ ...def, closeStart: token.start });
164
+ }
165
+ } else if (
166
+ open.length > 0 &&
167
+ ((token.type === 'variable' &&
168
+ token.scope === 'local' &&
169
+ token.name === 'children') ||
170
+ tokenTextContainsChildren(
171
+ token,
172
+ parametersOf,
173
+ passage.content,
174
+ hooks,
175
+ ))
176
+ ) {
177
+ open[open.length - 1]!.isBlock = true;
150
178
  }
151
- } else if (
152
- open.length > 0 &&
153
- ((token.type === 'variable' &&
154
- token.scope === 'local' &&
155
- token.name === 'children') ||
156
- tokenTextContainsChildren(token, parametersOf, passage.content))
157
- ) {
158
- open[open.length - 1]!.isBlock = true;
159
179
  }
160
- }
161
- done.push(...open);
162
- const defs: WidgetDefinition[] = [];
163
- for (const { token, isBlock, closeStart } of done) {
164
- try {
165
- const [from, to] = nameSpan(token.rawArgs);
166
- defs.push({
167
- ...parseWidgetDef(token.rawArgs),
168
- block: isBlock,
169
- passage: passage.name,
170
- start: token.start,
171
- end: token.end,
172
- nameStart: token.argsStart + from,
173
- nameEnd: token.argsStart + to,
174
- ...(closeStart === undefined ? {} : { closeStart }),
175
- });
176
- } catch {
177
- // The {widget} macro reports a definition it cannot read
180
+ done.push(...open);
181
+ const defs: WidgetDefinition[] = [];
182
+ for (const { token, isBlock, closeStart } of done) {
183
+ try {
184
+ const [from, to] = nameSpan(token.rawArgs);
185
+ defs.push({
186
+ ...parseWidgetDef(token.rawArgs),
187
+ block: isBlock,
188
+ passage: passage.name,
189
+ start: token.start,
190
+ end: token.end,
191
+ nameStart: token.argsStart + from,
192
+ nameEnd: token.argsStart + to,
193
+ ...(closeStart === undefined ? {} : { closeStart }),
194
+ });
195
+ } catch {
196
+ // The {widget} macro reports a definition it cannot read
197
+ }
178
198
  }
199
+ found.push(...defs.sort((a, b) => a.start - b.start));
179
200
  }
180
- found.push(...defs.sort((a, b) => a.start - b.start));
181
- }
182
- return found;
201
+ return found;
202
+ };
203
+ const initial = scan(false);
204
+ // Discover definitions with real raw bodies first, so JavaScript strings
205
+ // that merely mention a widget cannot replace the built-in do. Once a
206
+ // closed do widget is known, its body and its callers are markup.
207
+ return effectiveWidgetDefinitions(initial).some(
208
+ (def) => def.name.toLowerCase() === 'do',
209
+ )
210
+ ? scan(true)
211
+ : initial;
183
212
  }
184
213
 
185
214
  /**