@opencode/codemode 0.0.0-dev-892 → 0.0.0-dev-900

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 (117) hide show
  1. package/README.md +3 -0
  2. package/dist/codemode.d.ts +2 -0
  3. package/dist/codemode.js +10 -4
  4. package/dist/vm/async.d.ts +78 -0
  5. package/dist/vm/async.js +335 -0
  6. package/dist/vm/code.d.ts +122 -0
  7. package/dist/vm/code.js +407 -0
  8. package/dist/vm/compiler/compile.d.ts +13 -0
  9. package/dist/vm/compiler/compile.js +1477 -0
  10. package/dist/vm/compiler/scope.d.ts +74 -0
  11. package/dist/vm/compiler/scope.js +515 -0
  12. package/dist/vm/data.d.ts +7 -0
  13. package/dist/vm/data.js +13 -0
  14. package/dist/vm/generators.d.ts +42 -0
  15. package/dist/vm/generators.js +413 -0
  16. package/dist/vm/host.d.ts +103 -0
  17. package/dist/vm/host.js +226 -0
  18. package/dist/vm/index.d.ts +3 -0
  19. package/dist/vm/index.js +3 -0
  20. package/dist/vm/internal-prelude.d.ts +45 -0
  21. package/dist/vm/internal-prelude.js +534 -0
  22. package/dist/vm/opcodes.d.ts +222 -0
  23. package/dist/vm/opcodes.js +235 -0
  24. package/dist/vm/prelude/bytecode.d.ts +18 -0
  25. package/dist/vm/prelude/bytecode.js +31 -0
  26. package/dist/vm/prelude/bytecode.json +1 -0
  27. package/dist/vm/prelude/helpers.d.ts +8 -0
  28. package/dist/vm/prelude/helpers.js +258 -0
  29. package/dist/vm/prelude/prelude.d.ts +21 -0
  30. package/dist/vm/prelude/prelude.js +53 -0
  31. package/dist/vm/prelude/source.d.ts +1 -0
  32. package/dist/vm/prelude/source.js +652 -0
  33. package/dist/vm/runtime/callback.d.ts +25 -0
  34. package/dist/vm/runtime/callback.js +51 -0
  35. package/dist/vm/runtime/driver.d.ts +41 -0
  36. package/dist/vm/runtime/driver.js +142 -0
  37. package/dist/vm/runtime/errors.d.ts +23 -0
  38. package/dist/vm/runtime/errors.js +169 -0
  39. package/dist/vm/runtime/execute.d.ts +22 -0
  40. package/dist/vm/runtime/execute.js +278 -0
  41. package/dist/vm/runtime/extensions.d.ts +16 -0
  42. package/dist/vm/runtime/extensions.js +270 -0
  43. package/dist/vm/runtime/generators.d.ts +6 -0
  44. package/dist/vm/runtime/generators.js +44 -0
  45. package/dist/vm/runtime/globals.d.ts +6 -0
  46. package/dist/vm/runtime/globals.js +137 -0
  47. package/dist/vm/runtime/interpreter.d.ts +50 -0
  48. package/dist/vm/runtime/interpreter.js +94 -0
  49. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  50. package/dist/vm/runtime/intrinsic-names.js +166 -0
  51. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  52. package/dist/vm/runtime/intrinsics.js +111 -0
  53. package/dist/vm/runtime/limits.d.ts +10 -0
  54. package/dist/vm/runtime/limits.js +19 -0
  55. package/dist/vm/runtime/model.d.ts +58 -0
  56. package/dist/vm/runtime/model.js +57 -0
  57. package/dist/vm/runtime/modules.d.ts +4 -0
  58. package/dist/vm/runtime/modules.js +33 -0
  59. package/dist/vm/runtime/native.d.ts +19 -0
  60. package/dist/vm/runtime/native.js +41 -0
  61. package/dist/vm/runtime/objects.d.ts +403 -0
  62. package/dist/vm/runtime/objects.js +784 -0
  63. package/dist/vm/runtime/operations.d.ts +49 -0
  64. package/dist/vm/runtime/operations.js +288 -0
  65. package/dist/vm/runtime/promises.d.ts +55 -0
  66. package/dist/vm/runtime/promises.js +232 -0
  67. package/dist/vm/runtime/references.d.ts +8 -0
  68. package/dist/vm/runtime/references.js +51 -0
  69. package/dist/vm/runtime/signals.d.ts +69 -0
  70. package/dist/vm/runtime/signals.js +68 -0
  71. package/dist/vm/runtime/source.d.ts +29 -0
  72. package/dist/vm/runtime/source.js +63 -0
  73. package/dist/vm/runtime/table.d.ts +43 -0
  74. package/dist/vm/runtime/table.js +132 -0
  75. package/dist/vm/scheduler.d.ts +178 -0
  76. package/dist/vm/scheduler.js +63 -0
  77. package/dist/vm/snapshot/codec.d.ts +88 -0
  78. package/dist/vm/snapshot/codec.js +752 -0
  79. package/dist/vm/snapshot/snapshot.d.ts +39 -0
  80. package/dist/vm/snapshot/snapshot.js +69 -0
  81. package/dist/vm/snapshot.d.ts +29 -0
  82. package/dist/vm/snapshot.js +304 -0
  83. package/dist/vm/stdlib/array.d.ts +16 -0
  84. package/dist/vm/stdlib/array.js +311 -0
  85. package/dist/vm/stdlib/bytes.d.ts +11 -0
  86. package/dist/vm/stdlib/bytes.js +222 -0
  87. package/dist/vm/stdlib/collections.d.ts +7 -0
  88. package/dist/vm/stdlib/collections.js +188 -0
  89. package/dist/vm/stdlib/console.d.ts +6 -0
  90. package/dist/vm/stdlib/console.js +93 -0
  91. package/dist/vm/stdlib/date.d.ts +2 -0
  92. package/dist/vm/stdlib/date.js +123 -0
  93. package/dist/vm/stdlib/headers.d.ts +2 -0
  94. package/dist/vm/stdlib/headers.js +92 -0
  95. package/dist/vm/stdlib/iterator.d.ts +2 -0
  96. package/dist/vm/stdlib/iterator.js +30 -0
  97. package/dist/vm/stdlib/json.d.ts +3 -0
  98. package/dist/vm/stdlib/json.js +42 -0
  99. package/dist/vm/stdlib/math.d.ts +3 -0
  100. package/dist/vm/stdlib/math.js +73 -0
  101. package/dist/vm/stdlib/number.d.ts +3 -0
  102. package/dist/vm/stdlib/number.js +72 -0
  103. package/dist/vm/stdlib/object.d.ts +6 -0
  104. package/dist/vm/stdlib/object.js +201 -0
  105. package/dist/vm/stdlib/regexp.d.ts +8 -0
  106. package/dist/vm/stdlib/regexp.js +119 -0
  107. package/dist/vm/stdlib/string.d.ts +2 -0
  108. package/dist/vm/stdlib/string.js +272 -0
  109. package/dist/vm/stdlib/url.d.ts +25 -0
  110. package/dist/vm/stdlib/url.js +255 -0
  111. package/dist/vm/stdlib/value.d.ts +6 -0
  112. package/dist/vm/stdlib/value.js +32 -0
  113. package/dist/vm/stdlib/web.d.ts +5 -0
  114. package/dist/vm/stdlib/web.js +97 -0
  115. package/dist/vm/vm.d.ts +224 -0
  116. package/dist/vm/vm.js +2921 -0
  117. package/package.json +5 -2
@@ -0,0 +1,137 @@
1
+ import { Arr, BoundFn, Callable, coerceToInteger, get, Obj } from "./objects.js";
2
+ import { arrayGlobal } from "../stdlib/array.js";
3
+ import { textDecoderGlobal, textEncoderGlobal, uint8ArrayGlobal } from "../stdlib/bytes.js";
4
+ import { mapGlobal, setGlobal, weakMapGlobal, weakSetGlobal } from "../stdlib/collections.js";
5
+ import { consoleGlobal } from "../stdlib/console.js";
6
+ import { dateGlobal } from "../stdlib/date.js";
7
+ import { jsonGlobal } from "../stdlib/json.js";
8
+ import { mathGlobal } from "../stdlib/math.js";
9
+ import { booleanGlobal, numberGlobal } from "../stdlib/number.js";
10
+ import { objectGlobal } from "../stdlib/object.js";
11
+ import { regexpGlobal } from "../stdlib/regexp.js";
12
+ import { stringGlobal } from "../stdlib/string.js";
13
+ import { uriGlobal, urlGlobal, urlSearchParamsGlobal } from "../stdlib/url.js";
14
+ import { headersGlobal } from "../stdlib/headers.js";
15
+ import { iteratorGlobals } from "../stdlib/iterator.js";
16
+ import { coercion } from "../stdlib/value.js";
17
+ import { base64Global, cryptoGlobal, structuredCloneGlobal } from "../stdlib/web.js";
18
+ import { ToolReference } from "../../tool-runtime.js";
19
+ import { errorGlobal } from "./errors.js";
20
+ import { errorTypes } from "./intrinsics.js";
21
+ import { constants, constructor, methods, native, receiver } from "./native.js";
22
+ import { AsyncIteratorSymbol, IteratorSymbol, typeError } from "./model.js";
23
+ import { checkArrayLength } from "./limits.js";
24
+ import { generatorGlobals } from "./generators.js";
25
+ import { promiseGlobal } from "./promises.js";
26
+ import { Invoke } from "./signals.js";
27
+ // Function.prototype.constructor exists so `fn.constructor === Function` holds; dynamic code is unsupported.
28
+ const functionGlobal = (ctx) => {
29
+ const reject = () => {
30
+ throw typeError("The Function constructor is not supported; write the function inline.");
31
+ };
32
+ const target = (thisValue, method) => receiver(Callable, thisValue, `Function.prototype.${method}`);
33
+ methods(ctx.builtins, ctx.builtins.Function, [
34
+ ["call", 1, (thisValue, args, site) => new Invoke(target(thisValue, "call"), args[0], args.slice(1), site)],
35
+ [
36
+ "apply",
37
+ 2,
38
+ (thisValue, args, site) => new Invoke(target(thisValue, "apply"), args[0], listFromArrayLike(args[1]), site),
39
+ ],
40
+ [
41
+ "bind",
42
+ 1,
43
+ (thisValue, args) => new BoundFn(ctx.builtins.Function, target(thisValue, "bind"), args[0], args.slice(1)),
44
+ ],
45
+ ]);
46
+ return constructor(ctx.builtins, ctx.builtins.Function, {
47
+ name: "Function",
48
+ length: 1,
49
+ call: reject,
50
+ construct: reject,
51
+ });
52
+ };
53
+ // CreateListFromArrayLike: `apply` reads `length` and the indexed properties of any object.
54
+ const listFromArrayLike = (value) => {
55
+ if (value === undefined || value === null)
56
+ return [];
57
+ if (value instanceof Arr)
58
+ return [...value.items];
59
+ if (!(value instanceof Obj))
60
+ throw typeError("Function.prototype.apply expects an array-like argument list.");
61
+ const length = Math.max(0, coerceToInteger(get(value, "length")));
62
+ checkArrayLength(length);
63
+ return Array.from({ length }, (_, index) => get(value, String(index)));
64
+ };
65
+ const symbolGlobal = (ctx) => {
66
+ const symbol = native(ctx.builtins, {
67
+ name: "Symbol",
68
+ call: () => {
69
+ throw typeError("Symbol is not callable; only Symbol.asyncIterator and Symbol.iterator are available.");
70
+ },
71
+ callback: false,
72
+ });
73
+ constants(symbol, { asyncIterator: AsyncIteratorSymbol, iterator: IteratorSymbol });
74
+ return symbol;
75
+ };
76
+ // A table rather than a list so the names are known before any runtime exists.
77
+ const table = {
78
+ tools: () => new ToolReference([]),
79
+ search: (ctx) => native(ctx.builtins, { name: "search", call: (_, args) => ctx.search(args), callback: false }),
80
+ require: (ctx) => native(ctx.builtins, {
81
+ name: "require",
82
+ length: 1,
83
+ call: (_, args, site) => {
84
+ const specifier = args[0];
85
+ if (typeof specifier !== "string")
86
+ throw typeError("require expects a module name string.");
87
+ return ctx.module(specifier, site);
88
+ },
89
+ }),
90
+ undefined: () => undefined,
91
+ NaN: () => NaN,
92
+ Infinity: () => Infinity,
93
+ Object: (ctx) => objectGlobal(ctx),
94
+ Function: (ctx) => functionGlobal(ctx),
95
+ Array: (ctx) => arrayGlobal(ctx),
96
+ Math: (ctx) => mathGlobal(ctx),
97
+ JSON: (ctx) => jsonGlobal(ctx),
98
+ console: (ctx) => consoleGlobal(ctx),
99
+ Promise: (ctx) => promiseGlobal(ctx),
100
+ Symbol: (ctx) => symbolGlobal(ctx),
101
+ Iterator: (ctx) => iteratorGlobals(ctx),
102
+ Number: (ctx) => numberGlobal(ctx),
103
+ String: (ctx) => stringGlobal(ctx),
104
+ Boolean: (ctx) => booleanGlobal(ctx),
105
+ parseInt: (ctx) => coercion(ctx, "parseInt", 2),
106
+ parseFloat: (ctx) => coercion(ctx, "parseFloat"),
107
+ isFinite: (ctx) => coercion(ctx, "isFinite"),
108
+ isNaN: (ctx) => coercion(ctx, "isNaN"),
109
+ Date: (ctx) => dateGlobal(ctx),
110
+ RegExp: (ctx) => regexpGlobal(ctx),
111
+ Map: (ctx) => mapGlobal(ctx),
112
+ Set: (ctx) => setGlobal(ctx),
113
+ WeakMap: (ctx) => weakMapGlobal(ctx),
114
+ WeakSet: (ctx) => weakSetGlobal(ctx),
115
+ URL: (ctx) => urlGlobal(ctx),
116
+ URLSearchParams: (ctx) => urlSearchParamsGlobal(ctx),
117
+ Headers: (ctx) => headersGlobal(ctx),
118
+ Uint8Array: (ctx) => uint8ArrayGlobal(ctx),
119
+ TextEncoder: (ctx) => textEncoderGlobal(ctx),
120
+ TextDecoder: (ctx) => textDecoderGlobal(ctx),
121
+ encodeURI: (ctx) => uriGlobal(ctx, "encodeURI"),
122
+ encodeURIComponent: (ctx) => uriGlobal(ctx, "encodeURIComponent"),
123
+ decodeURI: (ctx) => uriGlobal(ctx, "decodeURI"),
124
+ decodeURIComponent: (ctx) => uriGlobal(ctx, "decodeURIComponent"),
125
+ atob: (ctx) => base64Global(ctx, "atob"),
126
+ btoa: (ctx) => base64Global(ctx, "btoa"),
127
+ crypto: (ctx) => cryptoGlobal(ctx),
128
+ structuredClone: (ctx) => structuredCloneGlobal(ctx),
129
+ ...Object.fromEntries(errorTypes.map((type) => [type, (ctx) => errorGlobal(type, ctx)])),
130
+ };
131
+ /** Names bound in every program before extensions apply. */
132
+ export const globalNames = new Set(Object.keys(table));
133
+ /** The immutable global bindings of every program, in declaration order. */
134
+ export const globals = (ctx) => {
135
+ generatorGlobals(ctx);
136
+ return Object.entries(table).map(([name, factory]) => [name, factory(ctx)]);
137
+ };
@@ -0,0 +1,50 @@
1
+ import type { ToolRuntime } from "../../tool-runtime.js";
2
+ import type { ExtensionRequest } from "../scheduler.js";
3
+ import { Vm } from "../vm.js";
4
+ import type { Builtins } from "./intrinsics.js";
5
+ import { IntrinsicNames } from "./intrinsic-names.js";
6
+ import { type AstNode, type Binding } from "./model.js";
7
+ import { Obj, type Value } from "./objects.js";
8
+ import { Prelude } from "../prelude/prelude.js";
9
+ import { Push } from "./signals.js";
10
+ import type { NodeId, Source } from "./source.js";
11
+ /** One program execution: the tool bridge, the VM that runs it, captured logs, and the global scope built once. */
12
+ export declare class Interpreter<R> {
13
+ readonly tools: ToolRuntime<R>;
14
+ readonly builtins: Builtins;
15
+ readonly logs: Array<string>;
16
+ /** Runs program code, and keeps the job queue, promises, and host calls the program waits on. */
17
+ readonly vm: Vm;
18
+ /** Names for this runtime's intrinsics, taken before any program code can change a built-in. */
19
+ readonly intrinsics: IntrinsicNames;
20
+ /** The built-ins written in Code Mode, and the scope they close over. */
21
+ readonly prelude: Prelude;
22
+ /** Makes the Effect an extension function's host work runs as; set by the extension bridge. */
23
+ extensionWork: ((request: ExtensionRequest) => unknown) | undefined;
24
+ /** The parsed sources this execution runs, by id, so a `NodeId` resolves to its node. */
25
+ readonly sources: Map<string, Source>;
26
+ /** The global bindings: the intrinsics, the host's globals, and the program's bindings. */
27
+ readonly globalScope: Map<string, Binding>;
28
+ private readonly modules;
29
+ private readonly namespaces;
30
+ constructor(options: {
31
+ readonly tools: ToolRuntime<R>;
32
+ readonly builtins: Builtins;
33
+ readonly logs?: Array<string>;
34
+ /** The host's globals (extensions, a test harness): made again, the same way, when a saved run is restored. */
35
+ readonly globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
36
+ /** Data bound for this program, part of its saved state; host globals of the same name win. */
37
+ readonly bindings?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
38
+ });
39
+ /** A module, as `require` returns it and a default import binds it: a global, by its Node module name. */
40
+ module(specifier: string, site?: AstNode): Value;
41
+ /**
42
+ * What `import * as` and `import()` see: the module's own properties, and the module itself as `default`, the way
43
+ * Node presents a CommonJS module.
44
+ */
45
+ namespace(specifier: string, site?: AstNode): Obj;
46
+ /** The node a `NodeId` names, in one of this execution's sources. */
47
+ node(id: NodeId): AstNode | undefined;
48
+ /** The built-in search: its result is usable directly, and can also be awaited or chained like a Promise. */
49
+ search(args: Array<Value>): Push;
50
+ }
@@ -0,0 +1,94 @@
1
+ import { Vm } from "../vm.js";
2
+ import { globals } from "./globals.js";
3
+ import { IntrinsicNames } from "./intrinsic-names.js";
4
+ import { PendingThrow } from "./model.js";
5
+ import { moduleName, resolveModule } from "./modules.js";
6
+ import { define, entries, makingIntrinsics, nativeRule, Obj } from "./objects.js";
7
+ import { Prelude } from "../prelude/prelude.js";
8
+ import { Push } from "./signals.js";
9
+ /** One program execution: the tool bridge, the VM that runs it, captured logs, and the global scope built once. */
10
+ export class Interpreter {
11
+ tools;
12
+ builtins;
13
+ logs;
14
+ /** Runs program code, and keeps the job queue, promises, and host calls the program waits on. */
15
+ vm;
16
+ /** Names for this runtime's intrinsics, taken before any program code can change a built-in. */
17
+ intrinsics;
18
+ /** The built-ins written in Code Mode, and the scope they close over. */
19
+ prelude;
20
+ /** Makes the Effect an extension function's host work runs as; set by the extension bridge. */
21
+ extensionWork;
22
+ /** The parsed sources this execution runs, by id, so a `NodeId` resolves to its node. */
23
+ sources = new Map();
24
+ /** The global bindings: the intrinsics, the host's globals, and the program's bindings. */
25
+ globalScope;
26
+ modules = new Map();
27
+ namespaces = new Map();
28
+ constructor(options) {
29
+ this.tools = options.tools;
30
+ this.builtins = options.builtins;
31
+ this.logs = options.logs ?? [];
32
+ // Program code has no receiver: top-level `this` is undefined, as in a module.
33
+ this.globalScope = new Map([["this", { value: undefined }]]);
34
+ // Everything made from here to the host globals is an intrinsic, with a static id (see `IntrinsicNames`).
35
+ const [[intrinsics, prelude], made] = makingIntrinsics(Object.values(this.builtins), () => {
36
+ const intrinsics = globals(this);
37
+ return [intrinsics, new Prelude(this, intrinsics)];
38
+ });
39
+ this.prelude = prelude;
40
+ const hosts = options.globals?.(this) ?? [];
41
+ this.intrinsics = new IntrinsicNames(made, {
42
+ globals: intrinsics,
43
+ builtins: this.builtins,
44
+ internals: [
45
+ ["Prelude", this.prelude.functions],
46
+ ["PreludeHelpers", this.prelude.helpers],
47
+ ],
48
+ }, hosts);
49
+ for (const [name, value] of [...intrinsics, ...(options.bindings?.(this) ?? []), ...hosts]) {
50
+ this.globalScope.set(name, { value });
51
+ }
52
+ nativeRule.sealed.add(this.builtins.Function);
53
+ // The VM never runs host work itself, so it does not need the services that work runs with.
54
+ this.vm = new Vm(this);
55
+ }
56
+ /** A module, as `require` returns it and a default import binds it: a global, by its Node module name. */
57
+ module(specifier, site) {
58
+ const name = moduleName(specifier);
59
+ const cached = this.modules.get(name);
60
+ if (cached !== undefined)
61
+ return cached;
62
+ const module = resolveModule(name, (global) => this.globalScope.get(global)?.value);
63
+ if (module === undefined)
64
+ throw new PendingThrow("Error", `Cannot import "${specifier}": it isn't available in Code Mode, which can't load packages or files. Use the provided globals, or call tools through \`tools\`.`, site);
65
+ this.modules.set(name, module);
66
+ return module;
67
+ }
68
+ /**
69
+ * What `import * as` and `import()` see: the module's own properties, and the module itself as `default`, the way
70
+ * Node presents a CommonJS module.
71
+ */
72
+ namespace(specifier, site) {
73
+ const module = this.module(specifier, site);
74
+ const name = moduleName(specifier);
75
+ const cached = this.namespaces.get(name);
76
+ if (cached)
77
+ return cached;
78
+ const namespace = new Obj(null);
79
+ if (module instanceof Obj)
80
+ for (const [key, value] of entries(module))
81
+ define(namespace, key, value);
82
+ define(namespace, "default", module);
83
+ this.namespaces.set(name, namespace);
84
+ return namespace;
85
+ }
86
+ /** The node a `NodeId` names, in one of this execution's sources. */
87
+ node(id) {
88
+ return this.sources.get(id.source)?.node(id);
89
+ }
90
+ /** The built-in search: its result is usable directly, and can also be awaited or chained like a Promise. */
91
+ search(args) {
92
+ return new Push("search", [args]);
93
+ }
94
+ }
@@ -0,0 +1,56 @@
1
+ import type { Builtins } from "./intrinsics.js";
2
+ import { Obj, type Value } from "./objects.js";
3
+ /**
4
+ * Deterministic names for one runtime's intrinsic objects, so saved state can refer to a built-in by name instead of
5
+ * copying it, and whether each one changed since the runtime was made.
6
+ *
7
+ * - **Static ids.** Every object made with the intrinsics (`createBuiltins`, the globals, the prelude) has an id: its
8
+ * creation index, which is the same in every runtime because making them is deterministic (see `makingIntrinsics`).
9
+ * The ids are named once per process, by a breadth-first walk of the first runtime made, before any program runs:
10
+ * from the global names (`Array.prototype.map`), then `%Name%` for built-in prototypes the walk cannot reach
11
+ * (`%Generator%`) and the prelude's internals, and what is reachable from them. The first path found names a value.
12
+ * No later runtime walks anything.
13
+ * - **`@host` names.** The host's globals (extensions, a test harness) differ between runtimes, so each runtime names
14
+ * them itself, `@name`, by a walk over only the objects they reach that have no static id. Host lists are small.
15
+ * - **Dirty bits.** `Obj.intrinsic` is the id plus one while the object is as made, negated once it changes. Every
16
+ * write to an object's properties, prototype, extensibility or elements marks it (`changed` in objects.ts), and so
17
+ * does restoring it from a saved record, so a run suspended twice keeps what changed before the first suspend.
18
+ */
19
+ export declare class IntrinsicNames {
20
+ /** The objects made with the intrinsics, by id. */
21
+ private readonly made;
22
+ private readonly hostValues;
23
+ private readonly hostNames;
24
+ private readonly hostIndex;
25
+ private named;
26
+ constructor(
27
+ /** The objects made with the intrinsics, by id. */
28
+ made: ReadonlyArray<Obj>, roots: Roots, hosts?: ReadonlyArray<readonly [string, Value]>);
29
+ /** The named intrinsics, in name order (see `all`). */
30
+ get values(): ReadonlyArray<Obj>;
31
+ /** The name of an intrinsic, or undefined for any other object. */
32
+ nameOf(value: Obj): string | undefined;
33
+ /** The intrinsic a name refers to. */
34
+ valueOf(name: string): Obj | undefined;
35
+ /** Every name: the static ones in walk order, then the host globals'. */
36
+ all(): ReadonlyArray<string>;
37
+ /** The host globals' names, `@name`, in walk order. */
38
+ hosts(): ReadonlyArray<string>;
39
+ /**
40
+ * The named intrinsics a saved state has to record: those changed since the runtime was made, and host values of
41
+ * classes whose state is not their properties (an extension's Map), which count as changed.
42
+ */
43
+ changed(): Array<Obj>;
44
+ private isStatic;
45
+ }
46
+ /** Whether a named object is still as the runtime made it, so its name alone restores it. */
47
+ export declare const unchanged: (value: Obj) => boolean;
48
+ /** The static names, in walk order, once a runtime has been made in this process. */
49
+ export declare const staticNames: () => ReadonlyArray<string>;
50
+ /** Where the walk that names the static intrinsics starts. */
51
+ export type Roots = {
52
+ readonly globals: ReadonlyArray<readonly [string, Value]>;
53
+ readonly builtins: Builtins;
54
+ /** Internal objects no global reaches (the prelude's functions and helpers), named like the builtins. */
55
+ readonly internals: ReadonlyArray<readonly [string, Obj]>;
56
+ };
@@ -0,0 +1,166 @@
1
+ import { AsyncIteratorSymbol, IteratorSymbol } from "./model.js";
2
+ import { Arr, Fn, Native, Obj } from "./objects.js";
3
+ /**
4
+ * Deterministic names for one runtime's intrinsic objects, so saved state can refer to a built-in by name instead of
5
+ * copying it, and whether each one changed since the runtime was made.
6
+ *
7
+ * - **Static ids.** Every object made with the intrinsics (`createBuiltins`, the globals, the prelude) has an id: its
8
+ * creation index, which is the same in every runtime because making them is deterministic (see `makingIntrinsics`).
9
+ * The ids are named once per process, by a breadth-first walk of the first runtime made, before any program runs:
10
+ * from the global names (`Array.prototype.map`), then `%Name%` for built-in prototypes the walk cannot reach
11
+ * (`%Generator%`) and the prelude's internals, and what is reachable from them. The first path found names a value.
12
+ * No later runtime walks anything.
13
+ * - **`@host` names.** The host's globals (extensions, a test harness) differ between runtimes, so each runtime names
14
+ * them itself, `@name`, by a walk over only the objects they reach that have no static id. Host lists are small.
15
+ * - **Dirty bits.** `Obj.intrinsic` is the id plus one while the object is as made, negated once it changes. Every
16
+ * write to an object's properties, prototype, extensibility or elements marks it (`changed` in objects.ts), and so
17
+ * does restoring it from a saved record, so a run suspended twice keeps what changed before the first suspend.
18
+ */
19
+ export class IntrinsicNames {
20
+ made;
21
+ hostValues = [];
22
+ hostNames = [];
23
+ hostIndex = new Map();
24
+ named;
25
+ constructor(
26
+ /** The objects made with the intrinsics, by id. */
27
+ made, roots, hosts = []) {
28
+ this.made = made;
29
+ made.forEach((value, id) => {
30
+ value.intrinsic = id + 1;
31
+ });
32
+ table ??= walk(made, roots);
33
+ if (made.length !== table.count) {
34
+ throw new Error(`This runtime made ${made.length} intrinsics, and the first one made ${table.count}.`);
35
+ }
36
+ const visit = (value, name) => {
37
+ if (!(value instanceof Obj) || this.hostIndex.has(value) || this.isStatic(value))
38
+ return;
39
+ this.hostIndex.set(value, this.hostValues.length);
40
+ this.hostValues.push(value);
41
+ this.hostNames.push(name());
42
+ value.intrinsic = table.count + this.hostValues.length;
43
+ };
44
+ let next = 0;
45
+ for (const [name, value] of hosts) {
46
+ visit(value, () => `@${name}`);
47
+ for (; next < this.hostValues.length; next++) {
48
+ const item = this.hostValues[next];
49
+ const base = this.hostNames[next];
50
+ for (const [key, slot] of item.props)
51
+ if ("value" in slot)
52
+ visit(slot.value, () => member(base, key));
53
+ if (item.proto !== null)
54
+ visit(item.proto, () => member(base, prototypeKey));
55
+ }
56
+ }
57
+ }
58
+ /** The named intrinsics, in name order (see `all`). */
59
+ get values() {
60
+ return (this.named ??= [...table.order.map((id) => this.made[id]), ...this.hostValues]);
61
+ }
62
+ /** The name of an intrinsic, or undefined for any other object. */
63
+ nameOf(value) {
64
+ if (this.isStatic(value)) {
65
+ const at = table.position[Math.abs(value.intrinsic) - 1];
66
+ return at < 0 ? undefined : table.names[at];
67
+ }
68
+ const host = this.hostIndex.get(value);
69
+ return host === undefined ? undefined : this.hostNames[host];
70
+ }
71
+ /** The intrinsic a name refers to. */
72
+ valueOf(name) {
73
+ const id = staticIds().get(name);
74
+ if (id !== undefined)
75
+ return this.made[id];
76
+ const host = this.hostNames.indexOf(name);
77
+ return host < 0 ? undefined : this.hostValues[host];
78
+ }
79
+ /** Every name: the static ones in walk order, then the host globals'. */
80
+ all() {
81
+ return [...table.names, ...this.hostNames];
82
+ }
83
+ /** The host globals' names, `@name`, in walk order. */
84
+ hosts() {
85
+ return this.hostNames;
86
+ }
87
+ /**
88
+ * The named intrinsics a saved state has to record: those changed since the runtime was made, and host values of
89
+ * classes whose state is not their properties (an extension's Map), which count as changed.
90
+ */
91
+ changed() {
92
+ return this.values.filter((value) => !unchanged(value));
93
+ }
94
+ isStatic(value) {
95
+ const id = Math.abs(value.intrinsic) - 1;
96
+ return id >= 0 && id < this.made.length && this.made[id] === value;
97
+ }
98
+ }
99
+ /** Whether a named object is still as the runtime made it, so its name alone restores it. */
100
+ export const unchanged = (value) => {
101
+ if (value.intrinsic <= 0)
102
+ return false;
103
+ const ctor = value.constructor;
104
+ return ctor === Obj || ctor === Arr || ctor === Native || ctor === Fn;
105
+ };
106
+ /** The static names, in walk order, once a runtime has been made in this process. */
107
+ export const staticNames = () => {
108
+ if (table === undefined)
109
+ throw new Error("No runtime has been made yet, so the intrinsics have no names.");
110
+ return table.names;
111
+ };
112
+ let table;
113
+ let ids;
114
+ const staticIds = () => (ids ??= new Map(table.names.map((name, at) => [name, table.order[at]])));
115
+ const walk = (made, roots) => {
116
+ const order = [];
117
+ const paths = [];
118
+ const position = made.map(() => -1);
119
+ const visit = (value, path) => {
120
+ if (!(value instanceof Obj))
121
+ return;
122
+ const id = value.intrinsic - 1;
123
+ if (id < 0 || made[id] !== value) {
124
+ throw new Error(`The intrinsic at ${describe(path)} was not made with this runtime's intrinsics.`);
125
+ }
126
+ if (position[id] !== -1)
127
+ return;
128
+ position[id] = order.length;
129
+ order.push(id);
130
+ paths.push(path);
131
+ };
132
+ const describe = (path) => typeof path === "string" ? path : member(describe(paths[path[0]]), path[1]);
133
+ let next = 0;
134
+ const drain = () => {
135
+ for (; next < order.length; next++) {
136
+ const item = made[order[next]];
137
+ for (const [key, slot] of item.props)
138
+ if ("value" in slot)
139
+ visit(slot.value, [next, key]);
140
+ if (item.proto !== null)
141
+ visit(item.proto, [next, prototypeKey]);
142
+ }
143
+ };
144
+ for (const [name, value] of roots.globals)
145
+ visit(value, name);
146
+ drain();
147
+ for (const [name, value] of [...Object.entries(roots.builtins), ...roots.internals]) {
148
+ visit(value, `%${name}%`);
149
+ drain();
150
+ }
151
+ const names = [];
152
+ for (const path of paths)
153
+ names.push(typeof path === "string" ? path : member(names[path[0]], path[1]));
154
+ return { count: made.length, order, names, position };
155
+ };
156
+ const prototypeKey = Symbol("[[Prototype]]");
157
+ const symbolNames = new Map([
158
+ [IteratorSymbol, "[Symbol.iterator]"],
159
+ [AsyncIteratorSymbol, "[Symbol.asyncIterator]"],
160
+ [prototypeKey, ".[[Prototype]]"],
161
+ ]);
162
+ const member = (base, key) => {
163
+ if (typeof key === "symbol")
164
+ return `${base}${symbolNames.get(key) ?? `[${String(key)}]`}`;
165
+ return /^[A-Za-z_$][\w$]*$/.test(key) ? `${base}.${key}` : `${base}[${JSON.stringify(key)}]`;
166
+ };
@@ -0,0 +1,15 @@
1
+ import { ErrorObj, Obj, type Value } from "./objects.js";
2
+ export declare const errorTypes: readonly ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError", "AggregateError"];
3
+ export type ErrorType = (typeof errorTypes)[number];
4
+ export declare const isErrorType: (name: string) => name is ErrorType;
5
+ declare const builtins: readonly ["Object", "Function", "Array", "String", "Number", "Boolean", "Date", "RegExp", "Map", "Set", "WeakMap", "WeakSet", "URL", "URLSearchParams", "Headers", "Uint8Array", "TextEncoder", "TextDecoder", "Promise", "PromiseLike", "Iterator", "IteratorHelper", "AsyncIterator", "Generator", "AsyncGenerator", "AsyncFromSyncIterator"];
6
+ /**
7
+ * The built-in prototype objects of one runtime, allocated empty in dependency order. The globals populate them
8
+ * and attach their constructors when the runtime is built.
9
+ */
10
+ export type Builtins = Readonly<Record<(typeof builtins)[number] | ErrorType, Obj>>;
11
+ export declare const createErrorValue: (prototype: Obj, message: string | undefined) => ErrorObj;
12
+ /** The prototype a primitive reads its methods from without being boxed; none for null, undefined, and symbols. */
13
+ export declare const primitivePrototype: (builtins: Builtins, value: Value) => Obj | undefined;
14
+ export declare const createBuiltins: () => Builtins;
15
+ export {};
@@ -0,0 +1,111 @@
1
+ import { define, hidden, Native, Arr, ErrorObj, Obj } from "./objects.js";
2
+ export const errorTypes = [
3
+ "Error",
4
+ "TypeError",
5
+ "RangeError",
6
+ "SyntaxError",
7
+ "ReferenceError",
8
+ "EvalError",
9
+ "URIError",
10
+ "AggregateError",
11
+ ];
12
+ export const isErrorType = (name) => errorTypes.includes(name);
13
+ const builtins = [
14
+ "Object",
15
+ "Function",
16
+ "Array",
17
+ "String",
18
+ "Number",
19
+ "Boolean",
20
+ "Date",
21
+ "RegExp",
22
+ "Map",
23
+ "Set",
24
+ "WeakMap",
25
+ "WeakSet",
26
+ "URL",
27
+ "URLSearchParams",
28
+ "Headers",
29
+ "Uint8Array",
30
+ "TextEncoder",
31
+ "TextDecoder",
32
+ "Promise",
33
+ "PromiseLike",
34
+ "Iterator",
35
+ "IteratorHelper",
36
+ "AsyncIterator",
37
+ "Generator",
38
+ "AsyncGenerator",
39
+ "AsyncFromSyncIterator",
40
+ ];
41
+ export const createErrorValue = (prototype, message) => {
42
+ const value = new ErrorObj(prototype);
43
+ if (message !== undefined)
44
+ define(value, "message", message, hidden);
45
+ return value;
46
+ };
47
+ /** The prototype a primitive reads its methods from without being boxed; none for null, undefined, and symbols. */
48
+ export const primitivePrototype = (builtins, value) => {
49
+ if (typeof value === "string")
50
+ return builtins.String;
51
+ if (typeof value === "number")
52
+ return builtins.Number;
53
+ if (typeof value === "boolean")
54
+ return builtins.Boolean;
55
+ return undefined;
56
+ };
57
+ export const createBuiltins = () => {
58
+ const object = new Obj(null);
59
+ // Function.prototype is itself callable and returns undefined.
60
+ const fn = new Native(object, { name: "", call: () => undefined });
61
+ const plain = () => new Obj(object);
62
+ const error = plain();
63
+ define(error, "name", "Error", hidden);
64
+ define(error, "message", "", hidden);
65
+ const derived = (type) => {
66
+ const proto = new Obj(error);
67
+ define(proto, "name", type, hidden);
68
+ define(proto, "message", "", hidden);
69
+ return proto;
70
+ };
71
+ const iterator = plain();
72
+ const asyncIterator = plain();
73
+ return {
74
+ Object: object,
75
+ Function: fn,
76
+ Array: new Arr(object),
77
+ String: plain(),
78
+ Number: plain(),
79
+ Boolean: plain(),
80
+ Date: plain(),
81
+ RegExp: plain(),
82
+ Map: plain(),
83
+ Set: plain(),
84
+ WeakMap: plain(),
85
+ WeakSet: plain(),
86
+ URL: plain(),
87
+ URLSearchParams: plain(),
88
+ Headers: plain(),
89
+ Uint8Array: plain(),
90
+ TextEncoder: plain(),
91
+ TextDecoder: plain(),
92
+ Promise: plain(),
93
+ /** What a synchronous result that can also be awaited inherits: then/catch/finally over a plain copy. */
94
+ PromiseLike: plain(),
95
+ Iterator: iterator,
96
+ IteratorHelper: new Obj(iterator),
97
+ AsyncIterator: asyncIterator,
98
+ Generator: new Obj(iterator),
99
+ AsyncGenerator: new Obj(asyncIterator),
100
+ /** CreateAsyncFromSyncIterator's objects; programs never see them. */
101
+ AsyncFromSyncIterator: new Obj(asyncIterator),
102
+ Error: error,
103
+ TypeError: derived("TypeError"),
104
+ RangeError: derived("RangeError"),
105
+ SyntaxError: derived("SyntaxError"),
106
+ ReferenceError: derived("ReferenceError"),
107
+ EvalError: derived("EvalError"),
108
+ URIError: derived("URIError"),
109
+ AggregateError: derived("AggregateError"),
110
+ };
111
+ };
@@ -0,0 +1,10 @@
1
+ /** Longest string a built-in or operator may produce. */
2
+ export declare const MAX_STRING_LENGTH: number;
3
+ /** Longest array a built-in may create or grow to. */
4
+ export declare const MAX_ARRAY_LENGTH = 10000000;
5
+ /** Most promises that may be pending at once. */
6
+ export declare const MAX_PENDING_PROMISES = 10000;
7
+ /** Deepest nesting a value may have when it crosses to or from the host. */
8
+ export declare const MAX_VALUE_DEPTH = 32;
9
+ export declare const checkStringLength: (length: number) => void;
10
+ export declare const checkArrayLength: (length: number) => void;
@@ -0,0 +1,19 @@
1
+ import { rangeError } from "./model.js";
2
+ // The timeout only fires between interpreter steps, so a single built-in must not be able to materialize an
3
+ // unbounded value. These bound what one call may build; programs cannot reach such sizes any other way.
4
+ /** Longest string a built-in or operator may produce. */
5
+ export const MAX_STRING_LENGTH = 1 << 24;
6
+ /** Longest array a built-in may create or grow to. */
7
+ export const MAX_ARRAY_LENGTH = 10_000_000;
8
+ /** Most promises that may be pending at once. */
9
+ export const MAX_PENDING_PROMISES = 10_000;
10
+ /** Deepest nesting a value may have when it crosses to or from the host. */
11
+ export const MAX_VALUE_DEPTH = 32;
12
+ export const checkStringLength = (length) => {
13
+ if (length > MAX_STRING_LENGTH)
14
+ throw rangeError("Invalid string length");
15
+ };
16
+ export const checkArrayLength = (length) => {
17
+ if (length > MAX_ARRAY_LENGTH)
18
+ throw rangeError("Invalid array length");
19
+ };