@rohal12/spindle 0.60.0 → 0.60.2

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.
@@ -33,12 +33,26 @@ function isHidden(el: Element): boolean {
33
33
  el.hasAttribute('hidden') ||
34
34
  el.getAttribute('aria-hidden') === 'true' ||
35
35
  /(^|;)\s*display\s*:\s*none\b/i.test(el.getAttribute('style') ?? '') ||
36
- NOT_TEXT.has(el.tagName)
36
+ NOT_TEXT.has(el.tagName) ||
37
+ (el.parentElement?.tagName === 'DETAILS' &&
38
+ !el.parentElement.hasAttribute('open') &&
39
+ el !==
40
+ Array.from(el.parentElement.children).find(
41
+ (c) => c.tagName === 'SUMMARY',
42
+ ))
37
43
  );
38
44
  }
39
45
 
40
46
  function formatValue(value: unknown): string {
41
- return JSON.stringify(value) ?? String(value);
47
+ try {
48
+ return JSON.stringify(value) ?? String(value);
49
+ } catch {
50
+ try {
51
+ return String(value);
52
+ } catch {
53
+ return '[unprintable value]';
54
+ }
55
+ }
42
56
  }
43
57
 
44
58
  /** What a control with an action shows: its type, variable and value. */
@@ -108,9 +122,15 @@ export function observableText(el: Element, skip?: string): string {
108
122
  }
109
123
  const block = BLOCKS.has(child.tagName);
110
124
  if (block) endLine();
111
- for (const c of Array.from(child.childNodes)) {
125
+ const closedDetails =
126
+ child.tagName === 'DETAILS' && !child.hasAttribute('open');
127
+ const children = closedDetails
128
+ ? Array.from(child.children).filter((c) => !isHidden(c))
129
+ : Array.from(child.childNodes);
130
+ for (const c of children) {
112
131
  walk(c, inPre || child.tagName === 'PRE');
113
132
  }
133
+ if (child.tagName === 'TD' || child.tagName === 'TH') out += '\t';
114
134
  if (block) endLine();
115
135
  };
116
136
 
@@ -1,6 +1,7 @@
1
1
  // The stored form of a save payload: what saves, exports and the session
2
2
  // hold, and the version of that form.
3
3
 
4
+ import { assertTrustedWatchers } from '../triggers';
4
5
  import { deserialize, serialize } from '../class-registry';
5
6
  import { createCounts } from '../utils/namespace';
6
7
  import type { SavePayload } from './types';
@@ -199,6 +200,9 @@ export function decodePayload(encoded: unknown): SavePayload {
199
200
  if (typeof data !== 'string') throw invalid();
200
201
  const body = deserialize(migrate(formatVersion, data));
201
202
  if (!isPayload(body)) throw invalid();
203
+ assertTrustedWatchers(
204
+ (body.watchers ?? []) as NonNullable<SavePayload['watchers']>,
205
+ );
202
206
  const payload = {
203
207
  ...body,
204
208
  visitCounts: mapToCounts(body.visitCounts),
package/src/store.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  resetTriggers,
24
24
  checkTriggersOnNavigation,
25
25
  restoreMacroWatchers,
26
+ assertTrustedWatchers,
26
27
  interfaceMounted,
27
28
  savedMacroWatchers,
28
29
  reinitTriggerState,
@@ -1838,6 +1839,7 @@ export const useStoryStore = create<StoryState>()(
1838
1839
  // Before anything is replaced: an incompatible payload leaves the
1839
1840
  // running game as it is
1840
1841
  assertPassagesExist(get().storyData, payload);
1842
+ assertTrustedWatchers(payload.watchers ?? []);
1841
1843
  applyReplacement(replacement);
1842
1844
 
1843
1845
  leavingPlaythrough = leaving;
package/src/structural.ts CHANGED
@@ -407,7 +407,7 @@ function equalBuiltin(
407
407
  if (a instanceof RegExp) {
408
408
  return (
409
409
  regExpText(a) === regExpText(b as RegExp) &&
410
- a.lastIndex === (b as RegExp).lastIndex &&
410
+ Object.is(a.lastIndex, (b as RegExp).lastIndex) &&
411
411
  equalExtraKeys(a, b, assumed)
412
412
  );
413
413
  }
package/src/triggers.ts CHANGED
@@ -1,3 +1,7 @@
1
+ import { tokenizeMarkup } from './markup/parse';
2
+ import { parseMacroArgs } from './components/macros/macro-args';
3
+ import { WATCH_PARAMETERS } from './watch-parameters';
4
+ import type { StoryData } from './parser';
1
5
  import { evaluate } from './expression';
2
6
  import { executeMutation, readState } from './execute-mutation';
3
7
  import { useStoryStore } from './store';
@@ -108,10 +112,9 @@ export function addMacroTrigger(
108
112
  condition: string,
109
113
  options: WatchOptions,
110
114
  ): void {
111
- const sortedOptions = Object.fromEntries(
112
- Object.entries(options).sort(([a], [b]) => (a < b ? -1 : 1)),
113
- );
114
- const macroKey = JSON.stringify([condition, sortedOptions]);
115
+ const macroKey = watcherKey(condition, options);
116
+ const story = useStoryStore.getState().storyData;
117
+ if (story) trustedWatchers(story).add(macroKey);
115
118
  if (triggers.some((t) => t.macroKey === macroKey)) return;
116
119
  registerTrigger(condition, options, macroKey);
117
120
  }
@@ -122,6 +125,60 @@ export interface SavedWatcher {
122
125
  options: WatchOptions;
123
126
  }
124
127
 
128
+ /** Canonical identity includes every option, so an imported action cannot change it. */
129
+ function watcherKey(condition: string, options: WatchOptions): string {
130
+ const sorted = Object.fromEntries(
131
+ Object.entries(options).sort(([a], [b]) => (a < b ? -1 : 1)),
132
+ );
133
+ return JSON.stringify([condition, sorted]);
134
+ }
135
+
136
+ // Definitions belong to this story, not a slot or the active trigger list.
137
+ // Remember dynamically registered definitions through unwatch/restart too.
138
+ const definitions = new WeakMap<StoryData, Set<string>>();
139
+
140
+ function trustedWatchers(story: StoryData): Set<string> {
141
+ let known = definitions.get(story);
142
+ if (known) return known;
143
+ known = new Set();
144
+ definitions.set(story, known);
145
+ for (const passage of story.passages.values()) {
146
+ try {
147
+ for (const token of tokenizeMarkup(passage.content)) {
148
+ if (
149
+ token.type !== 'macro' ||
150
+ token.isClose ||
151
+ token.name.toLowerCase() !== 'watch'
152
+ )
153
+ continue;
154
+ const { condition, options } = parseMacroArgs(
155
+ token.rawArgs,
156
+ WATCH_PARAMETERS,
157
+ );
158
+ if (typeof condition === 'string')
159
+ known.add(watcherKey(condition, options));
160
+ }
161
+ } catch {
162
+ // Script passages and malformed markup are not watcher declarations.
163
+ }
164
+ }
165
+ return known;
166
+ }
167
+
168
+ /** Validate all saved definitions before evaluating any of them or replacing state. */
169
+ export function assertTrustedWatchers(watchers: readonly SavedWatcher[]): void {
170
+ if (!watchers.length) return;
171
+ const story = useStoryStore.getState().storyData;
172
+ const known = story && trustedWatchers(story);
173
+ for (const { condition, options } of watchers) {
174
+ if (!known?.has(watcherKey(condition, options))) {
175
+ throw new Error(
176
+ 'Invalid save data: watcher is not defined by this story',
177
+ );
178
+ }
179
+ }
180
+ }
181
+
125
182
  /**
126
183
  * The {watch} macro watchers now registered, for a save or the session:
127
184
  * watchers outlive the passage that declared them, so a game restored
@@ -182,6 +239,7 @@ export function restoreMacroWatchers(
182
239
  watchers: readonly SavedWatcher[],
183
240
  interfaceSaved?: boolean,
184
241
  ): void {
242
+ assertTrustedWatchers(watchers);
185
243
  triggers = triggers.filter((t) => t.macroKey === undefined);
186
244
  for (const { condition, options } of watchers) {
187
245
  addMacroTrigger(condition, options);
@@ -6,7 +6,11 @@
6
6
  * Error its string form (e.g. "Error").
7
7
  */
8
8
  export function errorMessage(err: unknown, fallback?: string): string {
9
- if (err instanceof Error) return err.message || fallback || String(err);
10
- if (typeof err === 'string' && err !== '') return err;
11
- return fallback ?? String(err);
9
+ try {
10
+ if (err instanceof Error) return err.message || fallback || String(err);
11
+ if (typeof err === 'string' && err !== '') return err;
12
+ return fallback ?? String(err);
13
+ } catch {
14
+ return fallback ?? 'Unprintable error';
15
+ }
12
16
  }
@@ -0,0 +1,23 @@
1
+ import type { ParameterDef } from './registry';
2
+
3
+ /** Shared syntax for trusted story declarations and rendered watchers. */
4
+ export const WATCH_PARAMETERS = [
5
+ {
6
+ name: 'condition',
7
+ type: 'string',
8
+ holds: 'expression',
9
+ required: true,
10
+ },
11
+ {
12
+ name: 'options',
13
+ type: 'options',
14
+ parameters: [
15
+ { name: 'goto', type: 'string', holds: 'passage' },
16
+ { name: 'dialog', type: 'string', holds: 'passage' },
17
+ { name: 'run', type: 'string', holds: 'statements' },
18
+ { name: 'name', type: 'string', holds: 'text' },
19
+ { name: 'priority', type: 'number' },
20
+ { name: 'once', type: 'flag' },
21
+ ],
22
+ },
23
+ ] as const satisfies readonly ParameterDef[];