@opencode/codemode 2.2.5 → 2.2.7

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.
Files changed (142) hide show
  1. package/README.md +164 -7
  2. package/dist/codemode.d.ts +60 -4
  3. package/dist/codemode.js +63 -8
  4. package/dist/extension.d.ts +27 -9
  5. package/dist/extension.js +7 -3
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/interpreter/callback.d.ts +12 -1
  9. package/dist/interpreter/callback.js +13 -1
  10. package/dist/interpreter/execute.d.ts +1 -1
  11. package/dist/interpreter/execute.js +16 -4
  12. package/dist/interpreter/extensions.d.ts +3 -3
  13. package/dist/interpreter/extensions.js +17 -11
  14. package/dist/interpreter/globals.js +10 -0
  15. package/dist/interpreter/interpreter.d.ts +11 -1
  16. package/dist/interpreter/interpreter.js +88 -4
  17. package/dist/interpreter/modules.d.ts +4 -0
  18. package/dist/interpreter/modules.js +33 -0
  19. package/dist/interpreter/promises.js +2 -2
  20. package/dist/interpreter/runner.d.ts +1 -11
  21. package/dist/interpreter/runner.js +1 -13
  22. package/dist/stdlib/iterator.js +1 -2
  23. package/dist/suspend-error.d.ts +24 -0
  24. package/dist/suspend-error.js +25 -0
  25. package/dist/tool-runtime.d.ts +31 -7
  26. package/dist/tool-runtime.js +116 -26
  27. package/dist/tool.d.ts +45 -2
  28. package/dist/tool.js +30 -7
  29. package/dist/vm/async.d.ts +78 -0
  30. package/dist/vm/async.js +335 -0
  31. package/dist/vm/code.d.ts +122 -0
  32. package/dist/vm/code.js +407 -0
  33. package/dist/vm/compiler/compile.d.ts +13 -0
  34. package/dist/vm/compiler/compile.js +1477 -0
  35. package/dist/vm/compiler/scope.d.ts +74 -0
  36. package/dist/vm/compiler/scope.js +515 -0
  37. package/dist/vm/data.d.ts +7 -0
  38. package/dist/vm/data.js +13 -0
  39. package/dist/vm/generators.d.ts +42 -0
  40. package/dist/vm/generators.js +413 -0
  41. package/dist/vm/host.d.ts +106 -0
  42. package/dist/vm/host.js +231 -0
  43. package/dist/vm/index.d.ts +6 -0
  44. package/dist/vm/index.js +6 -0
  45. package/dist/vm/internal-prelude.d.ts +45 -0
  46. package/dist/vm/internal-prelude.js +534 -0
  47. package/dist/vm/opcodes.d.ts +222 -0
  48. package/dist/vm/opcodes.js +235 -0
  49. package/dist/vm/prelude/bytecode.d.ts +18 -0
  50. package/dist/vm/prelude/bytecode.js +31 -0
  51. package/dist/vm/prelude/bytecode.json +1 -0
  52. package/dist/vm/prelude/helpers.d.ts +8 -0
  53. package/dist/vm/prelude/helpers.js +258 -0
  54. package/dist/vm/prelude/prelude.d.ts +21 -0
  55. package/dist/vm/prelude/prelude.js +53 -0
  56. package/dist/vm/prelude/source.d.ts +1 -0
  57. package/dist/vm/prelude/source.js +652 -0
  58. package/dist/vm/runtime/callback.d.ts +25 -0
  59. package/dist/vm/runtime/callback.js +51 -0
  60. package/dist/vm/runtime/driver.d.ts +68 -0
  61. package/dist/vm/runtime/driver.js +254 -0
  62. package/dist/vm/runtime/errors.d.ts +23 -0
  63. package/dist/vm/runtime/errors.js +169 -0
  64. package/dist/vm/runtime/execute.d.ts +80 -0
  65. package/dist/vm/runtime/execute.js +442 -0
  66. package/dist/vm/runtime/extensions.d.ts +16 -0
  67. package/dist/vm/runtime/extensions.js +337 -0
  68. package/dist/vm/runtime/generators.d.ts +6 -0
  69. package/dist/vm/runtime/generators.js +44 -0
  70. package/dist/vm/runtime/globals.d.ts +6 -0
  71. package/dist/vm/runtime/globals.js +137 -0
  72. package/dist/vm/runtime/interpreter.d.ts +53 -0
  73. package/dist/vm/runtime/interpreter.js +96 -0
  74. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  75. package/dist/vm/runtime/intrinsic-names.js +166 -0
  76. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  77. package/dist/vm/runtime/intrinsics.js +111 -0
  78. package/dist/vm/runtime/limits.d.ts +10 -0
  79. package/dist/vm/runtime/limits.js +19 -0
  80. package/dist/vm/runtime/model.d.ts +58 -0
  81. package/dist/vm/runtime/model.js +57 -0
  82. package/dist/vm/runtime/modules.d.ts +4 -0
  83. package/dist/vm/runtime/modules.js +33 -0
  84. package/dist/vm/runtime/native.d.ts +19 -0
  85. package/dist/vm/runtime/native.js +41 -0
  86. package/dist/vm/runtime/objects.d.ts +403 -0
  87. package/dist/vm/runtime/objects.js +784 -0
  88. package/dist/vm/runtime/operations.d.ts +49 -0
  89. package/dist/vm/runtime/operations.js +288 -0
  90. package/dist/vm/runtime/promises.d.ts +55 -0
  91. package/dist/vm/runtime/promises.js +232 -0
  92. package/dist/vm/runtime/references.d.ts +8 -0
  93. package/dist/vm/runtime/references.js +51 -0
  94. package/dist/vm/runtime/signals.d.ts +69 -0
  95. package/dist/vm/runtime/signals.js +68 -0
  96. package/dist/vm/runtime/source.d.ts +29 -0
  97. package/dist/vm/runtime/source.js +63 -0
  98. package/dist/vm/runtime/table.d.ts +43 -0
  99. package/dist/vm/runtime/table.js +132 -0
  100. package/dist/vm/scheduler.d.ts +190 -0
  101. package/dist/vm/scheduler.js +74 -0
  102. package/dist/vm/snapshot/codec.d.ts +117 -0
  103. package/dist/vm/snapshot/codec.js +848 -0
  104. package/dist/vm/snapshot/snapshot.d.ts +53 -0
  105. package/dist/vm/snapshot/snapshot.js +74 -0
  106. package/dist/vm/snapshot.d.ts +32 -0
  107. package/dist/vm/snapshot.js +309 -0
  108. package/dist/vm/stdlib/array.d.ts +16 -0
  109. package/dist/vm/stdlib/array.js +311 -0
  110. package/dist/vm/stdlib/bytes.d.ts +11 -0
  111. package/dist/vm/stdlib/bytes.js +222 -0
  112. package/dist/vm/stdlib/collections.d.ts +7 -0
  113. package/dist/vm/stdlib/collections.js +188 -0
  114. package/dist/vm/stdlib/console.d.ts +6 -0
  115. package/dist/vm/stdlib/console.js +93 -0
  116. package/dist/vm/stdlib/date.d.ts +2 -0
  117. package/dist/vm/stdlib/date.js +123 -0
  118. package/dist/vm/stdlib/headers.d.ts +2 -0
  119. package/dist/vm/stdlib/headers.js +92 -0
  120. package/dist/vm/stdlib/iterator.d.ts +2 -0
  121. package/dist/vm/stdlib/iterator.js +30 -0
  122. package/dist/vm/stdlib/json.d.ts +3 -0
  123. package/dist/vm/stdlib/json.js +42 -0
  124. package/dist/vm/stdlib/math.d.ts +3 -0
  125. package/dist/vm/stdlib/math.js +73 -0
  126. package/dist/vm/stdlib/number.d.ts +3 -0
  127. package/dist/vm/stdlib/number.js +72 -0
  128. package/dist/vm/stdlib/object.d.ts +6 -0
  129. package/dist/vm/stdlib/object.js +201 -0
  130. package/dist/vm/stdlib/regexp.d.ts +8 -0
  131. package/dist/vm/stdlib/regexp.js +119 -0
  132. package/dist/vm/stdlib/string.d.ts +2 -0
  133. package/dist/vm/stdlib/string.js +272 -0
  134. package/dist/vm/stdlib/url.d.ts +25 -0
  135. package/dist/vm/stdlib/url.js +255 -0
  136. package/dist/vm/stdlib/value.d.ts +6 -0
  137. package/dist/vm/stdlib/value.js +32 -0
  138. package/dist/vm/stdlib/web.d.ts +5 -0
  139. package/dist/vm/stdlib/web.js +97 -0
  140. package/dist/vm/vm.d.ts +226 -0
  141. package/dist/vm/vm.js +2931 -0
  142. package/package.json +8 -5
@@ -0,0 +1,848 @@
1
+ import { Interpreter } from "../runtime/interpreter.js";
2
+ import { AsyncIteratorSymbol, IteratorSymbol, Lost, lostError, PendingThrow, Throw, } from "../runtime/model.js";
3
+ import { Arguments, Arr, BoundFn, Bytes, changed, DateObj, ErrorObj, GeneratorObj, HeadersObj, IteratorObj, MapObj, Native, Obj, Position, PromiseObj, RegExpObj, Resolver, SetObj, URLObj, URLSearchParamsObj, WeakMapObj, WeakSetObj, } from "../runtime/objects.js";
4
+ import { Convert, Interruption, Invoke } from "../runtime/signals.js";
5
+ import { deleted, OrderedTable } from "../runtime/table.js";
6
+ import { AsyncFromSyncIterator } from "../generators.js";
7
+ import { HostCall, Resolving } from "../scheduler.js";
8
+ import { TextDecoderObj } from "../stdlib/bytes.js";
9
+ import { ToolError, toolError } from "../../tool-error.js";
10
+ import { ToolReference, ToolRuntimeError } from "../../tool-runtime.js";
11
+ /** A saved state can't be read, or doesn't fit this runtime. */
12
+ import { SnapshotError } from "../../suspend-error.js";
13
+ export { SnapshotError };
14
+ // --- Registries ---
15
+ const symbols = new Map([
16
+ ["iterator", IteratorSymbol],
17
+ ["asyncIterator", AsyncIteratorSymbol],
18
+ ["deleted", deleted],
19
+ ]);
20
+ const symbolNames = new Map([...symbols].map(([name, symbol]) => [symbol, name]));
21
+ // `intrinsic` is not saved: a restored object is the program's, or a named intrinsic that keeps its own.
22
+ const objFields = ["props", "extensible", "proto", "intrinsic"];
23
+ const callable = { tag: "Function" };
24
+ // Built on first use: the VM's modules and this one import each other, so the classes aren't there at load time.
25
+ const builtinSpecs = () => [
26
+ { name: "Obj", ctor: Obj, fields: [], obj: true, constants: { tag: "Object" } },
27
+ { name: "Arr", ctor: Arr, fields: ["items", "elements"], obj: true, constants: { tag: "Array" } },
28
+ { name: "ErrorObj", ctor: ErrorObj, fields: ["failure"], obj: true, constants: { tag: "Error" } },
29
+ { name: "Arguments", ctor: Arguments, fields: [], obj: true, constants: { tag: "Arguments" } },
30
+ // Only named natives are saved (by name); an unnamed one is a host function, saved as `LostNative`.
31
+ { name: "Native", ctor: Native, fields: [], skip: ["length", "call", "construct", "callback"], obj: true },
32
+ {
33
+ name: "BoundFn",
34
+ ctor: BoundFn,
35
+ fields: ["length", "target", "boundThis", "boundArgs"],
36
+ obj: true,
37
+ constants: { ...callable, construct: undefined, callback: true },
38
+ },
39
+ {
40
+ name: "Resolver",
41
+ ctor: Resolver,
42
+ fields: ["length", "resolving", "kind"],
43
+ obj: true,
44
+ constants: { ...callable, construct: undefined, callback: true },
45
+ },
46
+ {
47
+ name: "PromiseObj",
48
+ ctor: PromiseObj,
49
+ fields: ["state", "result", "reactions", "handled", "id"],
50
+ obj: true,
51
+ constants: { tag: "Promise" },
52
+ },
53
+ {
54
+ name: "GeneratorObj",
55
+ ctor: GeneratorObj,
56
+ fields: ["state", "frame", "queue", "asynchronous"],
57
+ obj: true,
58
+ constants: { tag: "Generator" },
59
+ },
60
+ { name: "IteratorObj", ctor: IteratorObj, fields: ["cursor"], obj: true, constants: { tag: "Iterator" } },
61
+ { name: "DateObj", ctor: DateObj, fields: ["time"], obj: true, constants: { tag: "Date" } },
62
+ {
63
+ name: "RegExpObj",
64
+ ctor: RegExpObj,
65
+ fields: ["source", "flags", "lastIndex"],
66
+ skip: ["compiled"],
67
+ obj: true,
68
+ constants: { tag: "RegExp" },
69
+ reset: (value) => {
70
+ value.compiled = undefined;
71
+ },
72
+ },
73
+ { name: "MapObj", ctor: MapObj, fields: ["map"], obj: true, constants: { tag: "Map" } },
74
+ { name: "SetObj", ctor: SetObj, fields: ["set"], obj: true, constants: { tag: "Set" } },
75
+ { name: "WeakMapObj", ctor: WeakMapObj, fields: ["map"], obj: true, constants: { tag: "WeakMap" } },
76
+ { name: "WeakSetObj", ctor: WeakSetObj, fields: ["set"], obj: true, constants: { tag: "WeakSet" } },
77
+ {
78
+ name: "URLSearchParamsObj",
79
+ ctor: URLSearchParamsObj,
80
+ fields: ["params"],
81
+ obj: true,
82
+ constants: { tag: "URLSearchParams" },
83
+ },
84
+ { name: "HeadersObj", ctor: HeadersObj, fields: ["headers"], obj: true, constants: { tag: "Headers" } },
85
+ { name: "URLObj", ctor: URLObj, fields: ["searchParams", "url"], obj: true, constants: { tag: "URL" } },
86
+ { name: "Bytes", ctor: Bytes, fields: ["bytes"], obj: true, constants: { tag: "Uint8Array" } },
87
+ { name: "TextDecoderObj", ctor: TextDecoderObj, fields: ["decoder"], obj: true, constants: { tag: "Object" } },
88
+ {
89
+ name: "AsyncFromSyncIterator",
90
+ ctor: AsyncFromSyncIterator,
91
+ fields: ["sync", "site"],
92
+ obj: true,
93
+ constants: { tag: "AsyncFromSyncIterator" },
94
+ },
95
+ { name: "Position", ctor: Position, fields: ["index", "done", "source", "kind", "arrays"] },
96
+ {
97
+ name: "OrderedTable",
98
+ ctor: OrderedTable,
99
+ fields: ["keys", "values", "cursors", "tombstones", "pruneAt"],
100
+ skip: ["index"],
101
+ // The index is derived from the keys.
102
+ reset: (table) => {
103
+ table.index = new Map();
104
+ table.keys.forEach((key, at) => {
105
+ if (key !== deleted)
106
+ table.index.set(key, at);
107
+ });
108
+ },
109
+ },
110
+ {
111
+ name: "HostCall",
112
+ ctor: HostCall,
113
+ fields: ["status", "data", "admitted", "id", "key", "request", "label", "blocking", "result", "resolving", "site"],
114
+ },
115
+ { name: "Resolving", ctor: Resolving, fields: ["done", "scheduler", "promise", "site"] },
116
+ { name: "Throw", ctor: Throw, fields: ["value"] },
117
+ { name: "PendingThrow", ctor: PendingThrow, fields: ["type", "message", "kind", "suggestions", "node", "value"] },
118
+ { name: "Convert", ctor: Convert, fields: ["hints", "values", "ordinal", "coerce"] },
119
+ { name: "Invoke", ctor: Invoke, fields: ["callable", "thisValue", "args", "site"] },
120
+ { name: "ToolReference", ctor: ToolReference, fields: ["path"] },
121
+ { name: "Lost", ctor: Lost, fields: ["description"] },
122
+ {
123
+ name: "Interpreter",
124
+ ctor: Interpreter,
125
+ anchor: "ctx",
126
+ fields: ["logs", "globalScope", "modules", "namespaces"],
127
+ skip: ["tools", "builtins", "vm", "intrinsics", "extensionWork", "hosts", "sources", "prelude"],
128
+ },
129
+ ];
130
+ let builtins;
131
+ const builtinRegistry = () => {
132
+ if (builtins !== undefined)
133
+ return builtins;
134
+ const specs = builtinSpecs();
135
+ builtins = {
136
+ byCtor: new Map(specs.map((spec) => [spec.ctor, spec])),
137
+ byName: new Map(specs.map((spec) => [spec.name, spec])),
138
+ };
139
+ return builtins;
140
+ };
141
+ // A function an extension made while the program ran, which has no data form: saved as `LostNative`.
142
+ const hostFunction = {
143
+ name: "LostNative",
144
+ ctor: Native,
145
+ fields: ["length"],
146
+ obj: true,
147
+ constants: callable,
148
+ };
149
+ /** Host error classes that can travel as a failure, by name. */
150
+ const errorClasses = new Map([
151
+ ["Error", Error],
152
+ ["TypeError", TypeError],
153
+ ["RangeError", RangeError],
154
+ ["SyntaxError", SyntaxError],
155
+ ["ReferenceError", ReferenceError],
156
+ ["EvalError", EvalError],
157
+ ["URIError", URIError],
158
+ ["ToolRuntimeError", ToolRuntimeError],
159
+ ["ToolError", ToolError],
160
+ ]);
161
+ const errorNames = new Map([...errorClasses].map(([name, ctor]) => [ctor, name]));
162
+ /** The names of every class with a codec: a build that saves a different set cannot read this one's snapshots. */
163
+ export const codecShape = (extra = []) => JSON.stringify([[...builtinSpecs(), ...extra].map((spec) => [spec.name, spec.fields]), [...symbols.keys()]]);
164
+ const registry = (extra) => {
165
+ const { byCtor, byName } = builtinRegistry();
166
+ return extra === undefined || extra.length === 0
167
+ ? { byCtor, byName }
168
+ : {
169
+ byCtor: new Map([...byCtor, ...extra.map((spec) => [spec.ctor, spec])]),
170
+ byName: new Map([...byName, ...extra.map((spec) => [spec.name, spec])]),
171
+ };
172
+ };
173
+ // --- Encoding ---
174
+ /** Encodes everything reachable from `roots`: the roots' values and the records they refer to. */
175
+ export const encode = (roots, env) => {
176
+ const encoder = new Encoder(env);
177
+ const encoded = roots.map((root) => encoder.value(root));
178
+ encoder.drain();
179
+ return { roots: encoded, records: encoder.records };
180
+ };
181
+ class Encoder {
182
+ env;
183
+ records = [];
184
+ ids = new Map();
185
+ work = [];
186
+ // A URL's `searchParams` is the same host object its URLSearchParams wraps; it is encoded once every URL is known.
187
+ owners = new Map();
188
+ params = [];
189
+ // One `HostValue` record per value an extension returned, however many of its functions the state holds.
190
+ roots = new Map();
191
+ specs;
192
+ constructor(env) {
193
+ this.env = env;
194
+ this.specs = registry(env.specs);
195
+ }
196
+ value(value) {
197
+ switch (typeof value) {
198
+ case "string":
199
+ case "boolean":
200
+ return value;
201
+ case "undefined":
202
+ return ["u"];
203
+ case "number":
204
+ if (Number.isFinite(value) && !Object.is(value, -0))
205
+ return value;
206
+ return ["n", Object.is(value, -0) ? "-0" : String(value)];
207
+ case "symbol": {
208
+ const name = symbolNames.get(value);
209
+ const external = name === undefined ? this.env.external?.(value) : undefined;
210
+ if (external !== undefined)
211
+ return ["x", external];
212
+ if (name === undefined)
213
+ throw new SnapshotError(`Codec gap: the symbol ${String(value)} has no name.`);
214
+ return ["s", name];
215
+ }
216
+ case "bigint":
217
+ throw new SnapshotError("Codec gap: a bigint has no data form.");
218
+ }
219
+ if (value === null)
220
+ return null;
221
+ const object = value;
222
+ const external = this.env.external?.(object);
223
+ if (external !== undefined)
224
+ return ["x", external];
225
+ if (object instanceof Obj) {
226
+ const name = this.env.nameOf(object);
227
+ if (name !== undefined && this.env.unchanged(object))
228
+ return ["i", name];
229
+ }
230
+ else if (!Array.isArray(object)) {
231
+ const node = this.env.nodeId(object);
232
+ if (node !== undefined)
233
+ return ["a", node[0], node[1]];
234
+ }
235
+ return this.ref(object);
236
+ }
237
+ drain() {
238
+ for (let object = this.work.shift(); object !== undefined; object = this.work.shift()) {
239
+ const id = this.ids.get(object);
240
+ this.records[id] = this.record(object, id);
241
+ }
242
+ for (const [id, params] of this.params) {
243
+ const owner = this.owners.get(params);
244
+ this.records[id] =
245
+ owner === undefined
246
+ ? { t: "URLSearchParams", s: params.toString() }
247
+ : { t: "URLSearchParams", o: this.ref(owner) };
248
+ }
249
+ }
250
+ ref(object) {
251
+ const known = this.ids.get(object);
252
+ if (known !== undefined)
253
+ return ["r", known];
254
+ const id = this.records.length;
255
+ this.ids.set(object, id);
256
+ this.records.push(undefined);
257
+ this.work.push(object);
258
+ return ["r", id];
259
+ }
260
+ record(object, id) {
261
+ if (object instanceof Obj) {
262
+ const name = this.env.nameOf(object);
263
+ if (name !== undefined) {
264
+ const spec = this.spec(object);
265
+ return { t: "@", n: name, c: spec.name, ...this.fields(object, spec) };
266
+ }
267
+ }
268
+ if (Array.isArray(object)) {
269
+ // A sparse array (`length` can be ten million with nothing in it) saves only the indexes it has.
270
+ if (object.length > 1024) {
271
+ const present = Object.keys(object);
272
+ if (present.length * 2 < object.length) {
273
+ const entries = [];
274
+ for (const key of present)
275
+ entries.push(Number(key), this.value(object[Number(key)]));
276
+ return { t: "Array", l: object.length, s: entries };
277
+ }
278
+ }
279
+ const items = [];
280
+ for (let at = 0; at < object.length; at++)
281
+ items.push(at in object ? this.value(object[at]) : ["h"]);
282
+ return { t: "Array", v: items };
283
+ }
284
+ if (object instanceof Map) {
285
+ const entries = [];
286
+ for (const [key, item] of object)
287
+ entries.push(this.value(key), this.value(item));
288
+ const anchor = this.env.anchorOf(object);
289
+ return anchor === undefined ? { t: "Map", e: entries } : { t: "Map", e: entries, a: anchor };
290
+ }
291
+ if (object instanceof Set)
292
+ return { t: "Set", e: [...object].map((item) => this.value(item)) };
293
+ const spec = this.specs.byCtor.get(object.constructor);
294
+ if (spec !== undefined && spec.name !== "Native") {
295
+ if (spec.anchor !== undefined && this.env.anchorOf(object) !== spec.anchor) {
296
+ throw new SnapshotError(`Codec gap: a second ${spec.name} is reachable from the state.`);
297
+ }
298
+ return { t: spec.name, ...this.fields(object, spec) };
299
+ }
300
+ if (object instanceof Native) {
301
+ // A host function made while the program ran: inside a value an extension returned. Its extension saves that
302
+ // value when it has `snapshot` hooks; otherwise its name says what was lost.
303
+ const origin = this.env.hosts?.origin(object);
304
+ if (origin !== undefined) {
305
+ const root = this.hostValue(origin.extension, origin.root);
306
+ const fields = this.fields(object, hostFunction, hostFunction.fields);
307
+ return { t: "HostFunction", e: origin.extension, h: root, k: [...origin.path], l: origin.label, ...fields };
308
+ }
309
+ this.lose(`the function ${functionName(object)}`);
310
+ return { t: "LostNative", ...this.fields(object, hostFunction, hostFunction.fields) };
311
+ }
312
+ const proto = Object.getPrototypeOf(object);
313
+ if (proto === Object.prototype || proto === null) {
314
+ const entries = [];
315
+ for (const key of Object.keys(object))
316
+ entries.push(key, this.value(object[key]));
317
+ return proto === null ? { t: "Object", e: entries, n: 1 } : { t: "Object", e: entries };
318
+ }
319
+ if (object instanceof Error)
320
+ return this.error(object);
321
+ if (object instanceof Interruption)
322
+ return { t: "Interruption" };
323
+ if (object instanceof URL) {
324
+ this.owners.set(object.searchParams, object);
325
+ return { t: "URL", h: object.href };
326
+ }
327
+ if (object instanceof URLSearchParams) {
328
+ this.params.push([id, object]);
329
+ return undefined;
330
+ }
331
+ if (object instanceof Headers)
332
+ return { t: "Headers", e: [...object].map(([key, item]) => [key, item]) };
333
+ if (object instanceof Uint8Array) {
334
+ return { t: "Uint8Array", b: this.ref(object.buffer), o: object.byteOffset, l: object.length };
335
+ }
336
+ if (object instanceof ArrayBuffer)
337
+ return { t: "ArrayBuffer", d: base64(new Uint8Array(object)) };
338
+ if (object instanceof TextDecoder)
339
+ return { t: "TextDecoder", f: object.fatal, i: object.ignoreBOM };
340
+ const what = typeof object === "function" ? "a host function" : `a host ${object.constructor?.name ?? "object"}`;
341
+ this.lose(what);
342
+ return { t: "Lost", f: [what] };
343
+ }
344
+ // A value an extension returned, as its `snapshot.encode` saves it: plain data, checked before it is copied.
345
+ hostValue(extension, root) {
346
+ const known = this.roots.get(root);
347
+ if (known !== undefined)
348
+ return known;
349
+ const data = plainData(this.env.hosts.encode(extension, root), extension, new Set());
350
+ const id = this.records.length;
351
+ const ref = ["r", id];
352
+ this.roots.set(root, ref);
353
+ this.records.push(undefined);
354
+ this.records[id] = { t: "HostValue", e: extension, d: this.value(data) };
355
+ return ref;
356
+ }
357
+ lose(what) {
358
+ if (this.env.strict)
359
+ throw new SnapshotError(`Codec gap: ${what} has no data form.`);
360
+ this.env.lost.push(what);
361
+ }
362
+ spec(object) {
363
+ const spec = this.specs.byCtor.get(object.constructor);
364
+ if (spec === undefined)
365
+ throw new SnapshotError(`Codec gap: ${object.constructor.name} has no codec.`);
366
+ return spec;
367
+ }
368
+ // A class instance's saved fields, positional, with its `Obj` header when it is one. Fields the spec does not know
369
+ // are a codec gap: they would be silently dropped.
370
+ fields(object, spec, only) {
371
+ const record = object;
372
+ const fields = only ?? spec.fields;
373
+ if (only === undefined && spec.view === undefined) {
374
+ for (const key of Object.keys(object)) {
375
+ if (fields.includes(key) || spec.skip?.includes(key) || (spec.constants !== undefined && key in spec.constants))
376
+ continue;
377
+ if (spec.obj && (objFields.includes(key) || key === "tag"))
378
+ continue;
379
+ throw new SnapshotError(`Codec gap: ${spec.name}.${key} is not saved.`);
380
+ }
381
+ }
382
+ const values = only === undefined && spec.view !== undefined
383
+ ? spec.view(object).map((item) => this.value(item))
384
+ : fields.map((field) => (Object.hasOwn(object, field) ? this.value(record[field]) : ["-"]));
385
+ if (!(object instanceof Obj))
386
+ return { f: values };
387
+ const props = [];
388
+ for (const [key, slot] of object.props) {
389
+ props.push(typeof key === "symbol" ? this.value(key) : key);
390
+ if ("value" in slot) {
391
+ props.push(this.value(slot.value), (slot.writable ? 1 : 0) | (slot.enumerable ? 2 : 0) | (slot.configurable ? 4 : 0));
392
+ }
393
+ else
394
+ props.push(null, 8 | (slot.enumerable ? 2 : 0) | (slot.configurable ? 4 : 0));
395
+ }
396
+ return { f: values, p: object.proto === null ? null : this.value(object.proto), x: object.extensible, o: props };
397
+ }
398
+ error(error) {
399
+ const name = errorNames.get(error.constructor);
400
+ if (name === undefined) {
401
+ // A failure only ever reaches the program when it is thrown, so it is saved as what throwing a lost value does.
402
+ this.lose(`a host ${error.constructor.name}`);
403
+ return {
404
+ t: "PendingThrow",
405
+ ...this.fields(lostError(`An error of class ${error.constructor.name}`), this.specs.byName.get("PendingThrow")),
406
+ };
407
+ }
408
+ const fields = [];
409
+ for (const key of Object.keys(error)) {
410
+ if (key === "message" || key === "stack")
411
+ continue;
412
+ fields.push(key, this.value(error[key]));
413
+ }
414
+ return { t: "Error", c: name, m: error.message, e: fields };
415
+ }
416
+ }
417
+ // --- Decoding ---
418
+ /** Rebuilds the graph `encode` saved, filling anchors in place: the decoded roots. */
419
+ export const decode = (saved, env) => {
420
+ const decoder = new Decoder(saved.records, env);
421
+ for (let id = 0; id < saved.records.length; id++)
422
+ decoder.shell(id);
423
+ for (let id = 0; id < saved.records.length; id++)
424
+ decoder.fill(id);
425
+ decoder.finish();
426
+ return saved.roots.map((root) => decoder.value(root));
427
+ };
428
+ const invalid = (message) => {
429
+ throw new SnapshotError(`Invalid snapshot: ${message}`);
430
+ };
431
+ const isRecord = (value) => typeof value === "object" &&
432
+ value !== null &&
433
+ !Array.isArray(value) &&
434
+ typeof value.t === "string";
435
+ const list = (value, what) => Array.isArray(value) ? value : invalid(`${what} is not a list.`);
436
+ const text = (value, what) => typeof value === "string" ? value : invalid(`${what} is not text.`);
437
+ const count = (value, what) => Number.isSafeInteger(value) && value >= 0 ? value : invalid(`${what} is not a count.`);
438
+ const forbidden = new Set(["__proto__", "constructor", "prototype"]);
439
+ class Decoder {
440
+ records;
441
+ env;
442
+ shells;
443
+ filled;
444
+ // Derived state is rebuilt once every record is filled in, since it reads other records.
445
+ resets = [];
446
+ // Functions inside values extensions returned, wrapped again once every record is filled in.
447
+ hostFunctions = [];
448
+ // Those values, given back once each by their extension's `snapshot.decode`, by `HostValue` record.
449
+ hostValues = new Map();
450
+ specs;
451
+ constructor(records, env) {
452
+ this.records = records;
453
+ this.env = env;
454
+ this.specs = registry(env.specs);
455
+ this.shells = new Array(records.length);
456
+ this.filled = new Array(records.length).fill(false);
457
+ }
458
+ at(id) {
459
+ const record = this.records[id];
460
+ return isRecord(record) ? record : invalid(`record ${id} is malformed.`);
461
+ }
462
+ // Allocates the object a record restores, before anything is filled in, so references and cycles resolve.
463
+ shell(id) {
464
+ const known = this.shells[id];
465
+ if (known !== undefined)
466
+ return known;
467
+ const record = this.at(id);
468
+ const made = this.make(record, id);
469
+ this.shells[id] = made;
470
+ return made;
471
+ }
472
+ make(record, id) {
473
+ switch (record.t) {
474
+ case "Array":
475
+ return [];
476
+ case "Object":
477
+ return record.n === 1 ? Object.create(null) : {};
478
+ case "Map":
479
+ return record.a === undefined ? new Map() : this.anchor(text(record.a, "an anchor"), Map);
480
+ case "Set":
481
+ return new Set();
482
+ case "@": {
483
+ const name = text(record.n, "a built-in name");
484
+ const named = this.env.named(name);
485
+ if (named === undefined)
486
+ return invalid(`this runtime has no built-in or host global named ${name}.`);
487
+ const spec = this.classSpec(record.c);
488
+ if (named.constructor !== spec.ctor)
489
+ return invalid(`${name} is not a ${spec.name} in this runtime.`);
490
+ return named;
491
+ }
492
+ case "LostNative":
493
+ case "HostFunction":
494
+ return Object.create(Native.prototype);
495
+ case "HostValue":
496
+ return {};
497
+ case "Interruption":
498
+ return this.env.interruption();
499
+ case "Error": {
500
+ const name = text(record.c, "an error class");
501
+ const ctor = errorClasses.get(name) ?? invalid(`unknown error class ${name}.`);
502
+ const message = text(record.m, "an error message");
503
+ if (ctor === ToolError)
504
+ return toolError(message);
505
+ const made = Object.create(ctor.prototype);
506
+ Object.defineProperty(made, "message", {
507
+ value: message,
508
+ writable: true,
509
+ configurable: true,
510
+ enumerable: false,
511
+ });
512
+ return made;
513
+ }
514
+ case "URL":
515
+ return new URL(text(record.h, "a URL"));
516
+ case "URLSearchParams": {
517
+ if (record.o === undefined)
518
+ return new URLSearchParams(text(record.s, "search params"));
519
+ const owner = this.value(record.o);
520
+ return owner instanceof URL ? owner.searchParams : invalid(`record ${id} names no URL.`);
521
+ }
522
+ case "Headers": {
523
+ const entries = list(record.e, "headers").map((entry) => {
524
+ const pair = list(entry, "a header");
525
+ return [text(pair[0], "a header name"), text(pair[1], "a header value")];
526
+ });
527
+ return new Headers(entries);
528
+ }
529
+ case "ArrayBuffer":
530
+ return fromBase64(text(record.d, "bytes")).buffer;
531
+ case "Uint8Array": {
532
+ const buffer = this.value(record.b);
533
+ if (!(buffer instanceof ArrayBuffer))
534
+ return invalid(`record ${id} names no buffer.`);
535
+ const offset = count(record.o, "a byte offset");
536
+ const length = count(record.l, "a byte length");
537
+ if (offset + length > buffer.byteLength)
538
+ return invalid(`record ${id} reaches past its buffer.`);
539
+ return new Uint8Array(buffer, offset, length);
540
+ }
541
+ case "TextDecoder":
542
+ return new TextDecoder("utf-8", { fatal: record.f === true, ignoreBOM: record.i === true });
543
+ }
544
+ const spec = this.classSpec(record.t);
545
+ if (spec.name === "Native")
546
+ return invalid("a native is saved only by name.");
547
+ if (spec.anchor !== undefined)
548
+ return this.anchor(spec.anchor, spec.ctor);
549
+ return Object.create(spec.ctor.prototype);
550
+ }
551
+ anchor(name, ctor) {
552
+ const anchor = this.env.anchor(name);
553
+ if (anchor === undefined || anchor.constructor !== ctor)
554
+ return invalid(`unknown anchor ${name}.`);
555
+ return anchor;
556
+ }
557
+ classSpec(name) {
558
+ return this.specs.byName.get(text(name, "a class")) ?? invalid(`unknown record kind ${String(name)}.`);
559
+ }
560
+ fill(id) {
561
+ if (this.filled[id])
562
+ return;
563
+ this.filled[id] = true;
564
+ const record = this.at(id);
565
+ const target = this.shell(id);
566
+ switch (record.t) {
567
+ case "Array": {
568
+ const array = target;
569
+ if (record.v === undefined) {
570
+ const length = count(record.l, "an array length");
571
+ if (length > 4_294_967_295)
572
+ invalid("an array is too long.");
573
+ array.length = length;
574
+ const entries = list(record.s, "a sparse array");
575
+ for (let at = 0; at < entries.length; at += 2) {
576
+ const index = count(entries[at], "an array index");
577
+ if (index >= length)
578
+ invalid("an array index is past its length.");
579
+ array[index] = this.value(entries[at + 1]);
580
+ }
581
+ return;
582
+ }
583
+ const items = list(record.v, "an array");
584
+ items.forEach((item, at) => {
585
+ if (Array.isArray(item) && item[0] === "h")
586
+ return;
587
+ array[at] = this.value(item);
588
+ });
589
+ array.length = items.length;
590
+ return;
591
+ }
592
+ case "Object":
593
+ case "Error": {
594
+ const entries = list(record.e, record.t === "Error" ? "an error" : "an object");
595
+ for (let at = 0; at < entries.length; at += 2) {
596
+ const key = text(entries[at], "a key");
597
+ if (record.t === "Error" && forbidden.has(key))
598
+ invalid(`an error field is named ${key}.`);
599
+ Object.defineProperty(target, key, {
600
+ value: this.value(entries[at + 1]),
601
+ writable: true,
602
+ enumerable: true,
603
+ configurable: true,
604
+ });
605
+ }
606
+ return;
607
+ }
608
+ case "Map": {
609
+ const map = target;
610
+ if (record.a !== undefined)
611
+ map.clear();
612
+ const entries = list(record.e, "a map");
613
+ for (let at = 0; at < entries.length; at += 2)
614
+ map.set(this.value(entries[at]), this.value(entries[at + 1]));
615
+ return;
616
+ }
617
+ case "Set": {
618
+ const set = target;
619
+ for (const item of list(record.e, "a set"))
620
+ set.add(this.value(item));
621
+ return;
622
+ }
623
+ case "@":
624
+ this.fillClass(target, record, this.classSpec(record.c), true);
625
+ // Changed before it was saved, so it stays changed: a later save records it again.
626
+ return changed(target);
627
+ case "LostNative": {
628
+ this.fillClass(target, record, hostFunction, false);
629
+ const native = target;
630
+ const name = functionName(target);
631
+ native.tag = "Function";
632
+ native.call = (_, __, site) => {
633
+ throw lostError(`The function ${name}`, site);
634
+ };
635
+ native.construct = undefined;
636
+ native.callback = true;
637
+ return;
638
+ }
639
+ case "HostFunction":
640
+ this.fillClass(target, record, hostFunction, false);
641
+ this.hostFunctions.push([target, record]);
642
+ return;
643
+ case "HostValue":
644
+ case "Interruption":
645
+ case "URL":
646
+ case "URLSearchParams":
647
+ case "Headers":
648
+ case "ArrayBuffer":
649
+ case "Uint8Array":
650
+ case "TextDecoder":
651
+ return;
652
+ }
653
+ const spec = this.classSpec(record.t);
654
+ this.fillClass(target, record, spec, false);
655
+ }
656
+ fillClass(target, record, spec, named, only) {
657
+ const fields = only ?? spec.fields;
658
+ const values = list(record.f, `the fields of a ${spec.name}`);
659
+ if (values.length !== fields.length)
660
+ invalid(`a ${spec.name} has ${values.length} fields, not ${fields.length}.`);
661
+ if (spec.obj || named)
662
+ this.fillObj(target, record);
663
+ if (spec.constants !== undefined)
664
+ Object.assign(target, spec.constants);
665
+ fields.forEach((field, at) => {
666
+ const value = values[at];
667
+ if (Array.isArray(value) && value[0] === "-") {
668
+ delete target[field];
669
+ return;
670
+ }
671
+ target[field] = this.value(value);
672
+ });
673
+ const reset = spec.reset;
674
+ if (reset !== undefined)
675
+ this.resets.push(() => reset(target));
676
+ }
677
+ finish() {
678
+ for (const reset of this.resets)
679
+ reset();
680
+ if (this.hostFunctions.length === 0)
681
+ return;
682
+ const hosts = this.env.hosts ?? invalid("a function from an extension is saved, and this runtime has no extensions.");
683
+ for (const [target, record] of this.hostFunctions) {
684
+ const extension = text(record.e, "an extension");
685
+ const path = list(record.k, "a path").map((key) => typeof key === "number" ? count(key, "a path index") : text(key, "a path key"));
686
+ hosts.rewrap(target, {
687
+ extension,
688
+ root: this.hostValue(hosts, record.h, extension),
689
+ path,
690
+ label: text(record.l, "a label"),
691
+ });
692
+ }
693
+ }
694
+ // A value an extension returned, given back once by its `snapshot.decode` from the data it saved.
695
+ hostValue(hosts, ref, extension) {
696
+ const id = Array.isArray(ref) && ref[0] === "r" ? count(ref[1], "a record id") : invalid("a host value is not a record.");
697
+ const known = this.hostValues.get(id);
698
+ if (known !== undefined)
699
+ return known;
700
+ const record = id < this.records.length ? this.at(id) : invalid(`record ${id} does not exist.`);
701
+ if (record.t !== "HostValue" || record.e !== extension)
702
+ invalid(`record ${id} is not a value of ${extension}.`);
703
+ const root = hosts.decode(extension, this.value(record.d));
704
+ this.hostValues.set(id, root);
705
+ return root;
706
+ }
707
+ // An object's prototype, extensibility, and properties. A named object's accessors stay the ones it was made with.
708
+ fillObj(target, record) {
709
+ const proto = record.p === null ? null : this.value(record.p);
710
+ if (proto !== null && !(proto instanceof Obj))
711
+ invalid("a prototype is not an object.");
712
+ if (typeof record.x !== "boolean")
713
+ invalid("an object's extensibility is not a boolean.");
714
+ const entries = list(record.o, "an object's properties");
715
+ const props = new Map();
716
+ for (let at = 0; at < entries.length; at += 3) {
717
+ const raw = entries[at];
718
+ const key = typeof raw === "string" ? raw : this.value(raw);
719
+ if (typeof key !== "string" && typeof key !== "symbol")
720
+ invalid("a property key is not a string or symbol.");
721
+ const flags = count(entries[at + 2], "property flags");
722
+ const enumerable = (flags & 2) !== 0;
723
+ const configurable = (flags & 4) !== 0;
724
+ if ((flags & 8) !== 0) {
725
+ const original = target.props?.get(key);
726
+ if (original === undefined || "value" in original)
727
+ invalid(`the accessor ${String(key)} has no original.`);
728
+ const accessor = original;
729
+ props.set(key, { get: accessor.get, set: accessor.set, enumerable, configurable });
730
+ continue;
731
+ }
732
+ props.set(key, {
733
+ value: this.value(entries[at + 1]),
734
+ writable: (flags & 1) !== 0,
735
+ enumerable,
736
+ configurable,
737
+ });
738
+ }
739
+ const writable = target;
740
+ writable.intrinsic ??= 0;
741
+ writable.props = props;
742
+ writable.extensible = record.x;
743
+ writable.proto = proto;
744
+ }
745
+ value(value) {
746
+ switch (typeof value) {
747
+ case "string":
748
+ case "boolean":
749
+ return value;
750
+ case "number":
751
+ return Number.isFinite(value) ? value : invalid("a number is not finite.");
752
+ }
753
+ if (value === null)
754
+ return null;
755
+ if (!Array.isArray(value))
756
+ return invalid("a value is neither JSON data nor a tag.");
757
+ switch (value[0]) {
758
+ case "u":
759
+ return undefined;
760
+ case "n":
761
+ switch (value[1]) {
762
+ case "NaN":
763
+ return Number.NaN;
764
+ case "Infinity":
765
+ return Number.POSITIVE_INFINITY;
766
+ case "-Infinity":
767
+ return Number.NEGATIVE_INFINITY;
768
+ case "-0":
769
+ return -0;
770
+ }
771
+ return invalid(`unknown number ${String(value[1])}.`);
772
+ case "s":
773
+ return symbols.get(text(value[1], "a symbol")) ?? invalid(`unknown symbol ${String(value[1])}.`);
774
+ case "x":
775
+ return this.env.external?.(value[1]) ?? invalid(`unknown external value ${JSON.stringify(value[1])}.`);
776
+ case "i": {
777
+ const name = text(value[1], "a built-in name");
778
+ return this.env.named(name) ?? invalid(`this runtime has no built-in or host global named ${name}.`);
779
+ }
780
+ case "a":
781
+ return (this.env.node(text(value[1], "a source"), count(value[2], "a node index")) ??
782
+ invalid(`no node ${String(value[2])} in source ${String(value[1])}.`));
783
+ case "r": {
784
+ const id = count(value[1], "a record id");
785
+ if (id >= this.records.length)
786
+ invalid(`record ${id} does not exist.`);
787
+ return this.shell(id);
788
+ }
789
+ }
790
+ return invalid(`unknown tag ${String(value[0])}.`);
791
+ }
792
+ }
793
+ // What an extension's `snapshot.encode` gives must be plain data the codec copies and hands back to `decode`: JSON
794
+ // values and Uint8Arrays. Views (such as a `Buffer` slice on a shared slab) are copied into standalone `Uint8Array`s.
795
+ const plainData = (data, extension, seen) => {
796
+ if (data === null || typeof data === "string" || typeof data === "boolean")
797
+ return data;
798
+ if (typeof data === "number" && Number.isFinite(data))
799
+ return data;
800
+ if (data instanceof Uint8Array) {
801
+ return data.constructor === Uint8Array && data.byteOffset === 0 && data.byteLength === data.buffer.byteLength
802
+ ? data
803
+ : new Uint8Array(data);
804
+ }
805
+ const fail = (what) => {
806
+ throw new SnapshotError(`The extension "${extension}" saved a value it returned as data holding ${what}; snapshot.encode must give plain data (JSON values and Uint8Arrays).`);
807
+ };
808
+ if (typeof data !== "object") {
809
+ return fail(data === undefined ? "undefined" : typeof data === "number" ? String(data) : `a ${typeof data}`);
810
+ }
811
+ if (seen.has(data))
812
+ return fail("a circular reference");
813
+ const proto = Object.getPrototypeOf(data);
814
+ if (!Array.isArray(data) && proto !== Object.prototype && proto !== null) {
815
+ const name = data.constructor?.name ?? "object";
816
+ return fail(`${/^[AEIOU]/.test(name) ? "an" : "a"} ${name}`);
817
+ }
818
+ seen.add(data);
819
+ if (Array.isArray(data)) {
820
+ const out = data.map((item) => plainData(item, extension, seen));
821
+ seen.delete(data);
822
+ return out;
823
+ }
824
+ const out = proto === null ? Object.create(null) : {};
825
+ for (const [key, item] of Object.entries(data))
826
+ out[key] = plainData(item, extension, seen);
827
+ seen.delete(data);
828
+ return out;
829
+ };
830
+ const functionName = (fn) => {
831
+ const slot = fn.props.get("name");
832
+ return slot !== undefined && "value" in slot && typeof slot.value === "string" && slot.value !== ""
833
+ ? slot.value
834
+ : "(anonymous)";
835
+ };
836
+ const base64 = (bytes) => {
837
+ let binary = "";
838
+ for (let at = 0; at < bytes.length; at += 0x8000)
839
+ binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000));
840
+ return btoa(binary);
841
+ };
842
+ const fromBase64 = (encoded) => {
843
+ const binary = atob(encoded);
844
+ const bytes = new Uint8Array(binary.length);
845
+ for (let at = 0; at < binary.length; at++)
846
+ bytes[at] = binary.charCodeAt(at);
847
+ return bytes;
848
+ };