@aftertext/player 0.3.0 → 0.4.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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  A small headless player layer that threads an active AfterText runtime session
4
4
  one observable step at a time.
5
5
 
6
- > v0.3.0: the public API is early and may change.
6
+ > v0.4.0: the public API is early and may change.
7
7
 
8
8
  ## Install
9
9
 
@@ -27,6 +27,43 @@ console.log(player.current);
27
27
  The player delegates narrative semantics to `@aftertext/runtime`; it does not
28
28
  skip content, navigation, choices, or presentation results.
29
29
 
30
+ ## Save and restore
31
+
32
+ `snapshotPlayer` creates a JSON-compatible `PlayerSnapshot` of a `PlayerState`;
33
+ `restorePlayer` validates and reconstructs one. Both are pure and synchronous.
34
+
35
+ ```ts
36
+ import { restorePlayer, snapshotPlayer } from "@aftertext/player";
37
+
38
+ const snapshot = snapshotPlayer(document, player);
39
+ const serialized = JSON.stringify(snapshot);
40
+
41
+ const result = restorePlayer(document, JSON.parse(serialized));
42
+ if (result.ok) {
43
+ player = result.state;
44
+ } else {
45
+ console.error(result.error);
46
+ }
47
+ ```
48
+
49
+ - `snapshotPlayer` produces a plain `PlayerSnapshot`; `JSON.stringify`/
50
+ `JSON.parse` round-trip it directly, with no AfterText-specific encoding
51
+ step.
52
+ - `restorePlayer` accepts `snapshot: unknown` — it validates its input and
53
+ never throws, returning `{ ok: false, error }` for any malformed or
54
+ invalid input instead (errors-as-data, not exceptions).
55
+ - A snapshot taken against one document is rejected (`documentMismatch`) if
56
+ restored against a different, semantically changed document.
57
+ - Storage is entirely host-owned: this package has no save slots, no
58
+ storage backend, and no autosave. Where the serialized value lives is
59
+ the host's decision.
60
+ - A `PlayerSnapshot`'s `position`/`current` fields are public but opaque —
61
+ store and restore them verbatim; do not depend on their internal shape,
62
+ which is not guaranteed to stay the same across future package versions.
63
+ - `formatVersion` is used to validate a snapshot's shape, but this package
64
+ makes no promise that a snapshot taken by one version will restore
65
+ correctly on a later version.
66
+
30
67
  ## License
31
68
 
32
69
  MIT
@@ -0,0 +1,12 @@
1
+ import type { StoryDocument } from "@aftertext/compiler";
2
+ /**
3
+ * Computes a deterministic, browser-portable fingerprint from every
4
+ * execution/rendering-relevant authored semantic value in `document`
5
+ * (docs/CORE_SPEC.md Section 33.5) — explicitly excluding `SourceSpan`/
6
+ * `*Span`/`*Position` metadata and `metadata.title`/`metadata.entry`
7
+ * (neither is read anywhere in the compiled execution/rendering path).
8
+ * `entryScene` itself is included; `metadata.entry` is not the same field
9
+ * and is excluded.
10
+ */
11
+ export declare function computeDocumentFingerprint(document: StoryDocument): string;
12
+ //# sourceMappingURL=document-fingerprint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document-fingerprint.d.ts","sourceRoot":"","sources":["../src/document-fingerprint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAUV,aAAa,EAGd,MAAM,qBAAqB,CAAC;AA4J7B;;;;;;;;GAQG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,aAAa,GAAG,MAAM,CAQ1E"}
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Compile-time exhaustiveness guard: every canonicalizer below ends with
3
+ * this instead of an unconditional fallback `return`, so that adding a
4
+ * new AST discriminant variant without updating its canonicalizer is a
5
+ * TYPE ERROR here, not a silently-wrong fingerprint (docs/CORE_SPEC.md
6
+ * Section 33.5 — a missing semantic field must never be excluded merely
7
+ * because fingerprinting didn't notice it was added).
8
+ */
9
+ function unhandledVariant(value) {
10
+ throw new Error(`document-fingerprint: unhandled AST variant: ${JSON.stringify(value)}`);
11
+ }
12
+ /**
13
+ * Deterministic 64-bit FNV-1a hash over a string's UTF-16 code units, each
14
+ * fed as two bytes (high byte then low byte, a fixed order — the specific
15
+ * order is arbitrary but must never change, since changing it would
16
+ * silently change every existing fingerprint). Pure `bigint` arithmetic
17
+ * (docs/CORE_SPEC.md Section 33.5): no `node:crypto`, no WebCrypto, no
18
+ * external package, so this remains portable to every supported JS
19
+ * environment including browsers. This is a defensive mismatch detector,
20
+ * not a cryptographic guarantee (Section 33.5's own collision caveat).
21
+ */
22
+ const FNV_OFFSET_BASIS_64 = 0xcbf29ce484222325n;
23
+ const FNV_PRIME_64 = 0x100000001b3n;
24
+ const MASK_64 = 0xffffffffffffffffn;
25
+ function fnv1a64Hex(input) {
26
+ let hash = FNV_OFFSET_BASIS_64;
27
+ for (let i = 0; i < input.length; i++) {
28
+ const code = input.charCodeAt(i); // NOSONAR(typescript:S7758) — intentional UTF-16 code-unit iteration, not text processing; see comment above
29
+ const highByte = BigInt((code >> 8) & 0xff);
30
+ const lowByte = BigInt(code & 0xff);
31
+ hash = ((hash ^ highByte) * FNV_PRIME_64) & MASK_64;
32
+ hash = ((hash ^ lowByte) * FNV_PRIME_64) & MASK_64;
33
+ }
34
+ return hash.toString(16).padStart(16, "0");
35
+ }
36
+ /** Tags an authored-optional value so its absence never collides with a present value of any type, including an authored `0`/`false`/`""` (docs/CORE_SPEC.md Section 33.5). */
37
+ function optional(value) {
38
+ return value === undefined ? ["none"] : ["some", value];
39
+ }
40
+ /** Type-tags a primitive authored value so `"1"`, `1`, `true`, `"true"`, and `null` can never canonicalize to the same representation. */
41
+ function canonicalizeTypedPrimitive(value) {
42
+ if (value === null)
43
+ return ["null"];
44
+ if (typeof value === "string")
45
+ return ["string", value];
46
+ if (typeof value === "boolean")
47
+ return ["boolean", value];
48
+ return ["number", value];
49
+ }
50
+ function canonicalizeExpression(node) {
51
+ if (node.type === "Literal")
52
+ return ["Literal", canonicalizeTypedPrimitive(node.value)];
53
+ if (node.type === "Identifier")
54
+ return ["Identifier", node.name];
55
+ if (node.type === "Unary")
56
+ return ["Unary", node.operator, canonicalizeExpression(node.argument)];
57
+ if (node.type === "Binary") {
58
+ return ["Binary", node.operator, canonicalizeExpression(node.left), canonicalizeExpression(node.right)];
59
+ }
60
+ if (node.type === "Call")
61
+ return ["Call", node.callee, node.args.map(canonicalizeExpression)];
62
+ return unhandledVariant(node);
63
+ }
64
+ function canonicalizeInline(node) {
65
+ if (node.type === "Text")
66
+ return ["Text", node.value];
67
+ if (node.type === "Emphasis")
68
+ return ["Emphasis", node.children.map(canonicalizeInline)];
69
+ if (node.type === "Strong")
70
+ return ["Strong", node.children.map(canonicalizeInline)];
71
+ if (node.type === "InlineCode")
72
+ return ["InlineCode", node.value];
73
+ if (node.type === "Link")
74
+ return ["Link", node.url, node.children.map(canonicalizeInline)];
75
+ if (node.type === "LineBreak")
76
+ return ["LineBreak"];
77
+ return unhandledVariant(node);
78
+ }
79
+ function canonicalizePresentationCommand(command) {
80
+ if (command.type === "Background")
81
+ return ["Background", command.image];
82
+ if (command.type === "Layer")
83
+ return ["Layer", command.image];
84
+ if (command.type === "Camera")
85
+ return ["Camera", command.action, command.to, optional(command.durationMs)];
86
+ if (command.type === "Music")
87
+ return ["Music", command.track, optional(command.volume)];
88
+ if (command.type === "Sfx")
89
+ return ["Sfx", command.clip];
90
+ if (command.type === "Pause")
91
+ return ["Pause", command.durationMs];
92
+ if (command.type === "ShowSprite")
93
+ return ["ShowSprite", command.id, command.image, command.position];
94
+ if (command.type === "HideSprite")
95
+ return ["HideSprite", command.id];
96
+ return unhandledVariant(command);
97
+ }
98
+ function canonicalizeConditionExpression(condition) {
99
+ return condition ? ["some", canonicalizeExpression(condition)] : ["none"];
100
+ }
101
+ function canonicalizeChoiceItem(item) {
102
+ return ["ChoiceItem", item.text, item.target, canonicalizeConditionExpression(item.condition)];
103
+ }
104
+ function canonicalizeConditionalBranch(branch) {
105
+ return ["ConditionalBranch", branch.kind, canonicalizeConditionExpression(branch.condition), branch.blocks.map(canonicalizeBlock)];
106
+ }
107
+ function canonicalizeVariantBranch(branch) {
108
+ return [
109
+ "VariantBranch",
110
+ branch.kind,
111
+ branch.branchId,
112
+ canonicalizeConditionExpression(branch.condition),
113
+ branch.blocks.map(canonicalizeBlock)
114
+ ];
115
+ }
116
+ /**
117
+ * Covers every current `StoryBlock` variant (docs/CORE_SPEC.md Section
118
+ * 33.5) — Paragraph/Heading inline content, Dialogue speaker/content,
119
+ * Presentation's full authored command, Set name/expression, Goto target,
120
+ * Choice items, and Conditional/Variant branch semantics including their
121
+ * nested `blocks`. Never reads a `*Span`/`span` field anywhere.
122
+ */
123
+ function canonicalizeBlock(block) {
124
+ if (block.type === "Paragraph")
125
+ return ["Paragraph", block.children.map(canonicalizeInline)];
126
+ if (block.type === "Heading")
127
+ return ["Heading", block.depth, block.children.map(canonicalizeInline)];
128
+ if (block.type === "Dialogue")
129
+ return ["Dialogue", block.speaker, block.content.map(canonicalizeInline)];
130
+ if (block.type === "Presentation")
131
+ return ["Presentation", canonicalizePresentationCommand(block.command)];
132
+ if (block.type === "Set")
133
+ return ["Set", block.name, canonicalizeExpression(block.expression)];
134
+ if (block.type === "Goto")
135
+ return ["Goto", block.target];
136
+ if (block.type === "Choice")
137
+ return ["Choice", block.items.map(canonicalizeChoiceItem)];
138
+ if (block.type === "Conditional")
139
+ return ["Conditional", block.branches.map(canonicalizeConditionalBranch)];
140
+ if (block.type === "Variant")
141
+ return ["Variant", block.id, block.branches.map(canonicalizeVariantBranch)];
142
+ return unhandledVariant(block);
143
+ }
144
+ function canonicalizeScene(scene) {
145
+ return ["Scene", scene.id, scene.blocks.map(canonicalizeBlock)];
146
+ }
147
+ /**
148
+ * Ordinal (not locale-aware) string comparison, explicit rather than
149
+ * relying on `Array.prototype.sort()`'s own unspecified-by-omission
150
+ * default: this fingerprint must be deterministic across every JS
151
+ * environment (docs/CORE_SPEC.md Section 33.5), so the key order here
152
+ * must never depend on the host's locale/ICU data the way
153
+ * `String#localeCompare` would. Produces the exact same UTF-16-code-unit
154
+ * order the engine's own default string sort already uses — this is an
155
+ * explicitness fix, not a behavior change.
156
+ */
157
+ function compareOrdinal(a, b) {
158
+ if (a < b)
159
+ return -1;
160
+ if (a > b)
161
+ return 1;
162
+ return 0;
163
+ }
164
+ /** Sorted-key canonicalization (docs/CORE_SPEC.md Section 33.5): `initialState` is an unordered authored map, so authored key order must never affect the fingerprint, unlike every array-shaped field above. */
165
+ function canonicalizeInitialState(initialState) {
166
+ return Object.keys(initialState)
167
+ .sort(compareOrdinal)
168
+ .map((key) => [key, canonicalizeTypedPrimitive(initialState[key])]);
169
+ }
170
+ /**
171
+ * Computes a deterministic, browser-portable fingerprint from every
172
+ * execution/rendering-relevant authored semantic value in `document`
173
+ * (docs/CORE_SPEC.md Section 33.5) — explicitly excluding `SourceSpan`/
174
+ * `*Span`/`*Position` metadata and `metadata.title`/`metadata.entry`
175
+ * (neither is read anywhere in the compiled execution/rendering path).
176
+ * `entryScene` itself is included; `metadata.entry` is not the same field
177
+ * and is excluded.
178
+ */
179
+ export function computeDocumentFingerprint(document) {
180
+ const canonical = [
181
+ "StoryDocument",
182
+ document.entryScene,
183
+ canonicalizeInitialState(document.initialState),
184
+ document.scenes.map(canonicalizeScene)
185
+ ];
186
+ return `fnv1a64:${fnv1a64Hex(JSON.stringify(canonical))}`;
187
+ }
188
+ //# sourceMappingURL=document-fingerprint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document-fingerprint.js","sourceRoot":"","sources":["../src/document-fingerprint.ts"],"names":[],"mappings":"AAgBA;;;;;;;GAOG;AACH,SAAS,gBAAgB,CAAC,KAAY;IACpC,MAAM,IAAI,KAAK,CAAC,gDAAgD,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAC3F,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAChD,MAAM,YAAY,GAAG,cAAc,CAAC;AACpC,MAAM,OAAO,GAAG,mBAAmB,CAAC;AAEpC,SAAS,UAAU,CAAC,KAAa;IAC/B,IAAI,IAAI,GAAG,mBAAmB,CAAC;IAC/B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,IAAI,GA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AC1C,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,CAAC,CAAC,CAAC;IACrB,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,CAAC,CAAC;IACpB,OAAO,CAAC,CAAC;AACX,CAAC;AAED,iNAAiN;AACjN,SAAS,wBAAwB,CAAC,YAAkC;IAClE,OAAO,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC;SAC7B,IAAI,CAAC,cAAc,CAAC;SACpB,GAAG,CAAC,CAAC,GAAG,EAAa,EAAE,CAAC,CAAC,GAAG,EAAE,0BAA0B,CAAC,YAAY,CAAC,GAAG,CAAE,CAAC,CAAC,CAAC,CAAC;AACpF,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,0BAA0B,CAAC,QAAuB;IAChE,MAAM,SAAS,GAAc;QAC3B,eAAe;QACf,QAAQ,CAAC,UAAU;QACnB,wBAAwB,CAAC,QAAQ,CAAC,YAAY,CAAC;QAC/C,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC;KACvC,CAAC;IACF,OAAO,WAAW,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;AAC5D,CAAC"}
package/dist/index.d.ts CHANGED
@@ -3,4 +3,7 @@ export { createPlayer } from "./create-player.js";
3
3
  export { advancePlayer } from "./advance-player.js";
4
4
  export { selectPlayerChoice } from "./select-player-choice.js";
5
5
  export type { AdvanceOptions, AvailableChoiceItem, ContentResult, PresentationResult, DialogueResult, ChoiceResult, NavigationResult, CompletedResult, ErrorResult, ExecutionResult, RuntimeExecutionErrorKind, RuntimeExecutionError } from "@aftertext/runtime";
6
+ export type { JsonValue, PlayerSnapshot, PlayerRestoreError, RestorePlayerResult } from "./snapshot-types.js";
7
+ export { snapshotPlayer } from "./snapshot-player.js";
8
+ export { restorePlayer } from "./restore-player.js";
6
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,YAAY,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,YAAY,EACV,cAAc,EACd,mBAAmB,EACnB,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,WAAW,EACX,eAAe,EACf,yBAAyB,EACzB,qBAAqB,EACtB,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,YAAY,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,YAAY,EACV,cAAc,EACd,mBAAmB,EACnB,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,WAAW,EACX,eAAe,EACf,yBAAyB,EACzB,qBAAqB,EACtB,MAAM,oBAAoB,CAAC;AAU5B,YAAY,EAAE,SAAS,EAAE,cAAc,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC9G,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -12,4 +12,6 @@
12
12
  export { createPlayer } from "./create-player.js";
13
13
  export { advancePlayer } from "./advance-player.js";
14
14
  export { selectPlayerChoice } from "./select-player-choice.js";
15
+ export { snapshotPlayer } from "./snapshot-player.js";
16
+ export { restorePlayer } from "./restore-player.js";
15
17
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,yEAAyE;AACzE,2EAA2E;AAC3E,sEAAsE;AACtE,2EAA2E;AAC3E,uEAAuE;AACvE,EAAE;AACF,2DAA2D;AAC3D,wEAAwE;AACxE,kEAAkE;AAClE,kEAAkE;AAGlE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,yEAAyE;AACzE,2EAA2E;AAC3E,sEAAsE;AACtE,2EAA2E;AAC3E,uEAAuE;AACvE,EAAE;AACF,2DAA2D;AAC3D,wEAAwE;AACxE,kEAAkE;AAClE,kEAAkE;AAGlE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AA0B/D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC"}
@@ -0,0 +1,28 @@
1
+ import type { StoryDocument } from "@aftertext/compiler";
2
+ import { type RestorePlayerResult } from "./snapshot-types.js";
3
+ /**
4
+ * Reconstructs a live, caller-independent `PlayerState` from an opaque
5
+ * `PlayerSnapshot`-shaped value (docs/CORE_SPEC.md Section 33.8).
6
+ * `snapshot` is untrusted `unknown` data — every field is validated
7
+ * before any live state is constructed, and this function never throws
8
+ * for ordinary malformed input, including input designed to throw while
9
+ * merely being *inspected*: a plain object with a throwing getter on
10
+ * `formatVersion`/etc., or a `Proxy` whose `get`/`getPrototypeOf` trap
11
+ * throws, would otherwise propagate an exception out of this public
12
+ * boundary the first time a validator reads one of its properties. The
13
+ * single `try`/`catch` here — around the entire validation pipeline,
14
+ * not scattered per call site — is the one place that guarantee needs
15
+ * enforcing, since every validator below already assumes ordinary
16
+ * property access never throws.
17
+ *
18
+ * Validation proceeds in the merged spec's own locked numbered order:
19
+ * top-level shape -> formatVersion -> documentFingerprint -> runtimeState
20
+ * -> position/current JSON-compatibility -> structural position
21
+ * resolution (including Runtime's own exposure-flag/ReaderState
22
+ * consistency check) -> current-descriptor re-derivation. Only this last
23
+ * step produces `unresolvablePosition`; every earlier failure — including
24
+ * a structural position that fails to resolve at all — is
25
+ * `malformedSnapshot` (Section 33.8's own step 6 vs. step 7 boundary).
26
+ */
27
+ export declare function restorePlayer(document: StoryDocument, snapshot: unknown): RestorePlayerResult;
28
+ //# sourceMappingURL=restore-player.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restore-player.d.ts","sourceRoot":"","sources":["../src/restore-player.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA0B,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMjF,OAAO,EAA8C,KAAK,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAc3G;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,aAAa,EAAE,QAAQ,EAAE,OAAO,GAAG,mBAAmB,CAY7F"}
@@ -0,0 +1,224 @@
1
+ import { fromCursorPosition, INITIAL_CURSOR } from "@aftertext/runtime";
2
+ import { computeDocumentFingerprint } from "./document-fingerprint.js";
3
+ import { decodeCurrent } from "./snapshot-current.js";
4
+ import { buildDocumentIndex, hasVisitedCurrentScene, isFreshRuntimeState, validateRuntimeState } from "./snapshot-runtime-state.js";
5
+ import { isJsonValue, isPlainRecord } from "./snapshot-types.js";
6
+ function malformed(reason) {
7
+ return { ok: false, error: { kind: "malformedSnapshot", reason } };
8
+ }
9
+ function unresolvable(reason) {
10
+ return { ok: false, error: { kind: "unresolvablePosition", reason } };
11
+ }
12
+ function restored(state) {
13
+ return { ok: true, state };
14
+ }
15
+ /**
16
+ * Reconstructs a live, caller-independent `PlayerState` from an opaque
17
+ * `PlayerSnapshot`-shaped value (docs/CORE_SPEC.md Section 33.8).
18
+ * `snapshot` is untrusted `unknown` data — every field is validated
19
+ * before any live state is constructed, and this function never throws
20
+ * for ordinary malformed input, including input designed to throw while
21
+ * merely being *inspected*: a plain object with a throwing getter on
22
+ * `formatVersion`/etc., or a `Proxy` whose `get`/`getPrototypeOf` trap
23
+ * throws, would otherwise propagate an exception out of this public
24
+ * boundary the first time a validator reads one of its properties. The
25
+ * single `try`/`catch` here — around the entire validation pipeline,
26
+ * not scattered per call site — is the one place that guarantee needs
27
+ * enforcing, since every validator below already assumes ordinary
28
+ * property access never throws.
29
+ *
30
+ * Validation proceeds in the merged spec's own locked numbered order:
31
+ * top-level shape -> formatVersion -> documentFingerprint -> runtimeState
32
+ * -> position/current JSON-compatibility -> structural position
33
+ * resolution (including Runtime's own exposure-flag/ReaderState
34
+ * consistency check) -> current-descriptor re-derivation. Only this last
35
+ * step produces `unresolvablePosition`; every earlier failure — including
36
+ * a structural position that fails to resolve at all — is
37
+ * `malformedSnapshot` (Section 33.8's own step 6 vs. step 7 boundary).
38
+ */
39
+ export function restorePlayer(document, snapshot) {
40
+ try {
41
+ return restorePlayerUnchecked(document, snapshot);
42
+ }
43
+ catch {
44
+ // Never format the caught value: a hostile `unknown` input can throw a
45
+ // non-Error whose own `toString`/`Symbol.toPrimitive` throws, or an
46
+ // Error-like object with a throwing `message` getter — invoking either
47
+ // while building the reason string would itself throw, right back out
48
+ // of this handler. A fixed reason costs nothing (it's optional on
49
+ // `malformedSnapshot`) and can never fail to produce.
50
+ return malformed("snapshot could not be inspected.");
51
+ }
52
+ }
53
+ function restorePlayerUnchecked(document, snapshot) {
54
+ if (!isPlainRecord(snapshot))
55
+ return malformed("snapshot is not a plain object.");
56
+ if (snapshot.formatVersion !== 1) {
57
+ return { ok: false, error: { kind: "unsupportedFormatVersion" } };
58
+ }
59
+ if (typeof snapshot.documentFingerprint !== "string") {
60
+ return malformed("documentFingerprint is not a string.");
61
+ }
62
+ if (snapshot.documentFingerprint !== computeDocumentFingerprint(document)) {
63
+ return { ok: false, error: { kind: "documentMismatch" } };
64
+ }
65
+ const index = buildDocumentIndex(document);
66
+ const runtimeStateResult = validateRuntimeState(index, snapshot.runtimeState);
67
+ if (!runtimeStateResult.ok)
68
+ return malformed(runtimeStateResult.reason);
69
+ const runtimeState = runtimeStateResult.value;
70
+ // Read each property exactly once: an untrusted accessor could otherwise
71
+ // return a validated-looking value the first time (passing isJsonValue)
72
+ // and a different one the second, letting an unvalidated value drive
73
+ // reconstruction below.
74
+ const position = snapshot.position;
75
+ const rawCurrent = snapshot.current;
76
+ if (!isJsonValue(position) || !isJsonValue(rawCurrent)) {
77
+ return malformed("position/current are not JSON-compatible.");
78
+ }
79
+ const current = decodeCurrent(rawCurrent);
80
+ if (!current)
81
+ return malformed("current descriptor is malformed.");
82
+ return restoreForCurrent(document, index, runtimeState, current, position);
83
+ }
84
+ function restoreForCurrent(document, index, runtimeState, current, position) {
85
+ if (current.type === "notStarted")
86
+ return restoreNotStarted(document, runtimeState);
87
+ if (current.type === "navigation")
88
+ return restoreNavigation(index, runtimeState, current);
89
+ if (current.type === "completed")
90
+ return restoreCompleted(runtimeState);
91
+ return restoreStructural(document, runtimeState, current, position);
92
+ }
93
+ function restoreNotStarted(document, runtimeState) {
94
+ if (!isFreshRuntimeState(document, runtimeState)) {
95
+ return malformed("not-started runtimeState does not match createPlayer's own output.");
96
+ }
97
+ return restored({ runtimeState, cursor: INITIAL_CURSOR, current: null });
98
+ }
99
+ function restoreNavigation(index, runtimeState, current) {
100
+ if (current.to !== runtimeState.navigation.sceneId) {
101
+ return malformed("navigation.to does not match runtimeState.navigation.sceneId.");
102
+ }
103
+ if (!index.sceneIds.has(current.from)) {
104
+ return malformed(`navigation.from "${current.from}" does not exist.`);
105
+ }
106
+ return restored({ runtimeState, cursor: INITIAL_CURSOR, current: { type: "navigation", from: current.from, to: current.to } });
107
+ }
108
+ function restoreCompleted(runtimeState) {
109
+ if (!hasVisitedCurrentScene(runtimeState)) {
110
+ return malformed("completed runtimeState is missing the current scene's visit entry.");
111
+ }
112
+ return restored({ runtimeState, cursor: INITIAL_CURSOR, current: { type: "completed" } });
113
+ }
114
+ /**
115
+ * Handles every kind with a real structural position
116
+ * (content/dialogue/presentation/choice/error). Calls Runtime's own
117
+ * `fromCursorPosition` — any resolution failure there, including its own
118
+ * internal exposure-flag/ReaderState consistency check, is
119
+ * `malformedSnapshot`, not `unresolvablePosition` (Section 33.8 step 6).
120
+ */
121
+ function restoreStructural(document, runtimeState, current, position) {
122
+ const decoded = fromCursorPosition(document, runtimeState, position, current.type);
123
+ if (!decoded.ok)
124
+ return malformed(decoded.reason);
125
+ return reconstructResult(runtimeState, decoded.cursor, decoded.resolvedBlock, current);
126
+ }
127
+ function reconstructResult(runtimeState, cursor, resolvedBlock, current) {
128
+ if (current.type === "content")
129
+ return reconstructContent(runtimeState, cursor, resolvedBlock);
130
+ if (current.type === "dialogue")
131
+ return reconstructDialogue(runtimeState, cursor, resolvedBlock);
132
+ if (current.type === "presentation")
133
+ return reconstructPresentation(runtimeState, cursor, resolvedBlock);
134
+ if (current.type === "choice")
135
+ return reconstructChoice(runtimeState, cursor, resolvedBlock, current.items);
136
+ return reconstructError(runtimeState, cursor, current);
137
+ }
138
+ /** Only this re-derivation step — matching the resolved block's type to the suspension kind — produces `unresolvablePosition` (Section 33.8 step 7). */
139
+ function reconstructContent(runtimeState, cursor, resolvedBlock) {
140
+ if (resolvedBlock?.type !== "Paragraph" && resolvedBlock?.type !== "Heading") {
141
+ return unresolvable("resolved block is not a Paragraph or Heading.");
142
+ }
143
+ return restored({ runtimeState, cursor, current: { type: "content", block: resolvedBlock } });
144
+ }
145
+ function reconstructDialogue(runtimeState, cursor, resolvedBlock) {
146
+ if (resolvedBlock?.type !== "Dialogue")
147
+ return unresolvable("resolved block is not a Dialogue.");
148
+ return restored({
149
+ runtimeState,
150
+ cursor,
151
+ current: { type: "dialogue", speaker: resolvedBlock.speaker, content: resolvedBlock.content }
152
+ });
153
+ }
154
+ function reconstructPresentation(runtimeState, cursor, resolvedBlock) {
155
+ if (resolvedBlock?.type !== "Presentation")
156
+ return unresolvable("resolved block is not a Presentation.");
157
+ return restored({ runtimeState, cursor, current: { type: "presentation", command: resolvedBlock.command } });
158
+ }
159
+ function reconstructError(runtimeState, cursor, current) {
160
+ return restored({ runtimeState, cursor, current: { type: "error", error: { kind: current.kind, message: current.message } } });
161
+ }
162
+ /**
163
+ * Dynamic-programming validation of the persisted offered Choice items
164
+ * against the resolved `ChoiceNode`'s own authored items (docs/CORE_SPEC.md
165
+ * Section 33.8): `reachable[j]` means an authored prefix can have produced
166
+ * exactly the persisted prefix `persisted[0..j)` while including every
167
+ * processed unconditional authored item. A plain greedy left-to-right
168
+ * match is NOT sufficient — it mismatches when a duplicate conditioned
169
+ * item precedes a duplicate unconditional item with the same text/target
170
+ * and only one persisted occurrence exists. Never evaluates any
171
+ * `condition` expression. Rejects before building any reachable set
172
+ * when `persisted.length > authored.length`: an authored list can
173
+ * expose at most one persisted occurrence per item, so a longer
174
+ * persisted list can never be a valid subsequence regardless of
175
+ * content — otherwise a dense but still-within-`MAX_JSON_ARRAY_LENGTH`
176
+ * persisted payload paired with a small authored Choice would still pay
177
+ * the full cost below for a result already known to be `false`.
178
+ *
179
+ * `reachable` is the *sparse* set of currently-true positions, not a
180
+ * dense `m + 1`-element array indexed by every position regardless of
181
+ * whether it is reachable: `authored.length` is trusted (it comes from
182
+ * the compiled document, not the untrusted snapshot) and the compiler
183
+ * imposes no item-count limit, so a document can legitimately author
184
+ * tens of thousands of Choice items — a dense table would cost
185
+ * `authored.length × persisted.length` even for a perfectly valid
186
+ * round trip of such a Choice (quadratic in a size the untrusted input
187
+ * does not control, but still slow enough to block the event loop for
188
+ * a real, non-malicious save). Iterating only the sparse set gives the
189
+ * exact same result — every transition below is identical to the
190
+ * dense table's — in time proportional to how many positions are
191
+ * actually reachable at each step, which for the overwhelmingly common
192
+ * case (most or all items unconditional, at most one position ever
193
+ * reachable at a time) is linear in `authored.length` regardless of
194
+ * `persisted.length`.
195
+ */
196
+ function choiceItemsAreValidSubsequence(authored, persisted) {
197
+ if (persisted.length > authored.length)
198
+ return false;
199
+ const m = persisted.length;
200
+ let reachable = new Set([0]);
201
+ for (const item of authored) {
202
+ const next = new Set();
203
+ for (const j of reachable) {
204
+ if (item.condition)
205
+ next.add(j);
206
+ if (j < m && item.text === persisted[j].text && item.target === persisted[j].target)
207
+ next.add(j + 1);
208
+ }
209
+ reachable = next;
210
+ }
211
+ return reachable.has(m);
212
+ }
213
+ function reconstructChoice(runtimeState, cursor, resolvedBlock, persisted) {
214
+ if (resolvedBlock?.type !== "Choice")
215
+ return unresolvable("resolved block is not a Choice.");
216
+ if (persisted.length === 0)
217
+ return unresolvable("persisted choice items are empty.");
218
+ if (!choiceItemsAreValidSubsequence(resolvedBlock.items, persisted)) {
219
+ return unresolvable("persisted choice items are not a valid subsequence of the authored Choice.");
220
+ }
221
+ const items = persisted.map((item, itemIndex) => ({ index: itemIndex, text: item.text, target: item.target }));
222
+ return restored({ runtimeState, cursor, current: { type: "choice", items } });
223
+ }
224
+ //# sourceMappingURL=restore-player.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restore-player.js","sourceRoot":"","sources":["../src/restore-player.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAqE,MAAM,oBAAoB,CAAC;AAC3I,OAAO,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EAAE,aAAa,EAAwB,MAAM,uBAAuB,CAAC;AAE5E,OAAO,EAA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K,CAAC;QAAE,OAAO,YAAY,CAAC,mCAAmC,CAAC,CAAC;IACrF,IAAI,CAAC,8BAA8B,CAAC,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;QACpE,OAAO,YAAY,CAAC,4EAA4E,CAAC,CAAC;IACpG,CAAC;IAED,MAAM,KAAK,GAA0B,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IACtI,OAAO,QAAQ,CAAC,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;AAChF,CAAC"}
@@ -0,0 +1,51 @@
1
+ import type { ExecutionResult, RuntimeExecutionErrorKind } from "@aftertext/runtime";
2
+ import type { JsonValue } from "./snapshot-types.js";
3
+ /**
4
+ * Private, opaque current-result descriptor (docs/CORE_SPEC.md Section
5
+ * 33.7) — never exported. An AST-bearing live result (`content.block`,
6
+ * `dialogue.speaker`/`content`, `presentation.command`) is never stored
7
+ * here; only enough to identify which kind of suspension it was. The
8
+ * structural position needed to re-derive it comes from Runtime's own
9
+ * `toCursorPosition`/`fromCursorPosition`, not from this descriptor.
10
+ */
11
+ export type SnapshotCurrent = {
12
+ readonly type: "notStarted";
13
+ } | {
14
+ readonly type: "content";
15
+ } | {
16
+ readonly type: "dialogue";
17
+ } | {
18
+ readonly type: "presentation";
19
+ } | {
20
+ readonly type: "choice";
21
+ readonly items: readonly {
22
+ readonly text: string;
23
+ readonly target: string;
24
+ }[];
25
+ } | {
26
+ readonly type: "navigation";
27
+ readonly from: string;
28
+ readonly to: string;
29
+ } | {
30
+ readonly type: "completed";
31
+ } | {
32
+ readonly type: "error";
33
+ readonly kind: RuntimeExecutionErrorKind;
34
+ readonly message: string;
35
+ };
36
+ /**
37
+ * Encodes `current` as an opaque `JsonValue` (docs/CORE_SPEC.md Section
38
+ * 33.7). `current === null` means `PlayerState` was created but has never
39
+ * advanced — encoded as `"notStarted"`, the same uniform sentinel every
40
+ * other no-structural-position kind uses (Section 33.4's uniform-capture
41
+ * principle, extended here to the current descriptor itself).
42
+ */
43
+ export declare function encodeCurrent(current: ExecutionResult | null): JsonValue;
44
+ /**
45
+ * Validates and decodes an opaque `current` value (docs/CORE_SPEC.md
46
+ * Section 33.8) — `value` is untrusted JSON-compatible data, not trusted
47
+ * internal state. Returns `undefined` for any malformed shape; never
48
+ * throws.
49
+ */
50
+ export declare function decodeCurrent(value: JsonValue): SnapshotCurrent | undefined;
51
+ //# sourceMappingURL=snapshot-current.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshot-current.d.ts","sourceRoot":"","sources":["../src/snapshot-current.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AACrF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAGrD;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GACvB;IAAE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAA;CAAE,GAC/B;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAA;CAAE,GAC5B;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAA;CAAE,GAC7B;IAAE,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAA;CAAE,GACjC;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,SAAS;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;CAAE,GAC1G;IAAE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAA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