@rohal12/spindle 0.62.9 → 0.64.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.
package/src/js-lexer.ts CHANGED
@@ -716,152 +716,172 @@ function propertyName(node: unknown, src: string): void {
716
716
  * variable can't be. `shorthand`: the node is a shorthand property's value.
717
717
  */
718
718
  function walk(
719
- node: unknown,
719
+ root: unknown,
720
720
  src: string,
721
721
  out: ParsedCode,
722
722
  binding: boolean,
723
723
  shorthand: boolean,
724
724
  access: 'read' | 'write' | 'readwrite' = 'read',
725
725
  ): void {
726
- if (Array.isArray(node)) {
727
- for (const n of node) walk(n, src, out, binding, false, access);
728
- return;
726
+ type Visit = [unknown, boolean, boolean, typeof access];
727
+ const pending: Visit[] = [[root, binding, shorthand, access]];
728
+ while (pending.length) {
729
+ const [node, bind, short, role] = pending.pop()!;
730
+ const children: Visit[] = [];
731
+ visit(node, bind, short, role, children);
732
+ // Reverse only the work stack, retaining reference/string and error order.
733
+ for (let i = children.length - 1; i >= 0; i--) pending.push(children[i]!);
729
734
  }
730
- if (!isNode(node)) return;
731
- const sub = (
732
- child: unknown,
733
- bind = false,
734
- short = false,
735
- role: typeof access = 'read',
736
- ) => walk(child, src, out, bind, short, role);
737
- switch (node.type) {
738
- case 'Identifier': {
739
- const sigil = sigilOf(node, src);
740
- if (!sigil) return;
741
- if (binding) {
742
- throw new CodeSyntaxError(
743
- `"${node.name as string}" is a ${NAMESPACE_NAME[sigil[0]]} variable and can't be declared`,
744
- src,
745
- node.start,
746
- );
747
- }
748
- out.refs.push({
749
- sigil: sigil[0],
750
- name: sigil[1],
751
- start: node.start,
752
- end: node.end,
753
- shorthand,
754
- read: access !== 'write',
755
- write: access !== 'read',
756
- });
735
+
736
+ function visit(
737
+ node: unknown,
738
+ binding: boolean,
739
+ shorthand: boolean,
740
+ access: Visit[3],
741
+ children: Visit[],
742
+ ): void {
743
+ if (Array.isArray(node)) {
744
+ for (const n of node) children.push([n, binding, false, access]);
757
745
  return;
758
746
  }
759
- case 'Literal':
760
- if (typeof node.value === 'string') {
761
- out.strings.push(src.slice(node.start + 1, node.end - 1));
747
+ if (!isNode(node)) return;
748
+ const sub = (
749
+ child: unknown,
750
+ bind = false,
751
+ short = false,
752
+ role: typeof access = 'read',
753
+ ) => {
754
+ children.push([child, bind, short, role]);
755
+ };
756
+ switch (node.type) {
757
+ case 'Identifier': {
758
+ const sigil = sigilOf(node, src);
759
+ if (!sigil) return;
760
+ if (binding) {
761
+ throw new CodeSyntaxError(
762
+ `"${node.name as string}" is a ${NAMESPACE_NAME[sigil[0]]} variable and can't be declared`,
763
+ src,
764
+ node.start,
765
+ );
766
+ }
767
+ out.refs.push({
768
+ sigil: sigil[0],
769
+ name: sigil[1],
770
+ start: node.start,
771
+ end: node.end,
772
+ shorthand,
773
+ read: access !== 'write',
774
+ write: access !== 'read',
775
+ });
776
+ return;
762
777
  }
763
- return;
764
- case 'TemplateElement':
765
- out.strings.push((node.value as { raw: string }).raw);
766
- return;
767
- case 'MemberExpression':
768
- sub(node.object);
769
- if (node.computed) sub(node.property);
770
- else propertyName(node.property, src);
771
- return;
772
- case 'Property':
773
- if (node.computed) sub(node.key);
774
- else if (!node.shorthand) propertyName(node.key, src);
775
- if (node.shorthand) {
776
- const value = node.value as AnyNode;
777
- if (value.type === 'AssignmentPattern') {
778
- sub(value.left, binding, true, access);
779
- sub(value.right);
778
+ case 'Literal':
779
+ if (typeof node.value === 'string') {
780
+ out.strings.push(src.slice(node.start + 1, node.end - 1));
781
+ }
782
+ return;
783
+ case 'TemplateElement':
784
+ out.strings.push((node.value as { raw: string }).raw);
785
+ return;
786
+ case 'MemberExpression':
787
+ sub(node.object);
788
+ if (node.computed) sub(node.property);
789
+ else propertyName(node.property, src);
790
+ return;
791
+ case 'Property':
792
+ if (node.computed) sub(node.key);
793
+ else if (!node.shorthand) propertyName(node.key, src);
794
+ if (node.shorthand) {
795
+ const value = node.value as AnyNode;
796
+ if (value.type === 'AssignmentPattern') {
797
+ sub(value.left, binding, true, access);
798
+ sub(value.right);
799
+ } else {
800
+ sub(value, binding, true, access);
801
+ }
780
802
  } else {
781
- sub(value, binding, true, access);
803
+ sub(node.value, binding, false, access);
782
804
  }
783
- } else {
784
- sub(node.value, binding, false, access);
785
- }
786
- return;
787
- case 'MethodDefinition':
788
- case 'PropertyDefinition':
789
- if (node.computed) sub(node.key);
790
- else propertyName(node.key, src);
791
- sub(node.value);
792
- return;
793
- case 'LabeledStatement':
794
- sub(node.body);
795
- return;
796
- case 'BreakStatement':
797
- case 'ContinueStatement':
798
- case 'MetaProperty':
799
- case 'PrivateIdentifier':
800
- return;
801
- case 'VariableDeclarator':
802
- sub(node.id, true);
803
- sub(node.init);
804
- return;
805
- case 'FunctionDeclaration':
806
- case 'FunctionExpression':
807
- case 'ArrowFunctionExpression':
808
- sub(node.id, true);
809
- for (const p of node.params as unknown[]) sub(p, true);
810
- sub(node.body);
811
- return;
812
- case 'ClassDeclaration':
813
- case 'ClassExpression':
814
- sub(node.id, true);
815
- sub(node.superClass);
816
- sub(node.body);
817
- return;
818
- case 'CatchClause':
819
- sub(node.param, true);
820
- sub(node.body);
821
- return;
822
- case 'AssignmentExpression':
823
- sub(
824
- node.left,
825
- false,
826
- false,
827
- node.operator === '=' ? 'write' : 'readwrite',
828
- );
829
- sub(node.right);
830
- return;
831
- case 'UnaryExpression':
832
- sub(
833
- node.argument,
834
- false,
835
- false,
836
- node.operator === 'delete' ? 'write' : 'read',
837
- );
838
- return;
839
- case 'UpdateExpression':
840
- sub(node.argument, false, false, 'readwrite');
841
- return;
842
- case 'ForInStatement':
843
- case 'ForOfStatement':
844
- sub(node.left, false, false, 'write');
845
- sub(node.right);
846
- sub(node.body);
847
- return;
848
- case 'AssignmentPattern':
849
- sub(node.left, binding, false, access);
850
- sub(node.right);
851
- return;
852
- case 'ObjectPattern':
853
- case 'ArrayPattern':
854
- case 'RestElement':
855
- for (const key of ['properties', 'elements', 'argument']) {
856
- sub(node[key], binding, false, access);
857
- }
858
- return;
859
- default:
860
- for (const key in node) {
861
- if (key === 'type' || key === 'start' || key === 'end') continue;
862
- const v = node[key];
863
- if (typeof v === 'object' && v !== null) sub(v);
864
- }
805
+ return;
806
+ case 'MethodDefinition':
807
+ case 'PropertyDefinition':
808
+ if (node.computed) sub(node.key);
809
+ else propertyName(node.key, src);
810
+ sub(node.value);
811
+ return;
812
+ case 'LabeledStatement':
813
+ sub(node.body);
814
+ return;
815
+ case 'BreakStatement':
816
+ case 'ContinueStatement':
817
+ case 'MetaProperty':
818
+ case 'PrivateIdentifier':
819
+ return;
820
+ case 'VariableDeclarator':
821
+ sub(node.id, true);
822
+ sub(node.init);
823
+ return;
824
+ case 'FunctionDeclaration':
825
+ case 'FunctionExpression':
826
+ case 'ArrowFunctionExpression':
827
+ sub(node.id, true);
828
+ for (const p of node.params as unknown[]) sub(p, true);
829
+ sub(node.body);
830
+ return;
831
+ case 'ClassDeclaration':
832
+ case 'ClassExpression':
833
+ sub(node.id, true);
834
+ sub(node.superClass);
835
+ sub(node.body);
836
+ return;
837
+ case 'CatchClause':
838
+ sub(node.param, true);
839
+ sub(node.body);
840
+ return;
841
+ case 'AssignmentExpression':
842
+ sub(
843
+ node.left,
844
+ false,
845
+ false,
846
+ node.operator === '=' ? 'write' : 'readwrite',
847
+ );
848
+ sub(node.right);
849
+ return;
850
+ case 'UnaryExpression':
851
+ sub(
852
+ node.argument,
853
+ false,
854
+ false,
855
+ node.operator === 'delete' ? 'write' : 'read',
856
+ );
857
+ return;
858
+ case 'UpdateExpression':
859
+ sub(node.argument, false, false, 'readwrite');
860
+ return;
861
+ case 'ForInStatement':
862
+ case 'ForOfStatement':
863
+ sub(node.left, false, false, 'write');
864
+ sub(node.right);
865
+ sub(node.body);
866
+ return;
867
+ case 'AssignmentPattern':
868
+ sub(node.left, binding, false, access);
869
+ sub(node.right);
870
+ return;
871
+ case 'ObjectPattern':
872
+ case 'ArrayPattern':
873
+ case 'RestElement':
874
+ for (const key of ['properties', 'elements', 'argument']) {
875
+ sub(node[key], binding, false, access);
876
+ }
877
+ return;
878
+ default:
879
+ for (const key in node) {
880
+ if (key === 'type' || key === 'start' || key === 'end') continue;
881
+ const v = node[key];
882
+ if (typeof v === 'object' && v !== null) sub(v);
883
+ }
884
+ }
865
885
  }
866
886
  }
867
887
 
package/src/markup/ast.ts CHANGED
@@ -68,8 +68,7 @@ const BLOCK_MACROS = new NameSet([
68
68
 
69
69
  /**
70
70
  * The block widgets (those whose body renders `{@children}`), kept apart from
71
- * BLOCK_MACROS: a widget is redefined, so it is a block only while its latest
72
- * definition is, whereas the macros in BLOCK_MACROS stay blocks.
71
+ * built-in defaults: a widget is a block only while its latest definition is.
73
72
  */
74
73
  const BLOCK_WIDGETS = new NameSet();
75
74
  /** All widgets, including inline ones, override built-in parsing semantics. */
@@ -77,8 +76,12 @@ const WIDGETS = new NameSet();
77
76
 
78
77
  /** Classification owned by defineMacro, independent of explicit registrations. */
79
78
  const DEFINED_BLOCK_MACROS = new NameSet();
79
+ const DEFINED_MACROS = new NameSet();
80
+ /** Explicit registrations remain independent of macro/widget replacements. */
81
+ const REGISTERED_BLOCK_MACROS = new NameSet();
80
82
 
81
83
  export function setDefinedBlockMacro(name: string, isBlock: boolean): void {
84
+ DEFINED_MACROS.add(name);
82
85
  setClassification(DEFINED_BLOCK_MACROS, name, isBlock);
83
86
  }
84
87
 
@@ -98,16 +101,25 @@ export function isRawMacro(name: string, widget = WIDGETS.has(name)): boolean {
98
101
 
99
102
  /** Whether a macro takes a body closed by `{/name}`. */
100
103
  export function isBlockMacro(name: string): boolean {
101
- return (
102
- BLOCK_MACROS.has(name) ||
103
- DEFINED_BLOCK_MACROS.has(name) ||
104
- BLOCK_WIDGETS.has(name)
105
- );
104
+ if (REGISTERED_BLOCK_MACROS.has(name)) return true;
105
+ if (WIDGETS.has(name)) return BLOCK_WIDGETS.has(name);
106
+ if (DEFINED_MACROS.has(name)) return DEFINED_BLOCK_MACROS.has(name);
107
+ return isBuiltinBlockMacro(name);
108
+ }
109
+
110
+ /** Built-in defaults without any process-global registrations or widgets. */
111
+ export function isBuiltinBlockMacro(name: string): boolean {
112
+ return BLOCK_MACROS.has(name);
113
+ }
114
+
115
+ /** Explicit parser registrations, unaffected by effective tooling metadata. */
116
+ export function isRegisteredBlockMacro(name: string): boolean {
117
+ return REGISTERED_BLOCK_MACROS.has(name);
106
118
  }
107
119
 
108
120
  /** Register a custom macro as a block macro so the parser nests children. */
109
121
  export function registerBlockMacro(name: string): void {
110
- BLOCK_MACROS.add(name);
122
+ REGISTERED_BLOCK_MACROS.add(name);
111
123
  }
112
124
 
113
125
  /**
@@ -127,8 +139,9 @@ export function clearBlockWidgets(): void {
127
139
 
128
140
  /** Unregister a custom block macro (for test cleanup). */
129
141
  export function unregisterBlockMacro(name: string): void {
130
- BLOCK_MACROS.delete(name);
142
+ REGISTERED_BLOCK_MACROS.delete(name);
131
143
  DEFINED_BLOCK_MACROS.delete(name);
144
+ DEFINED_MACROS.delete(name);
132
145
  }
133
146
 
134
147
  /** Macros whose branches render as one: the node holds one per branch. */
@@ -0,0 +1,23 @@
1
+ /** Shared bounds for reparsing markup inside labels, selectors and attributes. */
2
+ export class MarkupExpansionBudget {
3
+ static readonly maxDepth = 64;
4
+ private depth = 0;
5
+ private remaining: number;
6
+
7
+ constructor(sourceLength: number) {
8
+ // Bound total rescanning as well as call depth, including large labels.
9
+ this.remaining = Math.max(65_536, sourceLength * 8);
10
+ }
11
+
12
+ enter(length: number): boolean {
13
+ if (this.depth >= MarkupExpansionBudget.maxDepth || length > this.remaining)
14
+ return false;
15
+ this.remaining -= length;
16
+ this.depth++;
17
+ return true;
18
+ }
19
+
20
+ leave(): void {
21
+ this.depth--;
22
+ }
23
+ }
@@ -10,7 +10,7 @@
10
10
  * runtime reads it, or, when it matches one further out, closes that one and
11
11
  * what was open inside it stays unclosed.
12
12
  */
13
- import { branchParents } from '../registry';
13
+ import { branchParents, getMacroParameters } from '../registry';
14
14
  import { sourcePositions } from './line-column';
15
15
  import { isBlockMacro, isRawMacro } from './ast';
16
16
  import type { HtmlToken, MacroToken, Span, Token } from './tokens';
@@ -153,13 +153,15 @@ export function pairMarkup(
153
153
  const isBlock = options.isBlock ?? isBlockMacro;
154
154
  const isRaw = options.isRaw ?? isRawMacro;
155
155
  const parentsOf = (name: string): readonly string[] => {
156
+ if (options.branchParents) return options.branchParents(name);
157
+ const registered = branchParents(name);
156
158
  const lower = name.toLowerCase();
157
159
  const builtin = Object.prototype.hasOwnProperty.call(BRANCH_PARENT, lower)
158
160
  ? BRANCH_PARENT[lower]
159
161
  : undefined;
160
- return builtin
161
- ? [builtin]
162
- : (options.branchParents?.(name) ?? branchParents(name));
162
+ return builtin && getMacroParameters.source(builtin) === undefined
163
+ ? [...registered, builtin]
164
+ : registered;
163
165
  };
164
166
  const errors: PairingError[] = [];
165
167
  const noticedAtEnd = (tokens[tokens.length - 1]?.end ?? 0) + 1;
@@ -321,7 +321,7 @@ export function scanMarkupTolerant(
321
321
  const rest = source.slice(base);
322
322
  const result = attempt(rest, base);
323
323
  if (Array.isArray(result)) {
324
- tokens.push(...result);
324
+ for (const token of result) tokens.push(token);
325
325
  break;
326
326
  }
327
327
  const at = base + result.offset;
@@ -345,7 +345,7 @@ export function scanMarkupTolerant(
345
345
  cut = prefix.offset;
346
346
  prefix = attempt(rest.slice(0, cut), base);
347
347
  }
348
- tokens.push(...prefix);
348
+ for (const token of prefix) tokens.push(token);
349
349
  damage.push(base + cut);
350
350
  // The character that started the damage is text
351
351
  if (cut < rest.length) {
@@ -226,7 +226,7 @@ function PlaceholderAttributes({
226
226
  const ref = useDirectAttributes(direct);
227
227
  return withAttributeErrors(
228
228
  errors,
229
- h(tag, ref ? { ...props, ref } : props, ...children),
229
+ h(tag, ref ? { ...props, ref } : props, children),
230
230
  );
231
231
  }
232
232
 
@@ -243,7 +243,7 @@ function DirectAttributes({
243
243
  children: preact.ComponentChildren[];
244
244
  }) {
245
245
  const ref = useDirectAttributes(direct);
246
- return h(tag, { ...props, ref }, ...children);
246
+ return h(tag, { ...props, ref }, children);
247
247
  }
248
248
 
249
249
  /** An error met while evaluating the named attribute. */
@@ -306,16 +306,20 @@ function htmlToPreact(
306
306
  unwrapParagraphs = false,
307
307
  ): preact.ComponentChildren {
308
308
  const content = parseHtmlInert(html.trim());
309
- if (unwrapParagraphs) {
310
- for (const child of Array.from(content.childNodes)) {
311
- if (child.nodeType === Node.ELEMENT_NODE && child.nodeName === 'P') {
312
- (child as Element).replaceWith(...Array.from(child.childNodes));
309
+ const children: preact.ComponentChildren[] = [];
310
+ for (const child of Array.from(content.childNodes)) {
311
+ if (
312
+ unwrapParagraphs &&
313
+ child.nodeType === Node.ELEMENT_NODE &&
314
+ child.nodeName === 'P'
315
+ ) {
316
+ for (const node of Array.from(child.childNodes)) {
317
+ children.push(convertDomNode(node, children.length, ph));
313
318
  }
319
+ } else {
320
+ children.push(convertDomNode(child, children.length, ph));
314
321
  }
315
322
  }
316
- const children = Array.from(content.childNodes).map((child, i) =>
317
- convertDomNode(child, i, ph),
318
- );
319
323
  return <>{children}</>;
320
324
  }
321
325
 
@@ -392,7 +396,7 @@ function convertDomNode(
392
396
  />
393
397
  );
394
398
  }
395
- return h(tag, { ...props, key }, ...children);
399
+ return h(tag, { ...props, key }, children);
396
400
  }
397
401
  return null;
398
402
  }
@@ -1047,7 +1051,7 @@ function buildPlainTextVnodes(
1047
1051
  const children = expandPlaceholderText(trimLineEdges(core), ph).filter(
1048
1052
  (part) => part !== '',
1049
1053
  );
1050
- return unwrapParagraphs ? <>{children}</> : h('p', null, ...children);
1054
+ return unwrapParagraphs ? <>{children}</> : h('p', null, children);
1051
1055
  }
1052
1056
 
1053
1057
  /**
@@ -1111,20 +1115,24 @@ export function renderNodes(
1111
1115
  components,
1112
1116
  nodes: [],
1113
1117
  };
1114
- let combined = '';
1118
+ const chunks: string[] = [];
1119
+ let trailingBackslash = false;
1115
1120
 
1116
1121
  for (let i = 0; i < nodes.length; i++) {
1117
1122
  const node = nodes[i]!;
1118
1123
  if (node.type === 'text') {
1119
- combined += node.value;
1124
+ chunks.push(node.value);
1125
+ if (node.value) trailingBackslash = node.value.endsWith('\\');
1120
1126
  continue;
1121
1127
  }
1122
1128
  const phIdx = components.length;
1123
1129
  components.push(renderSingleNode(node));
1124
1130
  ph.nodes.push(node);
1125
- if (combined.endsWith('\\')) combined += ESCAPE_GUARD;
1126
- combined += placeholderHtml(ph.nonce, phIdx);
1131
+ if (trailingBackslash) chunks.push(ESCAPE_GUARD);
1132
+ chunks.push(placeholderHtml(ph.nonce, phIdx));
1133
+ trailingBackslash = false;
1127
1134
  }
1135
+ const combined = chunks.join('');
1128
1136
 
1129
1137
  // Fast path: skip micromark + innerHTML when text has no markdown syntax.
1130
1138
  // This eliminates ~655 innerHTML calls on plain UI text like "ALMA",
@@ -25,6 +25,7 @@ import {
25
25
  import { CodeSyntaxError } from '../js-lexer';
26
26
  import { sourcePositions } from './line-column';
27
27
  import { isRawMacro } from './ast';
28
+ import { isSpecialPassage } from '../passage-roles';
28
29
 
29
30
  /** A passage to validate. */
30
31
  export interface MarkupPassage {
@@ -48,6 +49,7 @@ export type MarkupDiagnosticCode =
48
49
  | 'argument-error'
49
50
  | 'code-syntax'
50
51
  | 'unknown-passage'
52
+ | 'special-passage'
51
53
  | 'unquoted-passage-name';
52
54
 
53
55
  /** What a diagnostic names, by code (see docs/tooling.md). */
@@ -371,6 +373,17 @@ export function validateMarkup(
371
373
  );
372
374
  break;
373
375
  case 'passage':
376
+ if (piece.navigation && isSpecialPassage(piece.name)) {
377
+ report(
378
+ passage,
379
+ at,
380
+ at + piece.length,
381
+ 'special-passage',
382
+ `${where}Cannot navigate to special passage ${JSON.stringify(piece.name)} in ${piece.label}.`,
383
+ { name: piece.name, macro: piece.macro },
384
+ );
385
+ break;
386
+ }
374
387
  if (
375
388
  options.checkPassageNames !== false &&
376
389
  !passageNames.has(piece.name)
@@ -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
+ }