@rohal12/spindle 0.61.4 → 0.61.6

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/code-check.ts CHANGED
@@ -334,15 +334,19 @@ export function* codeAndText(
334
334
  tokens: readonly Token[],
335
335
  parametersOf: ParametersOf,
336
336
  ): Generator<Piece> {
337
- /** The index of the closing tag of the `name` macro opened at `t`. */
338
- const closeOf = (t: number, name: string) =>
339
- tokens.findIndex(
340
- (c, k) =>
341
- k > t &&
342
- c.type === 'macro' &&
343
- c.isClose &&
344
- c.name.toLowerCase() === name,
345
- );
337
+ // Only a plain-text body is read here: raw JavaScript in {do}, or a
338
+ // passage name in {dialog}. Start at the opener and stop at any markup,
339
+ // including a nested opener, rather than rescanning the token prefix.
340
+ const closeOfTextBody = (t: number, name: string): number => {
341
+ for (let k = t + 1; k < tokens.length; k++) {
342
+ const c = tokens[k]!;
343
+ if (c.type === 'text') continue;
344
+ return c.type === 'macro' && c.isClose && c.name.toLowerCase() === name
345
+ ? k
346
+ : -1;
347
+ }
348
+ return -1;
349
+ };
346
350
  for (let t = 0; t < tokens.length; t++) {
347
351
  const token = tokens[t]!;
348
352
  if (token.type === 'link') {
@@ -393,7 +397,7 @@ export function* codeAndText(
393
397
  } else if (token.type === 'macro' && !token.isClose) {
394
398
  const name = token.name.toLowerCase();
395
399
  if (name === 'do') {
396
- const close = closeOf(t, name);
400
+ const close = closeOfTextBody(t, name);
397
401
  if (close < 0) continue;
398
402
  const body = src.slice(token.end, tokens[close]!.start);
399
403
  yield {
@@ -409,9 +413,8 @@ export function* codeAndText(
409
413
  const args = token.rawArgs;
410
414
  if (PASSAGE_BODIES.has(name)) {
411
415
  // The body names the passage when it is only text
412
- const close = closeOf(t, name);
413
- const body = tokens.slice(t + 1, close);
414
- if (close > t + 1 && body.every((b) => b.type === 'text')) {
416
+ const close = closeOfTextBody(t, name);
417
+ if (close > t + 1) {
415
418
  const text = src.slice(token.end, tokens[close]!.start);
416
419
  const written = text.trim();
417
420
  yield {
@@ -6,6 +6,7 @@ import { defineMacro } from '../../define-macro';
6
6
  import { MacroError, logMacroError } from './MacroError';
7
7
  import { currentSourceLocation } from '../../utils/source-location';
8
8
  import { checkVariableName, ownValue } from '../../utils/namespace';
9
+ import { PendingIterationContext } from '../../hooks/use-story-fields';
9
10
 
10
11
  /**
11
12
  * The previous output before the first successful evaluation. Distinct from
@@ -126,6 +127,7 @@ defineMacro({
126
127
  const isTemp = target.startsWith('_');
127
128
  const name = target.slice(1);
128
129
  const localsUpdate = isLocal ? ctx.update : null;
130
+ const pendingIteration = ctx.hooks.useContext(PendingIterationContext);
129
131
 
130
132
  const prevOutput = ctx.hooks.useRef<unknown>(UNSET);
131
133
  // The navigation the target was last checked in
@@ -153,7 +155,11 @@ defineMacro({
153
155
  // The merged values only decide when to recompute; computeAndApply reads
154
156
  // the current ones. The tuple is renewed with them and with the render
155
157
  // counts, which rendered() / hasRendered() read.
156
- ctx.hooks.useLayoutEffect(compute, [ctx.merged]);
158
+ ctx.hooks.useLayoutEffect(() => {
159
+ // A queued effect can outlive the loop state its locals belong to.
160
+ // Let the owner reconcile first, dropping any removed iterations.
161
+ if (!pendingIteration?.(useStoryStore.getState())) compute();
162
+ }, [ctx.merged, pendingIteration]);
157
163
 
158
164
  return null;
159
165
  },
@@ -1,4 +1,4 @@
1
- import { useMemo } from 'preact/hooks';
1
+ import { useContext, useMemo } from 'preact/hooks';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { MacroError } from './MacroError';
4
4
  import { stableKey } from '../../utils/stable-key';
@@ -11,6 +11,11 @@ import type { ASTNode } from '../../markup/ast';
11
11
  import { checkVariableName } from '../../utils/namespace';
12
12
  import { readState } from '../../execute-mutation';
13
13
  import { LocalsScope } from './locals-scope';
14
+ import {
15
+ FrozenStateContext,
16
+ PendingIterationContext,
17
+ } from '../../hooks/use-story-fields';
18
+ import type { StoryState } from '../../store';
14
19
 
15
20
  /**
16
21
  * Check the arguments of "@item, @i of $list" or "@item of $list".
@@ -97,6 +102,26 @@ defineMacro({
97
102
  { name: 'list', type: 'expression', required: true },
98
103
  ],
99
104
  render({ rawArgs, children = [] }, ctx) {
105
+ const enclosingFreeze = useContext(FrozenStateContext);
106
+ const enclosingPending = useContext(PendingIterationContext);
107
+ const [variables, temporary, , transient] = ctx.merged!;
108
+ // Until this loop reconciles its rows, descendants still have the old
109
+ // @item/@i. Keep them from independently reacting to newer namespaces.
110
+ const pending = useMemo(
111
+ () => (state: StoryState) =>
112
+ !!enclosingPending?.(state) ||
113
+ // A detached owner keeps its snapshot permanently: there is no
114
+ // pending reconciliation for its initial effects to wait for.
115
+ ((state.variables !== variables ||
116
+ state.temporary !== temporary ||
117
+ state.transient !== transient) &&
118
+ !enclosingFreeze?.(state)),
119
+ [enclosingPending, enclosingFreeze, variables, temporary, transient],
120
+ );
121
+ const freeze = useMemo(
122
+ () => (state: StoryState) => !!enclosingFreeze?.(state) || pending(state),
123
+ [enclosingFreeze, pending],
124
+ );
100
125
  const keys = ctx.hooks.useRef<IterationKeys>({
101
126
  contents: [],
102
127
  generations: [],
@@ -158,9 +183,13 @@ defineMacro({
158
183
  ));
159
184
 
160
185
  return ctx.wrap(
161
- <ItemEditContext.Provider value={true}>
162
- {content}
163
- </ItemEditContext.Provider>,
186
+ <FrozenStateContext.Provider value={freeze}>
187
+ <PendingIterationContext.Provider value={pending}>
188
+ <ItemEditContext.Provider value={true}>
189
+ {content}
190
+ </ItemEditContext.Provider>
191
+ </PendingIterationContext.Provider>
192
+ </FrozenStateContext.Provider>,
164
193
  );
165
194
  },
166
195
  text({ rawArgs, children = [] }, ctx) {
@@ -1,4 +1,4 @@
1
- import { useStoryStore } from '../../store';
1
+ import { useStoryFields } from '../../hooks/use-story-fields';
2
2
  import { useLiveLocals } from '../../hooks/use-merged-locals';
3
3
  import { useInterpolate } from '../../hooks/use-interpolate';
4
4
  import { ownValue, variableNameError } from '../../utils/namespace';
@@ -23,9 +23,11 @@ export function VarDisplay({ node }: { node: VariableNode }) {
23
23
  const parts = name.split('.');
24
24
  const root = parts[0]!;
25
25
  // Own entries only, as the expression engine reads them
26
- const storeValue = useStoryStore((s) =>
27
- scope === 'local' ? undefined : ownValue(s[STORE_NAMESPACES[scope]], root),
28
- );
26
+ const state = useStoryFields('variables', 'temporary', 'transient');
27
+ const storeValue =
28
+ scope === 'local'
29
+ ? undefined
30
+ : ownValue(state[STORE_NAMESPACES[scope]], root);
29
31
 
30
32
  const sigil = SCOPE_SIGILS[scope];
31
33
  const nameError = variableNameError(root, sigil + root);
@@ -182,15 +182,8 @@ function startsLikeValue(token: string): boolean {
182
182
  if (first === '"' || first === "'" || first === '`') return true;
183
183
  // Variable ($var, _var, @var, %var), but not the modulo operator in `$a % 2`
184
184
  if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
185
- // Number literal
186
- if (/\d/.test(first)) return true;
187
- // Signed number (-1, +2)
188
- if (
189
- (first === '-' || first === '+') &&
190
- token.length > 1 &&
191
- /\d/.test(token[1]!)
192
- )
193
- return true;
185
+ // Number literal, optionally signed, including leading-dot decimals.
186
+ if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
194
187
  // Grouped expression or collection literal
195
188
  if (first === '(' || first === '[' || first === '{') return true;
196
189
  // Boolean / null / undefined, alone or leading an expression (true||$x)
@@ -176,7 +176,7 @@ function readOptions(
176
176
  }
177
177
 
178
178
  /** `inline %name` reads a transient variable; `inline % 2` is modulo. */
179
- const LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
179
+ const LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,]|\.(?!\d)|%(?![A-Za-z_]))/;
180
180
 
181
181
  /**
182
182
  * Where the rest of `src` is without the flag `word` as its last or first
@@ -25,7 +25,7 @@ import {
25
25
  import type { ASTNode } from './markup/ast';
26
26
  import { executeMutation, mutateState, readState } from './execute-mutation';
27
27
  import { evaluateDisplay } from './expression';
28
- import { useStoryStore } from './store';
28
+ import { useStoryFields } from './hooks/use-story-fields';
29
29
  import { getByPath, setByPath } from './utils/object-path';
30
30
  import { RESERVED_NAME } from './utils/namespace';
31
31
  import { parseMemberIdentifier, parseReferencePath } from './js-lexer';
@@ -299,7 +299,7 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
299
299
  );
300
300
  }
301
301
  ctx.varName = varExpr;
302
- ctx.value = useStoryStore((s) => getByPath(s.variables, segments));
302
+ ctx.value = getByPath(useStoryFields('variables').variables, segments);
303
303
  // In program order, also when mutation code performs the input
304
304
  ctx.getValue = () => getByPath(readState().variables, segments);
305
305
  ctx.setValue = displayOnly
@@ -14,9 +14,8 @@ import {
14
14
  import {
15
15
  multilineJsLiterals,
16
16
  replaceSpindleTokens,
17
- restoreSpindleTokens,
17
+ restoreHtmlTokens,
18
18
  replaceSvgBlocks,
19
- restoreSvgBlocks,
20
19
  placeholdersIntact,
21
20
  sameSpindleTokens,
22
21
  SPINDLE_PLACEHOLDERS,
@@ -299,6 +298,12 @@ async function formatLf(
299
298
  // HTML block — placeholder substitution + Prettier
300
299
  const { text: svgPlaceholdered, tokens: svgTokens } =
301
300
  replaceSvgBlocks(htmlText);
301
+ // A later whole-line Spindle token may hide an SVG marker. Check
302
+ // before that pass so a literal marker cannot stand in for it.
303
+ if (!placeholdersIntact(svgPlaceholdered, svgTokens, SVG_PLACEHOLDERS)) {
304
+ lines.push(...region.lines);
305
+ continue;
306
+ }
302
307
  const { text: placeholdered, tokens } =
303
308
  replaceSpindleTokens(svgPlaceholdered);
304
309
  const formatted = await formatHTMLPrettier(
@@ -318,11 +323,11 @@ async function formatLf(
318
323
  continue;
319
324
  }
320
325
  // A token's line breaks are its payload: keep them out of the line steps below
321
- const restoredSpindle = restoreSpindleTokens(
326
+ const restored = restoreHtmlTokens(
322
327
  formatted.trim(),
323
328
  tokens.map((t) => replaceAll(t, '\n', sentinel)),
329
+ svgTokens,
324
330
  );
325
- const restored = restoreSvgBlocks(restoredSpindle, svgTokens);
326
331
  for (const fLine of restored.split('\n')) {
327
332
  lines.push(fLine);
328
333
  }
@@ -611,12 +616,14 @@ const NO_WRAP = new Set([
611
616
  'atxHeading',
612
617
  'setextHeading',
613
618
  'table',
614
- 'listItem',
619
+ 'listOrdered',
620
+ 'listUnordered',
615
621
  'blockQuote',
616
622
  'definition',
617
623
  'thematicBreak',
618
624
  'htmlFlow',
619
625
  'codeText',
626
+ 'codeFenced',
620
627
  'link',
621
628
  'image',
622
629
  ]);
@@ -668,6 +675,15 @@ function wrapLines(
668
675
  const indent = indentMatch?.[1] ?? '';
669
676
 
670
677
  const wrapped = wordWrap(trimmed, maxLen, indent);
678
+ // A new line before inline punctuation can turn prose into a heading,
679
+ // list, quote, fence, etc. Keep the source line when wrapping adds syntax.
680
+ if (
681
+ wrapped.length > 1 &&
682
+ markdownLines(wrapped.join('\n'), isBlock, NO_WRAP).size
683
+ ) {
684
+ result.push(line);
685
+ continue;
686
+ }
671
687
  // Keep a Markdown hard break on the last wrapped line
672
688
  if (line.endsWith(' ')) wrapped[wrapped.length - 1] += ' ';
673
689
  result.push(...wrapped);
@@ -198,29 +198,45 @@ export function sameSpindleTokens(before: string, after: string): boolean {
198
198
  }
199
199
 
200
200
  /**
201
- * Put each of `tokens` back in place of its placeholders (those that
202
- * `placeholdersOf` gives for its index): the first of each.
201
+ * Restore the first occurrence of each marker in the unchanged document.
202
+ * Never search inserted source: literals may spell any other marker.
203
203
  */
204
204
  function restorePlaceholders(
205
205
  text: string,
206
- tokens: string[],
207
- placeholdersOf: PlaceholdersOf,
206
+ groups: readonly (readonly [readonly string[], PlaceholdersOf])[],
208
207
  ): string {
209
- let result = text;
210
- tokens.forEach((token, index) => {
211
- for (const placeholder of placeholdersOf(index)) {
212
- // Callback form: a replacement string would expand `$&`, `$'`, etc.
213
- result = result.replace(placeholder, () => token);
214
- }
208
+ const replacements = new Map<string, string>();
209
+ for (const [tokens, placeholdersOf] of groups) {
210
+ tokens.forEach((token, index) => {
211
+ for (const marker of placeholdersOf(index))
212
+ replacements.set(marker, token);
213
+ });
214
+ }
215
+ return text.replace(/<!--(?:SP|SVG):\d+-->|__SP\d+__/g, (marker) => {
216
+ const token = replacements.get(marker);
217
+ replacements.delete(marker);
218
+ // Callback form also preserves literal `$&`, `$'`, etc.
219
+ return token ?? marker;
215
220
  });
216
- return result;
221
+ }
222
+
223
+ /** Restore both families together, so neither can consume the other's source. */
224
+ export function restoreHtmlTokens(
225
+ text: string,
226
+ spindle: string[],
227
+ svg: string[],
228
+ ): string {
229
+ return restorePlaceholders(text, [
230
+ [spindle, SPINDLE_PLACEHOLDERS],
231
+ [svg, SVG_PLACEHOLDERS],
232
+ ]);
217
233
  }
218
234
 
219
235
  /**
220
236
  * Restore SVG blocks from placeholders.
221
237
  */
222
238
  export function restoreSvgBlocks(text: string, tokens: string[]): string {
223
- return restorePlaceholders(text, tokens, SVG_PLACEHOLDERS);
239
+ return restorePlaceholders(text, [[tokens, SVG_PLACEHOLDERS]]);
224
240
  }
225
241
 
226
242
  /**
@@ -312,5 +328,5 @@ export function replaceSpindleTokens(html: string): PlaceholderResult {
312
328
  * Restore original Spindle tokens from placeholders.
313
329
  */
314
330
  export function restoreSpindleTokens(text: string, tokens: string[]): string {
315
- return restorePlaceholders(text, tokens, SPINDLE_PLACEHOLDERS);
331
+ return restorePlaceholders(text, [[tokens, SPINDLE_PLACEHOLDERS]]);
316
332
  }
@@ -15,6 +15,15 @@ export const FrozenStateContext = createContext<
15
15
  ((state: StoryState) => boolean) | null
16
16
  >(null);
17
17
 
18
+ /**
19
+ * Whether a loop has yet to reconcile its rows with newer namespaces.
20
+ * Queued row effects wait for that reconciliation. This differs from a
21
+ * detached click body's permanent freeze: its initial effects still run.
22
+ */
23
+ export const PendingIterationContext = createContext<
24
+ ((state: StoryState) => boolean) | null
25
+ >(null);
26
+
18
27
  /**
19
28
  * Tells a timer ({repeat}, {timed}) whether the passage it belongs to has
20
29
  * been left: it must not run a new body then, for that would write into the
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { assertTrustedWatchers } from '../triggers';
5
5
  import { deserialize, serialize } from '../class-registry';
6
+ import { assertArrayLengths } from '../structural';
6
7
  import { createCounts, hasOwn } from '../utils/namespace';
7
8
  import type { SavePayload } from './types';
8
9
 
@@ -13,6 +14,9 @@ import type { SavePayload } from './types';
13
14
  */
14
15
  export const SAVE_FORMAT_VERSION = 1;
15
16
 
17
+ // Immer and author-facing array methods may scan logical slots, even holes.
18
+ const MAX_SAVE_ARRAY_LENGTH = 1_000_000;
19
+
16
20
  /**
17
21
  * A payload as stored: `data` is the payload serialized in one piece (see
18
22
  * serialize() in class-registry.ts), so values the history moments share
@@ -94,6 +98,7 @@ function variablePathError(err: unknown): unknown {
94
98
  */
95
99
  export function encodePayload(payload: SavePayload): EncodedPayload {
96
100
  try {
101
+ assertArrayLengths(payload, MAX_SAVE_ARRAY_LENGTH);
97
102
  return {
98
103
  formatVersion: SAVE_FORMAT_VERSION,
99
104
  data: serialize({
@@ -211,6 +216,7 @@ export function decodePayload(encoded: unknown): SavePayload {
211
216
  if (typeof data !== 'string') throw invalid();
212
217
  const body = deserialize(migrate(formatVersion, data));
213
218
  if (!isPayload(body)) throw invalid();
219
+ assertArrayLengths(body, MAX_SAVE_ARRAY_LENGTH);
214
220
  assertTrustedWatchers(
215
221
  (body.watchers ?? []) as NonNullable<SavePayload['watchers']>,
216
222
  );
package/src/store.ts CHANGED
@@ -765,17 +765,25 @@ export const subscribeStateReplacement = replacementListeners.subscribe;
765
765
  // Runtime handler cleanup (auto-unsub on restart)
766
766
  // ---------------------------------------------------------------------------
767
767
 
768
- let runtimeUnsubs: Array<() => void> = [];
768
+ let runtimeUnsubs = new Set<() => void>();
769
769
  let inRuntimePhase = false;
770
770
 
771
771
  /**
772
772
  * Track an unsubscribe function for automatic cleanup on restart.
773
- * No-op if called during the startup phase (before enterRuntimePhase).
773
+ * Return its manual cleanup, which also releases the tracked entry.
774
+ * Startup subscriptions (before enterRuntimePhase) survive restart.
774
775
  */
775
- export function trackRuntimeUnsub(unsub: () => void): void {
776
- if (inRuntimePhase) {
777
- runtimeUnsubs.push(unsub);
778
- }
776
+ export function trackRuntimeUnsub(unsub: () => void): () => void {
777
+ if (!inRuntimePhase) return unsub;
778
+ let cleanup: (() => void) | undefined = unsub;
779
+ const tracked = () => {
780
+ const call = cleanup;
781
+ cleanup = undefined;
782
+ runtimeUnsubs.delete(tracked);
783
+ call?.();
784
+ };
785
+ runtimeUnsubs.add(tracked);
786
+ return tracked;
779
787
  }
780
788
 
781
789
  /** Mark the start of the runtime phase. Called before executeStoryInit(). */
@@ -786,13 +794,13 @@ export function enterRuntimePhase(): void {
786
794
  /** Call all tracked unsubs and reset the runtime phase. */
787
795
  function cleanupRuntimeHandlers(): void {
788
796
  for (const unsub of runtimeUnsubs) unsub();
789
- runtimeUnsubs = [];
797
+ runtimeUnsubs.clear();
790
798
  inRuntimePhase = false;
791
799
  }
792
800
 
793
801
  /** Test-only: reset runtime phase state between tests. */
794
802
  export function _resetRuntimePhase(): void {
795
- runtimeUnsubs = [];
803
+ runtimeUnsubs = new Set();
796
804
  inRuntimePhase = false;
797
805
  }
798
806
 
@@ -1417,9 +1425,14 @@ export const useStoryStore = create<StoryState>()(
1417
1425
  }
1418
1426
 
1419
1427
  const previousPassage = get().currentPassage;
1420
- // A callback that restarted or loaded replaced the game this
1421
- // navigation was requested in: it does not carry on into the new one
1422
- if (replacesState(() => emit('beforenavigate', passageName))) return;
1428
+ // A callback may replace the game or move elsewhere. Like a history
1429
+ // traversal, this navigation must then give way to the callback's.
1430
+ const navigation = get().navigationId;
1431
+ if (
1432
+ replacesState(() => emit('beforenavigate', passageName)) ||
1433
+ get().navigationId !== navigation
1434
+ )
1435
+ return;
1423
1436
 
1424
1437
  // Compute variable delta before Immer set(). Read the variables after
1425
1438
  // beforenavigate so changes made by its handlers are recorded.
package/src/story-api.ts CHANGED
@@ -447,8 +447,7 @@ function createStoryAPI(): StoryAPI {
447
447
  ensureVariableChangedSubscription();
448
448
  }
449
449
  const unsub = emitterOn(event, callback);
450
- trackRuntimeUnsub(unsub);
451
- return unsub;
450
+ return trackRuntimeUnsub(unsub);
452
451
  },
453
452
 
454
453
  async waitForActions(): Promise<StoryAction[]> {