@rohal12/spindle 0.62.3 → 0.62.5

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.
@@ -4328,6 +4328,7 @@ function branchParents(name, macros) {
4328
4328
  function getMacroParameters(name) {
4329
4329
  return metadataRegistry.get(name)?.parameters;
4330
4330
  }
4331
+ getMacroParameters.source = (name) => metadataRegistry.get(name)?.source;
4331
4332
  function getMacroRegistry() {
4332
4333
  return Array.from(metadataRegistry.values());
4333
4334
  }
@@ -4446,6 +4447,8 @@ function pairMarkup(tokens, options = {}) {
4446
4447
  };
4447
4448
  const root = [];
4448
4449
  const stack = [];
4450
+ const openPositions = /* @__PURE__ */ new Map();
4451
+ const tagKey = (tag) => `${tag.type}:${lowerName(tag)}`;
4449
4452
  const add = (node) => (last$1(stack)?.into ?? root).push(node);
4450
4453
  /**
4451
4454
  * End the element on top of the stack, with `close` if it has one: its
@@ -4454,6 +4457,10 @@ function pairMarkup(tokens, options = {}) {
4454
4457
  const end = (ending, close, owns = ending === "closed") => {
4455
4458
  const { node, body } = stack.pop();
4456
4459
  const open = node.token;
4460
+ const key = tagKey(open);
4461
+ const positions = openPositions.get(key);
4462
+ positions.pop();
4463
+ if (positions.length === 0) openPositions.delete(key);
4457
4464
  const noticedAt = close ? close.end : noticedAtEnd;
4458
4465
  for (const { tag } of body.branches) if (open.type !== "macro" || !parentsOf(tag.name).includes(lowerName(open))) misplaced(tag, open, noticedAt);
4459
4466
  if (ending === "unclosed") report("unclosed-block", open, `Unclosed ${tagLabel(open)}: no ${closerOf(open)} closes it`, noticedAt, { name: nameOf(open) });
@@ -4472,8 +4479,7 @@ function pairMarkup(tokens, options = {}) {
4472
4479
  if (!top) report("stray-closer", token, `${tagLabel(token)} closes nothing: no ${token.type === "html" ? `<${token.tag}>` : `{${token.name}}`} is open here`, token.start, { name: nameOf(token) });
4473
4480
  else if (closes(top.node.token, token)) end("closed", token);
4474
4481
  else {
4475
- let outer = stack.length - 1;
4476
- while (outer >= 0 && !closes(stack[outer].node.token, token)) outer--;
4482
+ const outer = last$1(openPositions.get(tagKey(token)) ?? []) ?? -1;
4477
4483
  end("mismatch", token, outer === -1);
4478
4484
  if (outer !== -1) {
4479
4485
  while (stack.length > outer + 1) end("cut", token);
@@ -4517,6 +4523,10 @@ function pairMarkup(tokens, options = {}) {
4517
4523
  branches: []
4518
4524
  };
4519
4525
  node.body = body;
4526
+ const key = tagKey(token);
4527
+ const positions = openPositions.get(key) ?? [];
4528
+ positions.push(stack.length);
4529
+ openPositions.set(key, positions);
4520
4530
  stack.push({
4521
4531
  node,
4522
4532
  body,
@@ -10747,6 +10757,40 @@ function jsCodeEnd(onOpenEnd) {
10747
10757
  }
10748
10758
  /** The JavaScript reader Spindle uses today: js-lexer, then a lenient scan. */
10749
10759
  var defaultCodeEnd = jsCodeEnd();
10760
+ /**
10761
+ * Index possible brace ends for repeated recovery attempts in one template.
10762
+ * Within plain code, nested braces must close first. At a quote, slash or
10763
+ * escape we stop making lexical assumptions, but the remaining raw `}`s
10764
+ * still bound how many pending braces could close. Indexing visits each
10765
+ * opener once, so unmatched plain-code openers can skip suffix scans.
10766
+ */
10767
+ function indexCodeEnds(input) {
10768
+ const possible = /* @__PURE__ */ new Set();
10769
+ const pending = [];
10770
+ let remaining = 0;
10771
+ let lastBrace = -1;
10772
+ for (let i = 0; i < input.length; i++) if (input[i] === "}") {
10773
+ remaining++;
10774
+ lastBrace = i;
10775
+ }
10776
+ const uncertain = () => {
10777
+ for (let i = Math.max(0, pending.length - remaining); i < pending.length; i++) possible.add(pending[i]);
10778
+ pending.length = 0;
10779
+ };
10780
+ for (let i = 0; i < input.length; i++) {
10781
+ const c = input[i];
10782
+ if (c === "{") pending.push(i);
10783
+ else if (c === "}") {
10784
+ remaining--;
10785
+ const open = pending.pop();
10786
+ if (open !== void 0) possible.add(open);
10787
+ } else if (/['"`/\\]/.test(c)) uncertain();
10788
+ }
10789
+ return (start) => {
10790
+ if (start > lastBrace) return -1;
10791
+ return possible.has(start - 1) ? defaultCodeEnd.closeBrace(input, start, start) : parsedCodeEnd(input, start, "expression");
10792
+ };
10793
+ }
10750
10794
  //#endregion
10751
10795
  //#region src/markup/code-attributes.ts
10752
10796
  /**
@@ -10772,6 +10816,7 @@ function splitSigilTemplate(template, incomplete = false) {
10772
10816
  const parts = [];
10773
10817
  let text = "";
10774
10818
  let i = 0;
10819
+ const closeBrace = indexCodeEnds(template);
10775
10820
  while (i < template.length) {
10776
10821
  const brace = template.indexOf("{", i);
10777
10822
  if (brace === -1) {
@@ -10780,7 +10825,7 @@ function splitSigilTemplate(template, incomplete = false) {
10780
10825
  }
10781
10826
  text += template.slice(i, brace);
10782
10827
  i = brace + 1;
10783
- let end = isSigil(template[i]) ? defaultCodeEnd.closeBrace(template, i, i) : -1;
10828
+ let end = isSigil(template[i]) ? closeBrace(i) : -1;
10784
10829
  if (end === -1 && incomplete && isSigil(template[i])) end = template.length;
10785
10830
  if (end === -1) {
10786
10831
  text += "{";
@@ -11822,6 +11867,10 @@ function widgetParameters(params, holds = {}) {
11822
11867
  ...hasOwn(holds, name) ? { holds: holds[name] } : {}
11823
11868
  }));
11824
11869
  }
11870
+ /** A raw body is executable only while the builtin implementation owns it. */
11871
+ function executesRawBody(name, parametersOf) {
11872
+ return isRawMacro(name, parametersOf.widget?.(name) !== void 0) && parametersOf.source?.(name) !== "user";
11873
+ }
11825
11874
  /**
11826
11875
  * `params` with each `string` and `text` parameter (options too) saying
11827
11876
  * what it holds: what it declares, else `holds`.
@@ -11849,7 +11898,9 @@ function withHolds(params, holds) {
11849
11898
  function parameterLookup(macros) {
11850
11899
  const parameters = new NameMap();
11851
11900
  const widgets = new NameMap();
11852
- for (const { name, parameters: params, interpolate, widget } of macros) {
11901
+ const sources = new NameMap();
11902
+ for (const { name, parameters: params, interpolate, widget, source } of macros) {
11903
+ sources.set(name, source ?? "user");
11853
11904
  if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
11854
11905
  if (widget) widgets.set(name, widgetParameters(widget.params, widget.holds) ?? []);
11855
11906
  }
@@ -11863,6 +11914,7 @@ function parameterLookup(macros) {
11863
11914
  return params;
11864
11915
  };
11865
11916
  if (widgets.size > 0) lookup.widget = (name) => widgets.get(name);
11917
+ lookup.source = (name) => sources.get(name);
11866
11918
  return lookup;
11867
11919
  }
11868
11920
  /** What a `string` or `text` argument holds when its parameter doesn't say. */
@@ -11928,7 +11980,7 @@ function* codeAndText(src, tokens, parametersOf) {
11928
11980
  else if (token.type === "macro" && !token.isClose) {
11929
11981
  const name = token.name.toLowerCase();
11930
11982
  const widget = parametersOf.widget?.(name);
11931
- if (name === "do" && !widget) {
11983
+ if (executesRawBody(name, parametersOf)) {
11932
11984
  const close = closeOfTextBody(t, name);
11933
11985
  if (close < 0) continue;
11934
11986
  yield {
@@ -12289,6 +12341,7 @@ function locate(text, part, from) {
12289
12341
  //#region src/widgets/ast-scanner.ts
12290
12342
  /** The declared parameters of the macros registered so far. */
12291
12343
  var registeredParameters = (name) => parameterLookup(getMacroRegistry())(name);
12344
+ registeredParameters.source = getMacroParameters.source;
12292
12345
  /**
12293
12346
  * Whether the text of an attribute value or macro label renders a
12294
12347
  * `{@children}`: it is markup, parsed as the renderer parses it.
@@ -13144,7 +13197,6 @@ var TextEvaluator = class {
13144
13197
  }, depth + 1);
13145
13198
  }
13146
13199
  macro(node, scope, depth) {
13147
- if (isSubMacro(node.name)) return "";
13148
13200
  const widget = getWidget(node.name);
13149
13201
  if (widget) {
13150
13202
  let locals = scope.locals;
@@ -13167,6 +13219,7 @@ var TextEvaluator = class {
13167
13219
  widgetChildren: widgetChildrenOf(node.children, scope.widgetChildren)
13168
13220
  });
13169
13221
  }
13222
+ if (isSubMacro(node.name)) return "";
13170
13223
  const text = getMacroText(node.name);
13171
13224
  if (!text) {
13172
13225
  const message = getMacro(node.name) ? `{${node.name}} has no text form, so it can't be used in an attribute value or label` : `unknown macro {${node.name}}`;
@@ -13476,6 +13529,7 @@ function useRenderOptions() {
13476
13529
  inline: useContext(InlineContext),
13477
13530
  raw: useContext(RawTextContext),
13478
13531
  structural: useContext(StructuralContext),
13532
+ preserveEdges: true,
13479
13533
  locals: useContext(LocalsValuesContext)
13480
13534
  };
13481
13535
  }
@@ -14376,7 +14430,6 @@ function nodeKey(node) {
14376
14430
  return key;
14377
14431
  }
14378
14432
  function renderMacro(node, key) {
14379
- if (isSubMacro(node.name)) return null;
14380
14433
  const invocation = {
14381
14434
  rawArgs: node.rawArgs,
14382
14435
  className: node.className,
@@ -14389,6 +14442,7 @@ function renderMacro(node, key) {
14389
14442
  params: widget.params,
14390
14443
  invocationChildren: node.children
14391
14444
  }, key);
14445
+ if (isSubMacro(node.name)) return null;
14392
14446
  const Component = getMacro(node.name);
14393
14447
  if (Component) return /* @__PURE__ */ jsx(Component, {
14394
14448
  ...invocation,
@@ -14518,7 +14572,7 @@ function renderNodes(nodes, options) {
14518
14572
  const lead = combined.slice(0, skipChars(combined, 0, 1, EDGE_WS));
14519
14573
  const trail = lead.length === combined.length ? "" : combined.slice(skipChars(combined, combined.length, -1, EDGE_WS));
14520
14574
  const core = combined.slice(lead.length, combined.length - trail.length);
14521
- const edges = (content) => unwrapParagraphs && (lead || trail) ? /* @__PURE__ */ jsxs(Fragment$1, { children: [
14575
+ const edges = (content) => (unwrapParagraphs || options?.preserveEdges) && (lead || trail) ? /* @__PURE__ */ jsxs(Fragment$1, { children: [
14522
14576
  lead,
14523
14577
  content,
14524
14578
  trail
@@ -18333,8 +18387,14 @@ function establishPlaythrough(ifid) {
18333
18387
  function saveWithHooks(slot, custom, beginCapture, write) {
18334
18388
  try {
18335
18389
  const capture = beginCapture();
18336
- withoutDraws(() => emit("beforesave", slot, custom));
18337
- return write(capture()).then((result) => {
18390
+ let payload;
18391
+ try {
18392
+ withoutDraws(() => emit("beforesave", slot, custom));
18393
+ payload = capture();
18394
+ } finally {
18395
+ capture.dispose();
18396
+ }
18397
+ return write(payload).then((result) => {
18338
18398
  withoutDraws(() => emit("aftersave", slot));
18339
18399
  return result;
18340
18400
  });
@@ -19254,6 +19314,7 @@ function freshTransients(defaults) {
19254
19314
  function enterStart(state, passage, variables, transientDefaults) {
19255
19315
  state.currentPassage = passage;
19256
19316
  state.navigationId++;
19317
+ state.replacementNavigationId = state.navigationId;
19257
19318
  state.variables = variables;
19258
19319
  state.transient = freshTransients(transientDefaults);
19259
19320
  state.temporary = createNamespace();
@@ -19526,10 +19587,10 @@ function loadedEntryMoment(payload) {
19526
19587
  return moment;
19527
19588
  }
19528
19589
  /** The variable paths `Story.set` writes while a save's hooks run. */
19529
- var hookWrites = null;
19590
+ var hookWrites = /* @__PURE__ */ new Set();
19530
19591
  /** Note that `path` of the variables was written (see keepHookWrites). */
19531
19592
  function recordHookWrite(path) {
19532
- hookWrites?.set(pathKey(path), path);
19593
+ for (const writes of hookWrites) writes.set(pathKey(path), path);
19533
19594
  }
19534
19595
  /**
19535
19596
  * Write the changes between `before` and `after` (the live variables around
@@ -19772,6 +19833,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
19772
19833
  storyData: null,
19773
19834
  currentPassage: "",
19774
19835
  navigationId: 0,
19836
+ replacementNavigationId: 0,
19775
19837
  variables: createNamespace(),
19776
19838
  variableDefaults: {},
19777
19839
  transient: createNamespace(),
@@ -20087,14 +20149,17 @@ var useStoryStore = create()(storyStore((set, get) => ({
20087
20149
  const before = get().variables;
20088
20150
  const replaced = latestStateApplied;
20089
20151
  const writes = /* @__PURE__ */ new Map();
20090
- hookWrites = writes;
20091
- return () => {
20092
- if (hookWrites === writes) hookWrites = null;
20152
+ hookWrites.add(writes);
20153
+ const dispose = () => {
20154
+ hookWrites.delete(writes);
20155
+ };
20156
+ return Object.assign(() => {
20157
+ dispose();
20093
20158
  if (latestStateApplied !== replaced) throw new Error("spindle: a beforesave handler restarted or loaded the game, so the save was not made");
20094
20159
  const payload = get().getSavePayload();
20095
20160
  keepHookWrites(payload, before, get().variables, [...writes.values()]);
20096
20161
  return payload;
20097
- };
20162
+ }, { dispose });
20098
20163
  },
20099
20164
  loadFromPayload: (payload, slot, playthroughId, issued) => {
20100
20165
  const applying = slotLoadApplying ?? issued;
@@ -20138,6 +20203,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20138
20203
  set((state) => {
20139
20204
  state.currentPassage = payload.passage;
20140
20205
  state.navigationId++;
20206
+ state.replacementNavigationId = state.navigationId;
20141
20207
  state.variables = createNamespace(deepClone(entry?.variables ?? payload.variables));
20142
20208
  state.history = retained.map((m) => ({
20143
20209
  passage: m.passage,
@@ -23135,7 +23201,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
23135
23201
  });
23136
23202
  } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
23137
23203
  }
23138
- if (token.name.toLowerCase() === "do" && !parametersOf.widget?.(token.name)) {
23204
+ if (executesRawBody(token.name, parametersOf)) {
23139
23205
  let close = t + 1;
23140
23206
  while (close < tokens.length) {
23141
23207
  const c = tokens[close];
@@ -23886,7 +23952,6 @@ defineMacro({
23886
23952
  id: navigationId
23887
23953
  });
23888
23954
  const resolvedTypeRef = useRef("fade");
23889
- const prevHistoryLenRef = useRef(0);
23890
23955
  const displayedId = displayed.id;
23891
23956
  const isOutgoing = useCallback((state) => state.navigationId !== displayedId, [displayedId]);
23892
23957
  const hasLeft = useCallback(() => isOutgoing(useStoryStore.getState()), [isOutgoing]);
@@ -23910,12 +23975,9 @@ defineMacro({
23910
23975
  }, [cancelTransition]);
23911
23976
  useEffect(() => {
23912
23977
  const store = useStoryStore.getState();
23913
- const { history, historyIndex, transitionConfig } = store;
23914
- const prevLen = prevHistoryLenRef.current;
23915
- prevHistoryLenRef.current = history.length;
23978
+ const { replacementNavigationId, transitionConfig } = store;
23916
23979
  const isFirstLoad = !displayedPassage;
23917
- const isRestart = history.length === 1 && historyIndex === 0 && prevLen > 1;
23918
- const isLoad = history.length > 1 && historyIndex === history.length - 1 && prevLen > 1 && Math.abs(history.length - prevLen) > 1;
23980
+ const isReplacement = navigationId === replacementNavigationId;
23919
23981
  if (navigationId === displayed.id) return;
23920
23982
  const next = store.consumeNextTransition();
23921
23983
  cancelTransition();
@@ -23925,7 +23987,7 @@ defineMacro({
23925
23987
  setDisplayedPassage(currentPassage);
23926
23988
  return;
23927
23989
  }
23928
- if (isFirstLoad || isRestart || isLoad) {
23990
+ if (isFirstLoad || isReplacement) {
23929
23991
  resolvedTypeRef.current = "fade";
23930
23992
  setDisplayedPassage(currentPassage);
23931
23993
  return;
@@ -36,6 +36,56 @@ async function loadOptional(pkg, feature, importer = defaultImporter) {
36
36
  }
37
37
  }
38
38
  //#endregion
39
+ //#region src/play/window-events.ts
40
+ /** Expose the story's global window at the DOM event boundary. */
41
+ function installWindowEvents(window) {
42
+ const storyWindow = globalThis;
43
+ const wrapped = /* @__PURE__ */ new WeakMap();
44
+ const originals = /* @__PURE__ */ new WeakMap();
45
+ const wrap = (listener) => {
46
+ if (typeof listener !== "function") return listener;
47
+ let callback = wrapped.get(listener);
48
+ if (!callback) {
49
+ callback = listener.bind(storyWindow);
50
+ wrapped.set(listener, callback);
51
+ originals.set(callback, listener);
52
+ }
53
+ return callback;
54
+ };
55
+ const { addEventListener, removeEventListener } = window;
56
+ window.addEventListener = (type, listener, options) => addEventListener(type, wrap(listener), options);
57
+ window.removeEventListener = (type, listener) => removeEventListener(type, wrapped.get(listener) ?? listener);
58
+ for (const name of Object.getOwnPropertyNames(window)) {
59
+ const descriptor = Object.getOwnPropertyDescriptor(window, name);
60
+ if (!name.startsWith("on") || !descriptor.get || !descriptor.set) continue;
61
+ Object.defineProperty(window, name, {
62
+ ...descriptor,
63
+ get() {
64
+ const listener = descriptor.get.call(window);
65
+ return originals.get(listener) ?? listener;
66
+ },
67
+ set(listener) {
68
+ descriptor.set.call(window, wrap(listener));
69
+ }
70
+ });
71
+ }
72
+ const exposeWindow = (target) => target === window ? storyWindow : target;
73
+ const prototype = window.Event.prototype;
74
+ for (const name of ["target", "currentTarget"]) {
75
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
76
+ Object.defineProperty(prototype, name, {
77
+ ...descriptor,
78
+ get() {
79
+ return exposeWindow(descriptor.get.call(this));
80
+ }
81
+ });
82
+ }
83
+ const { composedPath } = prototype;
84
+ prototype.composedPath = function() {
85
+ return composedPath.call(this).map((target) => target === window ? storyWindow : target);
86
+ };
87
+ }
88
+ //#endregion
39
89
  //#region src/play/worker.ts
40
90
  /**
41
91
  * The worker thread of a play session: boots the story on happy-dom and
@@ -49,30 +99,68 @@ Object.defineProperty(process, "stdout", {
49
99
  });
50
100
  var port = parentPort;
51
101
  var data = workerData;
52
- /** Make happy-dom's window the global environment Spindle runs in. */
102
+ /** Install happy-dom's DOM in the global environment Spindle runs in. */
53
103
  async function installDom() {
54
104
  const { Window } = await loadOptional("happy-dom", "play sessions");
55
105
  const window = new Window({ url: "http://localhost/" });
106
+ installWindowEvents(window);
56
107
  const global = globalThis;
57
108
  const source = window;
58
- global.window = window;
59
109
  global.document = window.document;
60
- for (const name of Object.getOwnPropertyNames(window)) if (!(name in globalThis)) global[name] = source[name];
110
+ for (const name of Object.getOwnPropertyNames(window)) if (!(name in globalThis)) Object.defineProperty(globalThis, name, Object.getOwnPropertyDescriptor(window, name));
61
111
  for (const name of HAPPY_DOM_GLOBALS) Object.defineProperty(globalThis, name, {
62
112
  configurable: true,
63
113
  writable: true,
64
114
  value: source[name]
65
115
  });
66
- Object.defineProperty(globalThis, "BroadcastChannel", {
116
+ for (const name of [
117
+ "window",
118
+ "self",
119
+ "parent",
120
+ "top",
121
+ "frames"
122
+ ]) Object.defineProperty(globalThis, name, {
67
123
  configurable: true,
68
124
  writable: true,
69
- value: void 0
125
+ value: globalThis
70
126
  });
71
- Object.defineProperty(globalThis, "Story", {
127
+ Object.defineProperty(window, "Story", {
72
128
  configurable: true,
73
- get: () => source.Story
129
+ get: () => global.Story,
130
+ set: (value) => {
131
+ global.Story = value;
132
+ }
133
+ });
134
+ installIdleCallbacks();
135
+ Object.defineProperty(globalThis, "BroadcastChannel", {
136
+ configurable: true,
137
+ writable: true,
138
+ value: void 0
74
139
  });
75
140
  }
141
+ /** happy-dom has no idle scheduler; yield to a timer with a 50 ms budget. */
142
+ function installIdleCallbacks() {
143
+ const timers = /* @__PURE__ */ new Map();
144
+ let nextHandle = 0;
145
+ globalThis.requestIdleCallback = (callback, options) => {
146
+ const handle = ++nextHandle;
147
+ const requested = performance.now();
148
+ timers.set(handle, setTimeout(() => {
149
+ timers.delete(handle);
150
+ const started = performance.now();
151
+ const didTimeout = options?.timeout !== void 0 && started - requested >= options.timeout;
152
+ callback({
153
+ didTimeout,
154
+ timeRemaining: () => didTimeout ? 0 : Math.max(0, 50 - (performance.now() - started))
155
+ });
156
+ }, 1));
157
+ return handle;
158
+ };
159
+ globalThis.cancelIdleCallback = (handle) => {
160
+ clearTimeout(timers.get(handle));
161
+ timers.delete(handle);
162
+ };
163
+ }
76
164
  /**
77
165
  * Globals happy-dom's window replaces even where Node has its own:
78
166
  * - the event classes: happy-dom's dispatchEvent() refuses events made with
package/dist/pkg/play.js CHANGED
@@ -192,9 +192,9 @@ function workerExecArgv(execArgv) {
192
192
  return kept;
193
193
  }
194
194
  /**
195
- * Opens a session that runs the story in a worker. There `window` is
196
- * happy-dom's window, not `globalThis`: story code sees `Story` and the DOM
197
- * globals, but `window.foo = 1` does not make a bare global `foo`.
195
+ * Opens a session that runs the story in a worker with happy-dom's DOM.
196
+ * `window` is `globalThis`: properties authored on it are bare globals too.
197
+ * Idle callbacks use a timer-backed scheduler.
198
198
  * Requires `trusted: true`: story code has unrestricted host Node access.
199
199
  */
200
200
  function openPlaySession(options) {