@opencode/codemode 0.0.0-dev-884 → 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,51 @@
1
+ import { primitivePrototype } from "./intrinsics.js";
2
+ import { typeError } from "./model.js";
3
+ import { Callable, get, Builtin, Obj } from "./objects.js";
4
+ import { typeofValue } from "./references.js";
5
+ import { Convert, Invoke } from "./signals.js";
6
+ /** Invoke(value, name), as the call to make: the method the value would find through its prototype. */
7
+ export const invokeMethod = (builtins, value, name, label) => {
8
+ const target = value instanceof Obj ? value : primitivePrototype(builtins, value);
9
+ if (target === undefined)
10
+ throw typeError(`${label} called on null or undefined.`);
11
+ return new Invoke(get(target, name), value, [], undefined);
12
+ };
13
+ /**
14
+ * The conversions a built-in received, while it runs again after them: by ordinal, the order its `withPrimitives`
15
+ * calls run in. The VM resets `count` before every built-in call.
16
+ */
17
+ export const conversions = {
18
+ count: 0,
19
+ replay: undefined,
20
+ };
21
+ /**
22
+ * Runs a native body on values after ToPrimitive, in order, with one hint for all positions or one per position.
23
+ * Primitive values skip the conversion entirely. Otherwise the built-in asks the VM for the conversions (they
24
+ * call program code, so they run as prelude code) and runs again from the start once they are done; this call then
25
+ * receives them. So everything a built-in does before its last conversion must be repeatable: it reads, checks, and
26
+ * throws, but changes nothing. State the body needs as it was before the conversions (a Date's time) goes in `values`.
27
+ * With `coerce`, each value is also converted to a number or string (by its hint) before the next one is.
28
+ */
29
+ export const withPrimitives = (hints, values, body, coerce = false) => {
30
+ const ordinal = conversions.count++;
31
+ const replayed = conversions.replay?.[ordinal];
32
+ if (replayed !== undefined)
33
+ return body(replayed);
34
+ if (!values.some((value) => value instanceof Obj))
35
+ return body(values);
36
+ return new Convert(hints, values, ordinal, coerce);
37
+ };
38
+ /** Checks a callback argument: the callable it is, or the TypeError for one a callback site does not admit. */
39
+ export const requireCallback = (callback, name) => {
40
+ if (isSupportedCallback(callback))
41
+ return callback;
42
+ if (typeofValue(callback) === "function") {
43
+ throw typeError(`${name} cannot use this callable as a callback; wrap it in an arrow function, e.g. (value) => tools.ns.tool(value).`);
44
+ }
45
+ throw typeError(`${name} expects a function callback.`);
46
+ };
47
+ // The single acceptance list for callbacks: collections, sort, string replacers,
48
+ // Array.from mappers, and promise reactions all admit exactly these callables.
49
+ // Admission means dispatchable, not necessarily invocable: new-requiring
50
+ // constructors pass the gate and throw a TypeError on call, like JS.
51
+ export const isSupportedCallback = (value) => value instanceof Callable && !(value instanceof Builtin && !value.callback);
@@ -0,0 +1,41 @@
1
+ import { type Context, Effect } from "effect";
2
+ import type { ToolRuntime } from "../../tool-runtime.js";
3
+ import type { Vm } from "../vm.js";
4
+ import { type Completion } from "./signals.js";
5
+ /**
6
+ * Runs the VM (see `Vm`) in Effect: the only place program execution meets the host. It calls `vm.run`
7
+ * until the program ends, and does what each stop asks: yields to the Effect scheduler for a slice, and starts the host
8
+ * calls the VM queued, as fibers with the caller's services, reporting each outcome back with `vm.complete`.
9
+ * Fibers live only here, by host call id, and never become part of the VM's state.
10
+ *
11
+ * The VM and tool bridge can be swapped for restored ones between stops (the round-trip test mode does); a fiber's
12
+ * outcome goes to whichever VM is current, by host call id.
13
+ */
14
+ export declare class Driver<R> {
15
+ vm: Vm;
16
+ tools: ToolRuntime<R>;
17
+ /** The services host work runs with: the caller's, so tools see its context, tracing, and clock. */
18
+ private readonly services;
19
+ private readonly fibers;
20
+ private wake;
21
+ private stopping;
22
+ private interrupted;
23
+ /** Called at every slice and host stop, before queued calls start: the round-trip test mode swaps the VM. */
24
+ checkpoint: Effect.Effect<void, unknown, R> | undefined;
25
+ constructor(vm: Vm, tools: ToolRuntime<R>,
26
+ /** The services host work runs with: the caller's, so tools see its context, tracing, and clock. */
27
+ services: Context.Context<R>);
28
+ /**
29
+ * Runs the VM until the program's body completes, then returns how it ended. Host work it started may still be
30
+ * running; `interrupt` stops it. Host work interrupted on its own that reaches the program's body, or blocking host
31
+ * work that is interrupted, interrupts the execution.
32
+ */
33
+ run(): Effect.Effect<Completion, unknown, R>;
34
+ /** Whether the run holds live host values: an extension call in progress. */
35
+ get holdsHostValues(): boolean;
36
+ /** Stops host work still running, waiting for its cleanup. */
37
+ interrupt(): Effect.Effect<void>;
38
+ private launch;
39
+ private fork;
40
+ private get settled();
41
+ }
@@ -0,0 +1,142 @@
1
+ import { Cause, Effect, Exit, Fiber } from "effect";
2
+ import { locate } from "./errors.js";
3
+ import { PendingThrow } from "./model.js";
4
+ import { abrupt, Interruption, normal } from "./signals.js";
5
+ /**
6
+ * Runs the VM (see `Vm`) in Effect: the only place program execution meets the host. It calls `vm.run`
7
+ * until the program ends, and does what each stop asks: yields to the Effect scheduler for a slice, and starts the host
8
+ * calls the VM queued, as fibers with the caller's services, reporting each outcome back with `vm.complete`.
9
+ * Fibers live only here, by host call id, and never become part of the VM's state.
10
+ *
11
+ * The VM and tool bridge can be swapped for restored ones between stops (the round-trip test mode does); a fiber's
12
+ * outcome goes to whichever VM is current, by host call id.
13
+ */
14
+ export class Driver {
15
+ vm;
16
+ tools;
17
+ services;
18
+ fibers = new Map();
19
+ wake;
20
+ stopping = false;
21
+ // Blocking host work interrupted on its own, which interrupts the execution.
22
+ interrupted;
23
+ /** Called at every slice and host stop, before queued calls start: the round-trip test mode swaps the VM. */
24
+ checkpoint;
25
+ constructor(vm, tools,
26
+ /** The services host work runs with: the caller's, so tools see its context, tracing, and clock. */
27
+ services) {
28
+ this.vm = vm;
29
+ this.tools = tools;
30
+ this.services = services;
31
+ }
32
+ /**
33
+ * Runs the VM until the program's body completes, then returns how it ended. Host work it started may still be
34
+ * running; `interrupt` stops it. Host work interrupted on its own that reaches the program's body, or blocking host
35
+ * work that is interrupted, interrupts the execution.
36
+ */
37
+ run() {
38
+ const self = this;
39
+ return Effect.gen(function* () {
40
+ while (true) {
41
+ if (self.interrupted !== undefined)
42
+ return yield* Effect.failCause(self.interrupted);
43
+ const stop = self.vm.run();
44
+ if (stop.kind === "slice") {
45
+ if (self.checkpoint !== undefined)
46
+ yield* self.checkpoint;
47
+ yield* Effect.yieldNow;
48
+ continue;
49
+ }
50
+ if (stop.kind === "host") {
51
+ if (stop.calls.length === 0) {
52
+ yield* self.settled;
53
+ continue;
54
+ }
55
+ if (self.checkpoint !== undefined)
56
+ yield* self.checkpoint;
57
+ for (const handed of stop.calls)
58
+ self.launch(self.vm.call(handed.id) ?? handed);
59
+ continue;
60
+ }
61
+ if (stop.kind === "stuck") {
62
+ return abrupt(new PendingThrow("Error", "The program is waiting on a promise that can never settle: nothing else is running, so nothing can resolve it. Code Mode has no timers or sleep, so don't wait or poll inside a program.", stop.node));
63
+ }
64
+ const outcome = stop.completion;
65
+ if (!outcome.ok && outcome.error instanceof Interruption)
66
+ return yield* Effect.failCause(outcome.error.cause);
67
+ return outcome;
68
+ }
69
+ });
70
+ }
71
+ /** Whether the run holds live host values: an extension call in progress. */
72
+ get holdsHostValues() {
73
+ return this.vm.calls().some((call) => call.request.kind === "extension") || this.vm.activeExtension !== undefined;
74
+ }
75
+ /** Stops host work still running, waiting for its cleanup. */
76
+ interrupt() {
77
+ const self = this;
78
+ return Effect.gen(function* () {
79
+ self.stopping = true;
80
+ while (self.fibers.size > 0)
81
+ yield* Fiber.interruptAll([...self.fibers.values()]);
82
+ });
83
+ }
84
+ // Starts host work now; its outcome goes back to the VM: a blocking call's continues the job that made it, a
85
+ // concurrent call's waits in the inbox and settles its promise in a later job, in completion order.
86
+ launch(call) {
87
+ call.status = "running";
88
+ const request = call.request;
89
+ if (request.kind === "tool")
90
+ return this.fork(call.id, this.tools.execute(request.path, request.args));
91
+ if (request.kind === "search")
92
+ return this.fork(call.id, this.tools.search(request.args));
93
+ // An extension's work, made by the extension bridge with the program's services in its requirements.
94
+ return this.fork(call.id, this.vm.ctx.extensionWork(request.call));
95
+ }
96
+ // Forks `work` with the caller's services; it starts synchronously, so admission and hooks happen before the VM
97
+ // runs another job.
98
+ fork(id, work) {
99
+ const fiber = Effect.runForkWith(this.services)(work);
100
+ this.fibers.set(id, fiber);
101
+ fiber.addObserver((exit) => {
102
+ if (this.fibers.get(id) === fiber)
103
+ this.fibers.delete(id);
104
+ // Interrupted to end the run: nothing is left to settle.
105
+ if (this.stopping)
106
+ return;
107
+ const call = this.vm.call(id);
108
+ if (call === undefined)
109
+ return;
110
+ if (call.blocking) {
111
+ // Blocking work interrupted on its own interrupts the execution.
112
+ if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause))
113
+ this.interrupted = exit.cause;
114
+ else
115
+ this.vm.complete(id, Exit.isSuccess(exit) ? normal(exit.value) : abrupt(Cause.squash(exit.cause)));
116
+ this.wake?.();
117
+ return;
118
+ }
119
+ this.vm.complete(id, Exit.isSuccess(exit)
120
+ ? normal(exit.value)
121
+ : abrupt(Cause.hasInterruptsOnly(exit.cause)
122
+ ? new Interruption(exit.cause)
123
+ : Cause.hasDies(exit.cause)
124
+ ? locate(Cause.squash(exit.cause), call.site)
125
+ : Cause.squash(exit.cause)));
126
+ this.wake?.();
127
+ });
128
+ }
129
+ get settled() {
130
+ return Effect.callback((resume) => {
131
+ if (this.vm.ready || this.interrupted !== undefined)
132
+ return resume(Effect.void);
133
+ this.wake = () => {
134
+ this.wake = undefined;
135
+ resume(Effect.void);
136
+ };
137
+ return Effect.sync(() => {
138
+ this.wake = undefined;
139
+ });
140
+ });
141
+ }
142
+ }
@@ -0,0 +1,23 @@
1
+ import type { Diagnostic } from "../../codemode.js";
2
+ import { type AstNode } from "./model.js";
3
+ import { type ErrorType } from "./intrinsics.js";
4
+ import { type Native, ErrorObj, Obj, type Value } from "./objects.js";
5
+ import type { Interpreter } from "./interpreter.js";
6
+ /**
7
+ * A host error's message as text. A host can store anything there; an object must not cross as itself, and turning it
8
+ * into text would run its own methods.
9
+ */
10
+ export declare const errorMessage: (error: Error) => string;
11
+ /** A host error's name as a program error type, read once so a getter cannot pass the check and then change. */
12
+ export declare const errorType: (error: Error) => ErrorType;
13
+ export declare const normalizeError: (error: unknown) => Diagnostic;
14
+ /**
15
+ * Gives a failure the source location of the expression that raised it, keeping the first one attached. Host errors
16
+ * that escape a built-in become the equivalent program error here.
17
+ */
18
+ export declare const locate: (error: unknown, node?: AstNode) => unknown;
19
+ /** The program value a handler receives for a failure; one failure always yields the same value. */
20
+ export declare const materialize: <R>(ctx: Interpreter<R>, thrown: unknown) => Value;
21
+ export declare const createAggregateErrorValue: <R>(ctx: Interpreter<R>, errors: Array<Value>, message: string, proto?: Obj) => ErrorObj;
22
+ /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
23
+ export declare const errorGlobal: <R>(type: ErrorType, ctx: Interpreter<R>) => Native;
@@ -0,0 +1,169 @@
1
+ import { ToolError } from "../../tool-error.js";
2
+ import { ToolRuntimeError } from "../../tool-runtime.js";
3
+ import { formatLocation, PendingThrow, Throw, sourceLocation } from "./model.js";
4
+ import { containsRuntimeReference } from "./references.js";
5
+ import { createErrorValue, isErrorType } from "./intrinsics.js";
6
+ import { constructor, methods, prototypeFrom, receiver } from "./native.js";
7
+ import { define, get, has, hidden, Arr, ErrorObj, Obj, coerceToString, } from "./objects.js";
8
+ import { Invoke } from "./signals.js";
9
+ import { withPrimitives } from "./callback.js";
10
+ import { formatValue } from "../stdlib/console.js";
11
+ import { inPrelude } from "./source.js";
12
+ /**
13
+ * A host error's message as text. A host can store anything there; an object must not cross as itself, and turning it
14
+ * into text would run its own methods.
15
+ */
16
+ export const errorMessage = (error) => {
17
+ const message = error.message;
18
+ if (typeof message === "string")
19
+ return message;
20
+ if (message === undefined || typeof message === "function" || (typeof message === "object" && message !== null)) {
21
+ return "";
22
+ }
23
+ return String(message);
24
+ };
25
+ /** A host error's name as a program error type, read once so a getter cannot pass the check and then change. */
26
+ export const errorType = (error) => {
27
+ const name = error.name;
28
+ return typeof name === "string" && isErrorType(name) ? name : "Error";
29
+ };
30
+ export const normalizeError = (error) => {
31
+ if (error instanceof PendingThrow) {
32
+ const location = error.node?.loc ? sourceLocation(error.node) : undefined;
33
+ return {
34
+ kind: error.kind,
35
+ message: `${error.type}: ${error.message}${formatLocation(location)}`,
36
+ ...(location ? { location } : {}),
37
+ ...(error.suggestions ? { suggestions: error.suggestions } : {}),
38
+ };
39
+ }
40
+ if (error instanceof ToolRuntimeError) {
41
+ return {
42
+ kind: error.kind,
43
+ message: error.message,
44
+ ...(error.suggestions.length > 0 ? { suggestions: error.suggestions } : {}),
45
+ };
46
+ }
47
+ if (error instanceof ToolError) {
48
+ return { kind: "ToolFailure", message: error.message };
49
+ }
50
+ if (error instanceof Throw) {
51
+ const value = error.value;
52
+ if (value instanceof ErrorObj) {
53
+ return value.failure ? normalizeError(value.failure) : { kind: "ExecutionFailure", message: errorToString(value) };
54
+ }
55
+ let message;
56
+ if (containsRuntimeReference(value)) {
57
+ // Never expose runtime reference internals through thrown values.
58
+ message = "a non-data value";
59
+ }
60
+ else if (typeof value === "string") {
61
+ message = value;
62
+ }
63
+ else {
64
+ message = formatValue(value);
65
+ }
66
+ return { kind: "ExecutionFailure", message: `Uncaught: ${message}` };
67
+ }
68
+ if (error instanceof RangeError && /call stack|recursion/i.test(errorMessage(error))) {
69
+ return {
70
+ kind: "ExecutionFailure",
71
+ message: "Execution exceeded the maximum nesting depth.",
72
+ };
73
+ }
74
+ if (error instanceof Error) {
75
+ return {
76
+ kind: error.name === "SyntaxError" ? "ParseError" : "ExecutionFailure",
77
+ message: errorMessage(error),
78
+ };
79
+ }
80
+ return {
81
+ kind: "ExecutionFailure",
82
+ message: String(error),
83
+ };
84
+ };
85
+ /**
86
+ * Gives a failure the source location of the expression that raised it, keeping the first one attached. Host errors
87
+ * that escape a built-in become the equivalent program error here.
88
+ */
89
+ export const locate = (error, node) => {
90
+ if (error instanceof PendingThrow) {
91
+ if ((error.node === undefined || inPrelude(error.node)) && node)
92
+ error.node = node;
93
+ return error;
94
+ }
95
+ if (error instanceof Error && !(error instanceof ToolError) && !(error instanceof ToolRuntimeError)) {
96
+ return new PendingThrow(errorType(error), errorMessage(error), node);
97
+ }
98
+ return error;
99
+ };
100
+ /** The program value a handler receives for a failure; one failure always yields the same value. */
101
+ export const materialize = (ctx, thrown) => {
102
+ if (thrown instanceof Throw)
103
+ return thrown.value;
104
+ const builtins = ctx.builtins;
105
+ if (thrown instanceof PendingThrow) {
106
+ if (thrown.value === undefined) {
107
+ thrown.value = createErrorValue(builtins[thrown.type], thrown.message);
108
+ thrown.value.failure = thrown;
109
+ }
110
+ return thrown.value;
111
+ }
112
+ return createErrorValue(builtins[thrown instanceof Error ? errorType(thrown) : "Error"], normalizeError(thrown).message);
113
+ };
114
+ /** Error.prototype.toString: `name: message`, omitting whichever side is empty. */
115
+ const errorToString = (self) => {
116
+ const name = get(self, "name");
117
+ const message = get(self, "message");
118
+ const shownName = name === undefined ? "Error" : coerceToString(name);
119
+ const shownMessage = message === undefined ? "" : coerceToString(message);
120
+ if (shownMessage === "")
121
+ return shownName;
122
+ if (shownName === "")
123
+ return shownMessage;
124
+ return `${shownName}: ${shownMessage}`;
125
+ };
126
+ export const createAggregateErrorValue = (ctx, errors, message, proto = ctx.builtins.AggregateError) => {
127
+ const value = createErrorValue(proto, message);
128
+ define(value, "errors", new Arr(ctx.builtins.Array, errors), { ...hidden });
129
+ return value;
130
+ };
131
+ // ES2022 `new Error(message, { cause })`: installed only when the options object has the property at all.
132
+ const withCause = (created, options) => {
133
+ if (options instanceof Obj && has(options, "cause"))
134
+ define(created, "cause", get(options, "cause"), hidden);
135
+ return created;
136
+ };
137
+ /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
138
+ export const errorGlobal = (type, ctx) => {
139
+ const builtins = ctx.builtins;
140
+ const prototype = builtins[type];
141
+ const construct = (args, newTarget) => {
142
+ const proto = prototypeFrom(newTarget, prototype);
143
+ if (type === "AggregateError") {
144
+ const message = args[1];
145
+ return withPrimitives("string", message === undefined ? [] : [message], ([text]) => {
146
+ const created = withCause(createErrorValue(proto, message === undefined ? "" : coerceToString(text)), args[2]);
147
+ return new Invoke(ctx.prelude.fn("aggregateError"), undefined, [created, args[0]], undefined);
148
+ }, true);
149
+ }
150
+ const message = args[0];
151
+ return withPrimitives("string", message === undefined ? [] : [message], ([text]) => withCause(createErrorValue(proto, message === undefined ? undefined : coerceToString(text)), args[1]), true);
152
+ };
153
+ const ctor = constructor(builtins, prototype, {
154
+ name: type,
155
+ length: type === "AggregateError" ? 2 : 1,
156
+ call: (_, args) => construct(args, ctor),
157
+ construct,
158
+ });
159
+ if (type === "Error") {
160
+ methods(builtins, prototype, [
161
+ ["toString", 0, (thisValue) => errorToString(receiver(Obj, thisValue, "Error.prototype.toString"))],
162
+ ]);
163
+ methods(builtins, ctor, [["isError", 1, (_, args) => args[0] instanceof ErrorObj]]);
164
+ return ctor;
165
+ }
166
+ // Derived constructors extend Error itself, so its statics are inherited. The globals table creates Error first.
167
+ ctor.proto = get(builtins.Error, "constructor");
168
+ return ctor;
169
+ };
@@ -0,0 +1,22 @@
1
+ import { type Program } from "acorn";
2
+ import { Effect } from "effect";
3
+ import type { DataValue, Diagnostic, ResolvedExecutionLimits, Result } from "../../codemode.js";
4
+ import type { Extension } from "../../extension.js";
5
+ import { ToolRuntime } from "../../tool-runtime.js";
6
+ import { Interpreter } from "./interpreter.js";
7
+ import type { Value } from "./objects.js";
8
+ import { Source } from "./source.js";
9
+ type Globals<R> = (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
10
+ /** Runs a program on the VM with `CodeMode.make`'s extensions and JSON bindings. */
11
+ export declare const execute: <R>(code: string, prepared: ToolRuntime.Prepared<R>, limits: ResolvedExecutionLimits, hooks: ToolRuntime.Hooks<R>, extensions: ReadonlyArray<Extension>, bindings: Readonly<Record<string, DataValue>> | undefined) => Effect.Effect<Result, never, R>;
12
+ export declare const executeProgram: <R>(code: string, prepared: ToolRuntime.Prepared<R>, limits: ResolvedExecutionLimits, hooks: ToolRuntime.Hooks<R>, globals?: Globals<R>, bindings?: Globals<R>, lossy?: boolean) => Effect.Effect<Result, never, R>;
13
+ export declare const setRoundTrip: (enabled: boolean) => void;
14
+ export declare const parseProgram: (code: string) => {
15
+ ok: true;
16
+ program: Program;
17
+ source: Source;
18
+ } | {
19
+ ok: false;
20
+ error: Diagnostic;
21
+ };
22
+ export {};