@rohal12/spindle 0.62.9 → 0.63.0

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.
@@ -168,9 +168,14 @@ export function observe(): Observation {
168
168
  passage,
169
169
  text: body ? observableText(body, DIALOG) : '',
170
170
  }));
171
- const errors = [passageEl, ...bodies.map((d) => d.body), contextEl].flatMap(
172
- (el) =>
173
- el ? observableErrors(el, DIALOG, el === contextEl ? el : undefined) : [],
171
+ // The persistent interface can show errors outside the passage. Scan its
172
+ // shared root once, then read dialogs and the hidden StoryContext separately.
173
+ const errors = [
174
+ document.getElementById('root') ?? passageEl,
175
+ ...bodies.map((d) => d.body),
176
+ contextEl,
177
+ ].flatMap((el) =>
178
+ el ? observableErrors(el, DIALOG, el === contextEl ? el : undefined) : [],
174
179
  );
175
180
  // The runtime errors shown (as banners) until dismissed, with what failed
176
181
  for (const { context, message } of getRuntimeErrors()) {
@@ -0,0 +1,19 @@
1
+ /** Runtime-owned passage roles, shared with stateless authoring tools. */
2
+ const SPECIAL_PASSAGES = new Set([
3
+ 'StoryInit',
4
+ 'StoryInterface',
5
+ 'StoryVariables',
6
+ 'StoryTransients',
7
+ 'StoryLoading',
8
+ 'SaveTitle',
9
+ 'PassageReady',
10
+ 'PassageHeader',
11
+ 'PassageFooter',
12
+ 'PassageDone',
13
+ 'StoryContext',
14
+ ]);
15
+
16
+ /** Whether `name` is a special passage, which navigation never goes to. */
17
+ export function isSpecialPassage(name: string): boolean {
18
+ return SPECIAL_PASSAGES.has(name);
19
+ }
package/src/store.ts CHANGED
@@ -64,7 +64,7 @@ import {
64
64
  underChange,
65
65
  type PathChange,
66
66
  } from './structural';
67
- import { getByPath } from './utils/object-path';
67
+ import { getByPath, setByPath } from './utils/object-path';
68
68
  import { isIndexKey } from './utils/value-kinds';
69
69
  import {
70
70
  noPassageError,
@@ -95,31 +95,14 @@ import {
95
95
  type Counts,
96
96
  type Namespace,
97
97
  } from './utils/namespace';
98
+ import { isSpecialPassage } from './passage-roles';
99
+ export { isSpecialPassage } from './passage-roles';
98
100
 
99
101
  enablePatches();
100
102
  // Story state holds Map and Set values: Immer must be able to draft them
101
103
  // when a write (a dot path, a macro binding) reaches one
102
104
  enableMapSet();
103
105
 
104
- const SPECIAL_PASSAGES = new Set([
105
- 'StoryInit',
106
- 'StoryInterface',
107
- 'StoryVariables',
108
- 'StoryTransients',
109
- 'StoryLoading',
110
- 'SaveTitle',
111
- 'PassageReady',
112
- 'PassageHeader',
113
- 'PassageFooter',
114
- 'PassageDone',
115
- 'StoryContext',
116
- ]);
117
-
118
- /** Whether `name` is a special passage, which navigation never goes to. */
119
- export function isSpecialPassage(name: string): boolean {
120
- return SPECIAL_PASSAGES.has(name);
121
- }
122
-
123
106
  // ---------------------------------------------------------------------------
124
107
  // Patch-based variable history (module-level, outside Zustand)
125
108
  // ---------------------------------------------------------------------------
@@ -1515,14 +1498,14 @@ export const useStoryStore = create<StoryState>()(
1515
1498
  setVariable: (name: string, value: unknown) => {
1516
1499
  set((state) => {
1517
1500
  checkVariableName(name, `$${name}`);
1518
- state.variables[name] = value;
1501
+ setByPath(state.variables, [name], value);
1519
1502
  });
1520
1503
  },
1521
1504
 
1522
1505
  setTemporary: (name: string, value: unknown) => {
1523
1506
  set((state) => {
1524
1507
  checkVariableName(name, `_${name}`);
1525
- state.temporary[name] = value;
1508
+ setByPath(state.temporary, [name], value);
1526
1509
  });
1527
1510
  },
1528
1511
 
@@ -1543,7 +1526,7 @@ export const useStoryStore = create<StoryState>()(
1543
1526
  setTransient: (name: string, value: unknown) => {
1544
1527
  set((state) => {
1545
1528
  checkVariableName(name, `%${name}`);
1546
- state.transient[name] = value;
1529
+ setByPath(state.transient, [name], value);
1547
1530
  });
1548
1531
  },
1549
1532
 
@@ -44,6 +44,7 @@ import {
44
44
  } from './utils/namespace';
45
45
  import { staticLiteral, type LiteralShape } from './static-literal';
46
46
  import { parse } from 'acorn';
47
+ import { MarkupExpansionBudget } from './markup/expansion-budget';
47
48
 
48
49
  /**
49
50
  * The tokens of markup, or none if it is malformed (validateMarkup reports
@@ -502,6 +503,7 @@ const BUILTIN_STORE_VAR_MACROS: readonly string[] = [
502
503
 
503
504
  /** What reading the variable references of markup depends on. */
504
505
  interface ReferenceOptions {
506
+ expansionBudget?: MarkupExpansionBudget;
505
507
  /** The (lowercase) names of the input macros that bind a variable. */
506
508
  storeVarMacros: ReadonlySet<string>;
507
509
  parametersOf: ParametersOf;
@@ -572,7 +574,24 @@ function scanInterpolations(
572
574
  options: ReferenceOptions,
573
575
  ): void {
574
576
  if (!text.includes('{')) return;
575
- collectTokenRefs(text, tokensOf(text, true, options), at, emit, options);
577
+ const budget = options.expansionBudget!;
578
+ if (!budget.enter(text.length)) return;
579
+ try {
580
+ const offset = at(0);
581
+ const sourceOffsets =
582
+ at(text.length) - offset === text.length
583
+ ? undefined
584
+ : Array.from({ length: text.length + 1 }, (_, i) => at(i));
585
+ collectTokenRefs(
586
+ text,
587
+ tokensOf(text, true, options),
588
+ (i) => sourceOffsets?.[i] ?? offset + i,
589
+ emit,
590
+ options,
591
+ );
592
+ } finally {
593
+ budget.leave();
594
+ }
576
595
  }
577
596
 
578
597
  /**
@@ -891,7 +910,10 @@ export function collectVariableReferences(
891
910
  tokensOf(content, false, options),
892
911
  (i) => i,
893
912
  (ref) => found.push(ref),
894
- options,
913
+ {
914
+ ...options,
915
+ expansionBudget: new MarkupExpansionBudget(content.length),
916
+ },
895
917
  ),
896
918
  );
897
919
  // The scan visits a macro's arguments before its selectors, and bindings
package/src/tooling.ts CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  type MarkupDiagnostic,
17
17
  type MarkupPassage,
18
18
  } from './markup/validate';
19
- import { isBlockMacro, isRawMacro } from './markup/ast';
19
+ import { isBlockMacro, isRawMacro, isRegisteredBlockMacro } from './markup/ast';
20
20
  import {
21
21
  tokenizeMarkup as tokenizeRawMarkup,
22
22
  tokenizeMarkupTolerant as tokenizeRawMarkupTolerant,
@@ -122,6 +122,7 @@ export type {
122
122
  PairMarkupOptions,
123
123
  } from './markup/pair';
124
124
  export { isBlockMacro } from './markup/ast';
125
+ export { isSpecialPassage } from './passage-roles';
125
126
  export type { MarkupErrorCode } from './markup/parse';
126
127
  export {
127
128
  endsWithOperator,
@@ -271,9 +272,6 @@ export function validateStoryMarkup(
271
272
  const widgets = effectiveWidgetDefinitions(
272
273
  readWidgetDefinitions(list, parameterLookup(all)),
273
274
  );
274
- const blocks = new Set(
275
- widgets.filter((def) => def.block).map((def) => def.name.toLowerCase()),
276
- );
277
275
  const parametersOf = parameterLookup([
278
276
  ...all,
279
277
  ...definedWidgetMacros(widgets),
@@ -282,15 +280,21 @@ export function validateStoryMarkup(
282
280
  const name = macro.name.toLowerCase();
283
281
  known.add(name);
284
282
  for (const sub of macro.subMacros) known.add(sub.toLowerCase());
285
- if (macro.block) blocks.add(name);
286
283
  }
287
284
  return validateMarkup(list, {
288
285
  branchParents: (name) => branchParents(name, all),
289
286
  isKnownMacro: (name) => known.has(name),
290
287
  macroNames: known,
291
288
  parametersOf,
292
- isBlockMacro: (name) =>
293
- blocks.has(name.toLowerCase()) || isBlockMacro(name),
289
+ isBlockMacro: blockLookup([
290
+ ...all,
291
+ ...widgets.map((w) => ({
292
+ name: w.name,
293
+ block: w.block,
294
+ subMacros: [],
295
+ widget: w,
296
+ })),
297
+ ]),
294
298
  checkPassageNames: options.checkPassageNames,
295
299
  tolerant: options.tolerant,
296
300
  });
@@ -303,10 +307,13 @@ function definedWidgetMacros(widgets: readonly WidgetDefinition[]) {
303
307
 
304
308
  /** Whether a macro takes a body, among `macros` and the built-in ones. */
305
309
  function blockLookup(macros: readonly ToolingMacro[]) {
306
- const blocks = new Set(
307
- macros.filter((m) => m.block).map((m) => m.name.toLowerCase()),
308
- );
309
- return (name: string) => blocks.has(name.toLowerCase()) || isBlockMacro(name);
310
+ const definitions = new NameMap<boolean>();
311
+ for (const macro of effectiveToolingMacros(macros)) {
312
+ definitions.set(macro.name, macro.block);
313
+ }
314
+ return (name: string) =>
315
+ isRegisteredBlockMacro(name) ||
316
+ (definitions.get(name) ?? isBlockMacro(name));
310
317
  }
311
318
 
312
319
  /**
@@ -3,6 +3,7 @@ import type { Token } from '../markup/tokens';
3
3
  import { codeAndText, parameterLookup, type ParametersOf } from '../code-check';
4
4
  import { parseMarkup, type MarkupHooks } from '../markup/parse';
5
5
  import { getMacroRegistry, getMacroParameters } from '../registry';
6
+ import { MarkupExpansionBudget } from '../markup/expansion-budget';
6
7
 
7
8
  /** The declared parameters of the macros registered so far. */
8
9
  export const registeredParameters: ParametersOf = (name) =>
@@ -17,16 +18,19 @@ function textContainsChildren(
17
18
  text: string,
18
19
  parametersOf: ParametersOf,
19
20
  hooks?: Partial<MarkupHooks>,
21
+ budget = new MarkupExpansionBudget(text.length),
20
22
  ): boolean {
21
23
  if (!text.includes('{')) return false;
22
- let nodes: ASTNode[];
24
+ if (!budget.enter(text.length)) return false;
23
25
  try {
24
- nodes = parseMarkup(text, { text: true, hooks });
26
+ const nodes = parseMarkup(text, { text: true, hooks });
27
+ return astContainsChildren(nodes, parametersOf, hooks, budget);
25
28
  } catch {
26
29
  // The renderer reports the markup that does not parse
27
30
  return false;
31
+ } finally {
32
+ budget.leave();
28
33
  }
29
- return astContainsChildren(nodes, parametersOf, hooks);
30
34
  }
31
35
 
32
36
  /**
@@ -42,11 +46,12 @@ export function tokenTextContainsChildren(
42
46
  parametersOf: ParametersOf = registeredParameters,
43
47
  src = '',
44
48
  hooks?: Partial<MarkupHooks>,
49
+ budget?: MarkupExpansionBudget,
45
50
  ): boolean {
46
51
  for (const piece of codeAndText(src, [token], parametersOf)) {
47
52
  if (
48
53
  piece.kind === 'text' &&
49
- textContainsChildren(piece.text, parametersOf, hooks)
54
+ textContainsChildren(piece.text, parametersOf, hooks, budget)
50
55
  ) {
51
56
  return true;
52
57
  }
@@ -55,7 +60,7 @@ export function tokenTextContainsChildren(
55
60
  }
56
61
 
57
62
  /**
58
- * Recursively scan an AST node array for a VariableNode
63
+ * Scan an AST node array for a VariableNode
59
64
  * with scope 'local' and name 'children' (@children), in the content and in
60
65
  * the attributes and labels that render markup. A nested `{widget}` is not
61
66
  * entered: its slot belongs to the innermost widget (as widgetDefinitions
@@ -65,8 +70,11 @@ export function astContainsChildren(
65
70
  nodes: ASTNode[],
66
71
  parametersOf: ParametersOf = registeredParameters,
67
72
  hooks?: Partial<MarkupHooks>,
73
+ budget?: MarkupExpansionBudget,
68
74
  ): boolean {
69
- for (const node of nodes) {
75
+ const pending = [...nodes];
76
+ while (pending.length) {
77
+ const node = pending.pop()!;
70
78
  if (
71
79
  node.type === 'variable' &&
72
80
  node.scope === 'local' &&
@@ -96,17 +104,13 @@ export function astContainsChildren(
96
104
  argsStart: 0,
97
105
  argsEnd: 0,
98
106
  };
99
- if (
100
- tokenTextContainsChildren(tag, parametersOf, '', hooks) ||
101
- astContainsChildren(node.children, parametersOf, hooks)
102
- ) {
107
+ if (tokenTextContainsChildren(tag, parametersOf, '', hooks, budget)) {
103
108
  return true;
104
109
  }
110
+ for (const child of node.children) pending.push(child);
105
111
  if (node.type === 'macro' && node.branches) {
106
112
  for (const branch of node.branches) {
107
- if (astContainsChildren(branch.children, parametersOf, hooks)) {
108
- return true;
109
- }
113
+ for (const child of branch.children) pending.push(child);
110
114
  }
111
115
  }
112
116
  }
@@ -10,6 +10,7 @@ import type { MacroToken } from '../markup/tokens';
10
10
  import type { ParametersOf } from '../code-check';
11
11
  import { NameMap } from '../utils/macro-names';
12
12
  import { registeredParameters, tokenTextContainsChildren } from './ast-scanner';
13
+ import { MarkupExpansionBudget } from '../markup/expansion-budget';
13
14
 
14
15
  /** A {widget} definition's name, then its `@` parameters. */
15
16
  export const WIDGET_PARAMETERS = [
@@ -146,6 +147,7 @@ export function widgetDefinitions(
146
147
  if (passage.name !== 'StoryInit' && !passage.tags?.includes('widget')) {
147
148
  continue;
148
149
  }
150
+ const budget = new MarkupExpansionBudget(passage.content.length);
149
151
  // The open definitions: their tags, and whether a slot was seen
150
152
  const open: {
151
153
  token: MacroToken;
@@ -172,6 +174,7 @@ export function widgetDefinitions(
172
174
  parametersOf,
173
175
  passage.content,
174
176
  hooks,
177
+ budget,
175
178
  ))
176
179
  ) {
177
180
  open[open.length - 1]!.isBlock = true;
@@ -171,6 +171,7 @@ export interface MarkupDiagnostic {
171
171
  * | --- | --- |
172
172
  * | `unknown-macro` | `name`, `suggestions` (the closest known macro, if close) |
173
173
  * | `unknown-passage` | `name`, `macro` (`link` for `[[…]]`), `suggestions` |
174
+ * | `special-passage` | `name`, `macro` |
174
175
  * | `unquoted-passage-name` | `name`, `macro` |
175
176
  * | `argument-error` | `macro` |
176
177
  * | `code-syntax` | `macro`, for a macro argument |
@@ -181,6 +182,7 @@ export type MarkupDiagnosticCode =
181
182
  | 'argument-error'
182
183
  | 'code-syntax'
183
184
  | 'unknown-passage'
185
+ | 'special-passage'
184
186
  | 'unquoted-passage-name';
185
187
 
186
188
  /** What a diagnostic names, by code (see {@link MarkupDiagnosticCode}). */
@@ -887,6 +889,8 @@ export interface CodePiece extends PieceBase {
887
889
  export interface PassagePiece extends PieceBase {
888
890
  kind: 'passage';
889
891
  name: string;
892
+ /** A known navigation target, rather than included/dialog content. */
893
+ navigation?: true;
890
894
  /** The markup it is in, for an error: `[[Go->Hall]]`. */
891
895
  label: string;
892
896
  /** How much of the markup is the name, as written (quotes included). */
@@ -1050,6 +1054,9 @@ export declare function pairMarkup(
1050
1054
  */
1051
1055
  export declare function isBlockMacro(name: string): boolean;
1052
1056
 
1057
+ /** Whether a case-sensitive passage name is reserved and cannot be navigated to. */
1058
+ export declare function isSpecialPassage(name: string): boolean;
1059
+
1053
1060
  // ---------------------------------------------------------------------------
1054
1061
  // Declarations
1055
1062
  // ---------------------------------------------------------------------------