@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.
@@ -15,6 +15,7 @@ export {
15
15
  pieceOffset,
16
16
  pairMarkup,
17
17
  isBlockMacro,
18
+ isSpecialPassage,
18
19
  parseStoryVariables,
19
20
  parseDeclarations,
20
21
  formatDiagnostic,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.9",
3
+ "version": "0.63.0",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
package/src/code-check.ts CHANGED
@@ -50,6 +50,7 @@ import { NameMap } from './utils/macro-names';
50
50
  import { hasOwn } from './utils/namespace';
51
51
  import { isRawMacro } from './markup/ast';
52
52
  import { sourcePositions } from './markup/line-column';
53
+ import { MarkupExpansionBudget } from './markup/expansion-budget';
53
54
 
54
55
  /** While a pass runs: the code it parsed so far, by goal and source. */
55
56
  let parses: Map<string, ParsedCode | CodeSyntaxError> | null = null;
@@ -156,6 +157,8 @@ interface MacroPiece extends LabeledPiece {
156
157
  export interface PassagePiece extends MacroPiece {
157
158
  kind: 'passage';
158
159
  name: string;
160
+ /** A known navigation target, rather than included/dialog content. */
161
+ navigation?: true;
159
162
  }
160
163
 
161
164
  /**
@@ -387,6 +390,9 @@ export function* codeAndText(
387
390
  offset: token.targetStart,
388
391
  length: token.targetEnd - token.targetStart,
389
392
  macro: 'link',
393
+ ...(usesBuiltinSemantics('link', parametersOf) && {
394
+ navigation: true as const,
395
+ }),
390
396
  label: src.slice(token.start, token.end),
391
397
  };
392
398
  // The label is markup too (the link renders as `{link}`)
@@ -479,7 +485,16 @@ export function* codeAndText(
479
485
  continue;
480
486
  }
481
487
  const params = parametersOf(name);
482
- if (params) yield* argPieces(args, argsAt, params, token.name, label);
488
+ if (params) {
489
+ const navigation = usesBuiltinSemantics(name, parametersOf)
490
+ ? name === 'goto' || name === 'link'
491
+ ? ['passage']
492
+ : name === 'watch'
493
+ ? ['goto']
494
+ : []
495
+ : [];
496
+ yield* argPieces(args, argsAt, params, token.name, label, navigation);
497
+ }
483
498
  if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
484
499
  }
485
500
  }
@@ -518,6 +533,7 @@ export function* passagePiecesOf(
518
533
  (i) => i,
519
534
  undefined,
520
535
  locate,
536
+ new MarkupExpansionBudget(src.length),
521
537
  );
522
538
  }
523
539
 
@@ -535,6 +551,7 @@ function* expand(
535
551
  toRoot: (offset: number) => number,
536
552
  where: string | undefined,
537
553
  locate: ReturnType<typeof sourcePositions>,
554
+ budget: MarkupExpansionBudget,
538
555
  ): Generator<Piece> {
539
556
  for (const flat of codeAndText(src, tokens, parametersOf)) {
540
557
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
@@ -543,41 +560,67 @@ function* expand(
543
560
  continue;
544
561
  }
545
562
  // The text may not be where its length says: a string with escapes
546
- const toText = (i: number) => toRoot(pieceOffset(flat, i));
547
- const inner = analyzeMarkup(flat.text, {
548
- text: true,
549
- hooks: {
550
- ...(options.isBlock && { isBlock: options.isBlock }),
551
- isRaw: (name) =>
552
- isRawMacro(name, parametersOf.widget?.(name) !== undefined),
553
- },
554
- });
555
- yield {
556
- ...(piece as TextPiece),
557
- tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
558
- errors: inner.errors.map((e) => {
559
- const { line, column } = locate(toText(e.offset));
560
- return new MarkupError(
561
- e.reason,
562
- toText(e.offset),
563
- line,
564
- column,
565
- e.code,
566
- toText(e.end),
567
- e.data,
568
- );
569
- }),
570
- };
571
- yield* expand(
572
- root,
573
- flat.text,
574
- inner.tokens,
575
- parametersOf,
576
- options,
577
- toText,
578
- flat.where,
579
- locate,
580
- );
563
+ // nestedPiece flattened the offsets into the root source. Avoid composing
564
+ // a recursive mapping closure for every enclosing label.
565
+ const toText = (i: number) => pieceOffset(piece, i);
566
+ if (!budget.enter(flat.text.length)) {
567
+ const at = toText(0);
568
+ const { line, column } = locate(at);
569
+ yield {
570
+ ...(piece as TextPiece),
571
+ errors: [
572
+ new MarkupError(
573
+ 'Markup in labels and attributes exceeds the nesting or work limit',
574
+ at,
575
+ line,
576
+ column,
577
+ 'nesting-limit',
578
+ toText(flat.text.length),
579
+ { limit: String(MarkupExpansionBudget.maxDepth) },
580
+ ),
581
+ ],
582
+ };
583
+ continue;
584
+ }
585
+ try {
586
+ const inner = analyzeMarkup(flat.text, {
587
+ text: true,
588
+ hooks: {
589
+ ...(options.isBlock && { isBlock: options.isBlock }),
590
+ isRaw: (name) =>
591
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined),
592
+ },
593
+ });
594
+ yield {
595
+ ...(piece as TextPiece),
596
+ tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
597
+ errors: inner.errors.map((e) => {
598
+ const { line, column } = locate(toText(e.offset));
599
+ return new MarkupError(
600
+ e.reason,
601
+ toText(e.offset),
602
+ line,
603
+ column,
604
+ e.code,
605
+ toText(e.end),
606
+ e.data,
607
+ );
608
+ }),
609
+ };
610
+ yield* expand(
611
+ root,
612
+ flat.text,
613
+ inner.tokens,
614
+ parametersOf,
615
+ options,
616
+ toText,
617
+ flat.where,
618
+ locate,
619
+ budget,
620
+ );
621
+ } finally {
622
+ budget.leave();
623
+ }
581
624
  }
582
625
  }
583
626
 
@@ -676,6 +719,7 @@ export function* argPieces(
676
719
  params: readonly ParameterDef[],
677
720
  macro: string,
678
721
  label: string,
722
+ navigation: readonly string[] = [],
679
723
  ): Generator<Piece> {
680
724
  let values: Record<string, unknown>;
681
725
  const spans: ArgSpans = new Map();
@@ -702,6 +746,7 @@ export function* argPieces(
702
746
  macro,
703
747
  label,
704
748
  'quotes',
749
+ navigation,
705
750
  );
706
751
  }
707
752
 
@@ -757,6 +802,7 @@ function* valuePieces(
757
802
  macro: string,
758
803
  label: string,
759
804
  escapes: Escapes,
805
+ navigation: readonly string[] = [],
760
806
  ): Generator<Piece> {
761
807
  const name = macro.toLowerCase();
762
808
  /** The pieces of the parameters `list`, with their values in `from`. */
@@ -785,6 +831,7 @@ function* valuePieces(
785
831
  length: end - start,
786
832
  macro: name,
787
833
  label,
834
+ ...(navigation.includes(param.name) && { navigation: true as const }),
788
835
  });
789
836
  const goal = codeGoal(param);
790
837
  if (param.type === 'passage') {
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,20 @@ 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 BLOCK_MACROS.has(name);
108
+ }
109
+
110
+ /** Explicit parser registrations, unaffected by effective tooling metadata. */
111
+ export function isRegisteredBlockMacro(name: string): boolean {
112
+ return REGISTERED_BLOCK_MACROS.has(name);
106
113
  }
107
114
 
108
115
  /** Register a custom macro as a block macro so the parser nests children. */
109
116
  export function registerBlockMacro(name: string): void {
110
- BLOCK_MACROS.add(name);
117
+ REGISTERED_BLOCK_MACROS.add(name);
111
118
  }
112
119
 
113
120
  /**
@@ -127,8 +134,9 @@ export function clearBlockWidgets(): void {
127
134
 
128
135
  /** Unregister a custom block macro (for test cleanup). */
129
136
  export function unregisterBlockMacro(name: string): void {
130
- BLOCK_MACROS.delete(name);
137
+ REGISTERED_BLOCK_MACROS.delete(name);
131
138
  DEFINED_BLOCK_MACROS.delete(name);
139
+ DEFINED_MACROS.delete(name);
132
140
  }
133
141
 
134
142
  /** 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
+ }
@@ -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) {
@@ -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)