@opencode/codemode 2.2.6 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/README.md +115 -29
  2. package/dist/{vm/async.d.ts → async.d.ts} +1 -1
  3. package/dist/codemode.d.ts +13 -22
  4. package/dist/codemode.js +18 -39
  5. package/dist/data.d.ts +4 -19
  6. package/dist/data.js +1 -82
  7. package/dist/extension.d.ts +20 -1
  8. package/dist/extension.js +14 -1
  9. package/dist/{vm/host.d.ts → host.d.ts} +5 -2
  10. package/dist/{vm/host.js → host.js} +9 -4
  11. package/dist/index.d.ts +1 -1
  12. package/dist/{vm/opcodes.d.ts → opcodes.d.ts} +1 -1
  13. package/dist/{vm/prelude → prelude}/helpers.js +1 -1
  14. package/dist/{vm/runtime → runtime}/driver.d.ts +18 -8
  15. package/dist/{vm/runtime → runtime}/driver.js +90 -20
  16. package/dist/{vm/runtime → runtime}/errors.js +2 -2
  17. package/dist/{vm/runtime → runtime}/execute.d.ts +18 -9
  18. package/dist/{vm/runtime → runtime}/execute.js +45 -15
  19. package/dist/{vm/runtime → runtime}/extensions.d.ts +2 -2
  20. package/dist/{vm/runtime → runtime}/extensions.js +121 -19
  21. package/dist/{vm/runtime → runtime}/globals.js +1 -1
  22. package/dist/{vm/runtime → runtime}/interpreter.d.ts +4 -1
  23. package/dist/{vm/runtime → runtime}/interpreter.js +2 -0
  24. package/dist/{vm/runtime → runtime}/model.d.ts +1 -1
  25. package/dist/{vm/runtime → runtime}/objects.d.ts +1 -1
  26. package/dist/{vm/runtime → runtime}/objects.js +1 -1
  27. package/dist/{vm/runtime → runtime}/operations.d.ts +1 -1
  28. package/dist/{vm/runtime → runtime}/operations.js +1 -1
  29. package/dist/scan.js +2 -2
  30. package/dist/{vm/scheduler.d.ts → scheduler.d.ts} +16 -4
  31. package/dist/{vm/scheduler.js → scheduler.js} +13 -2
  32. package/dist/{vm/snapshot → snapshot}/codec.d.ts +37 -6
  33. package/dist/{vm/snapshot → snapshot}/codec.js +112 -8
  34. package/dist/{vm/snapshot → snapshot}/snapshot.d.ts +13 -6
  35. package/dist/{vm/snapshot → snapshot}/snapshot.js +19 -4
  36. package/dist/{vm/snapshot.js → snapshot.js} +5 -2
  37. package/dist/stdlib/array.d.ts +14 -9
  38. package/dist/stdlib/array.js +89 -276
  39. package/dist/stdlib/bytes.d.ts +11 -7
  40. package/dist/stdlib/bytes.js +112 -79
  41. package/dist/stdlib/collections.d.ts +7 -7
  42. package/dist/stdlib/collections.js +30 -339
  43. package/dist/stdlib/console.d.ts +2 -2
  44. package/dist/stdlib/console.js +3 -3
  45. package/dist/stdlib/date.d.ts +2 -2
  46. package/dist/stdlib/date.js +21 -30
  47. package/dist/stdlib/headers.d.ts +2 -2
  48. package/dist/stdlib/headers.js +15 -33
  49. package/dist/stdlib/iterator.d.ts +2 -2
  50. package/dist/stdlib/iterator.js +10 -303
  51. package/dist/stdlib/json.d.ts +2 -2
  52. package/dist/stdlib/json.js +15 -31
  53. package/dist/stdlib/math.d.ts +2 -7
  54. package/dist/stdlib/math.js +6 -30
  55. package/dist/stdlib/number.d.ts +3 -3
  56. package/dist/stdlib/number.js +8 -8
  57. package/dist/stdlib/object.d.ts +4 -4
  58. package/dist/stdlib/object.js +12 -30
  59. package/dist/stdlib/regexp.d.ts +6 -5
  60. package/dist/stdlib/regexp.js +18 -13
  61. package/dist/stdlib/string.d.ts +2 -2
  62. package/dist/stdlib/string.js +53 -53
  63. package/dist/stdlib/url.d.ts +21 -9
  64. package/dist/stdlib/url.js +55 -55
  65. package/dist/stdlib/value.d.ts +3 -4
  66. package/dist/stdlib/value.js +5 -6
  67. package/dist/stdlib/web.d.ts +4 -4
  68. package/dist/stdlib/web.js +7 -7
  69. package/dist/tool-runtime.d.ts +34 -12
  70. package/dist/tool-runtime.js +350 -68
  71. package/dist/tool-schema.d.ts +5 -0
  72. package/dist/tool-schema.js +36 -16
  73. package/dist/tool.d.ts +60 -2
  74. package/dist/tool.js +17 -1
  75. package/dist/{vm/vm.d.ts → vm.d.ts} +4 -3
  76. package/dist/{vm/vm.js → vm.js} +1 -1
  77. package/package.json +5 -7
  78. package/dist/interpreter/callback.d.ts +0 -24
  79. package/dist/interpreter/callback.js +0 -86
  80. package/dist/interpreter/errors.js +0 -173
  81. package/dist/interpreter/execute.d.ts +0 -14
  82. package/dist/interpreter/execute.js +0 -207
  83. package/dist/interpreter/extensions.d.ts +0 -9
  84. package/dist/interpreter/extensions.js +0 -248
  85. package/dist/interpreter/generators.d.ts +0 -3
  86. package/dist/interpreter/generators.js +0 -168
  87. package/dist/interpreter/globals.js +0 -144
  88. package/dist/interpreter/interpreter.d.ts +0 -48
  89. package/dist/interpreter/interpreter.js +0 -2253
  90. package/dist/interpreter/intrinsics.d.ts +0 -15
  91. package/dist/interpreter/intrinsics.js +0 -105
  92. package/dist/interpreter/model.d.ts +0 -68
  93. package/dist/interpreter/model.js +0 -54
  94. package/dist/interpreter/native.d.ts +0 -17
  95. package/dist/interpreter/native.js +0 -35
  96. package/dist/interpreter/objects.d.ts +0 -301
  97. package/dist/interpreter/objects.js +0 -592
  98. package/dist/interpreter/promises.d.ts +0 -18
  99. package/dist/interpreter/promises.js +0 -292
  100. package/dist/interpreter/runner.d.ts +0 -188
  101. package/dist/interpreter/runner.js +0 -492
  102. package/dist/interpreter/scope.d.ts +0 -16
  103. package/dist/interpreter/scope.js +0 -79
  104. package/dist/suspend-error.d.ts +0 -23
  105. package/dist/suspend-error.js +0 -25
  106. package/dist/vm/data.d.ts +0 -7
  107. package/dist/vm/data.js +0 -13
  108. package/dist/vm/index.d.ts +0 -6
  109. package/dist/vm/index.js +0 -6
  110. package/dist/vm/runtime/errors.d.ts +0 -23
  111. package/dist/vm/runtime/globals.d.ts +0 -6
  112. package/dist/vm/runtime/limits.d.ts +0 -10
  113. package/dist/vm/runtime/limits.js +0 -19
  114. package/dist/vm/runtime/modules.d.ts +0 -4
  115. package/dist/vm/runtime/modules.js +0 -33
  116. package/dist/vm/runtime/references.d.ts +0 -8
  117. package/dist/vm/runtime/references.js +0 -51
  118. package/dist/vm/stdlib/array.d.ts +0 -16
  119. package/dist/vm/stdlib/array.js +0 -311
  120. package/dist/vm/stdlib/bytes.d.ts +0 -11
  121. package/dist/vm/stdlib/bytes.js +0 -222
  122. package/dist/vm/stdlib/collections.d.ts +0 -7
  123. package/dist/vm/stdlib/collections.js +0 -188
  124. package/dist/vm/stdlib/console.d.ts +0 -6
  125. package/dist/vm/stdlib/console.js +0 -93
  126. package/dist/vm/stdlib/date.d.ts +0 -2
  127. package/dist/vm/stdlib/date.js +0 -123
  128. package/dist/vm/stdlib/headers.d.ts +0 -2
  129. package/dist/vm/stdlib/headers.js +0 -92
  130. package/dist/vm/stdlib/iterator.d.ts +0 -2
  131. package/dist/vm/stdlib/iterator.js +0 -30
  132. package/dist/vm/stdlib/json.d.ts +0 -3
  133. package/dist/vm/stdlib/json.js +0 -42
  134. package/dist/vm/stdlib/math.d.ts +0 -3
  135. package/dist/vm/stdlib/math.js +0 -73
  136. package/dist/vm/stdlib/number.d.ts +0 -3
  137. package/dist/vm/stdlib/number.js +0 -72
  138. package/dist/vm/stdlib/object.d.ts +0 -6
  139. package/dist/vm/stdlib/object.js +0 -201
  140. package/dist/vm/stdlib/regexp.d.ts +0 -8
  141. package/dist/vm/stdlib/regexp.js +0 -119
  142. package/dist/vm/stdlib/string.d.ts +0 -2
  143. package/dist/vm/stdlib/string.js +0 -272
  144. package/dist/vm/stdlib/url.d.ts +0 -25
  145. package/dist/vm/stdlib/url.js +0 -255
  146. package/dist/vm/stdlib/value.d.ts +0 -6
  147. package/dist/vm/stdlib/value.js +0 -32
  148. package/dist/vm/stdlib/web.d.ts +0 -5
  149. package/dist/vm/stdlib/web.js +0 -97
  150. /package/dist/{vm/async.js → async.js} +0 -0
  151. /package/dist/{vm/code.d.ts → code.d.ts} +0 -0
  152. /package/dist/{vm/code.js → code.js} +0 -0
  153. /package/dist/{vm/compiler → compiler}/compile.d.ts +0 -0
  154. /package/dist/{vm/compiler → compiler}/compile.js +0 -0
  155. /package/dist/{vm/compiler → compiler}/scope.d.ts +0 -0
  156. /package/dist/{vm/compiler → compiler}/scope.js +0 -0
  157. /package/dist/{vm/generators.d.ts → generators.d.ts} +0 -0
  158. /package/dist/{vm/generators.js → generators.js} +0 -0
  159. /package/dist/{vm/internal-prelude.d.ts → internal-prelude.d.ts} +0 -0
  160. /package/dist/{vm/internal-prelude.js → internal-prelude.js} +0 -0
  161. /package/dist/{vm/opcodes.js → opcodes.js} +0 -0
  162. /package/dist/{vm/prelude → prelude}/bytecode.d.ts +0 -0
  163. /package/dist/{vm/prelude → prelude}/bytecode.js +0 -0
  164. /package/dist/{vm/prelude → prelude}/bytecode.json +0 -0
  165. /package/dist/{vm/prelude → prelude}/helpers.d.ts +0 -0
  166. /package/dist/{vm/prelude → prelude}/prelude.d.ts +0 -0
  167. /package/dist/{vm/prelude → prelude}/prelude.js +0 -0
  168. /package/dist/{vm/prelude → prelude}/source.d.ts +0 -0
  169. /package/dist/{vm/prelude → prelude}/source.js +0 -0
  170. /package/dist/{vm/runtime → runtime}/callback.d.ts +0 -0
  171. /package/dist/{vm/runtime → runtime}/callback.js +0 -0
  172. /package/dist/{interpreter → runtime}/errors.d.ts +0 -0
  173. /package/dist/{vm/runtime → runtime}/generators.d.ts +0 -0
  174. /package/dist/{vm/runtime → runtime}/generators.js +0 -0
  175. /package/dist/{interpreter → runtime}/globals.d.ts +0 -0
  176. /package/dist/{vm/runtime → runtime}/intrinsic-names.d.ts +0 -0
  177. /package/dist/{vm/runtime → runtime}/intrinsic-names.js +0 -0
  178. /package/dist/{vm/runtime → runtime}/intrinsics.d.ts +0 -0
  179. /package/dist/{vm/runtime → runtime}/intrinsics.js +0 -0
  180. /package/dist/{interpreter → runtime}/limits.d.ts +0 -0
  181. /package/dist/{interpreter → runtime}/limits.js +0 -0
  182. /package/dist/{vm/runtime → runtime}/model.js +0 -0
  183. /package/dist/{interpreter → runtime}/modules.d.ts +0 -0
  184. /package/dist/{interpreter → runtime}/modules.js +0 -0
  185. /package/dist/{vm/runtime → runtime}/native.d.ts +0 -0
  186. /package/dist/{vm/runtime → runtime}/native.js +0 -0
  187. /package/dist/{vm/runtime → runtime}/promises.d.ts +0 -0
  188. /package/dist/{vm/runtime → runtime}/promises.js +0 -0
  189. /package/dist/{interpreter → runtime}/references.d.ts +0 -0
  190. /package/dist/{interpreter → runtime}/references.js +0 -0
  191. /package/dist/{vm/runtime → runtime}/signals.d.ts +0 -0
  192. /package/dist/{vm/runtime → runtime}/signals.js +0 -0
  193. /package/dist/{vm/runtime → runtime}/source.d.ts +0 -0
  194. /package/dist/{vm/runtime → runtime}/source.js +0 -0
  195. /package/dist/{vm/runtime → runtime}/table.d.ts +0 -0
  196. /package/dist/{vm/runtime → runtime}/table.js +0 -0
  197. /package/dist/{vm/snapshot.d.ts → snapshot.d.ts} +0 -0
@@ -1,207 +0,0 @@
1
- import { parse } from "acorn";
2
- import { Cause, Effect, Option, Schema } from "effect";
3
- import { ToolRuntime } from "../tool-runtime.js";
4
- import { normalizeError } from "./errors.js";
5
- import { createBuiltins } from "./intrinsics.js";
6
- import { Interpreter } from "./interpreter.js";
7
- import { formatLocation, sourceLocation } from "./model.js";
8
- export const executeProgram = (code, prepared, limits, hooks, globals) => {
9
- if (code.trim().length === 0) {
10
- return Effect.succeed({
11
- ok: false,
12
- error: { kind: "ParseError", message: "Code cannot be empty." },
13
- toolCalls: [],
14
- });
15
- }
16
- // Allocate execution state inside suspension so reused Effects never share it.
17
- return Effect.suspend(() => {
18
- const builtins = createBuiltins();
19
- const tools = ToolRuntime.make(prepared, limits.maxToolCalls, hooks);
20
- const logs = [];
21
- const logged = () => (logs.length > 0 ? { logs: [...logs] } : {});
22
- // Set only after copy-out so timeouts cannot report invalid values as completed.
23
- let returned;
24
- let runner;
25
- const base = Effect.gen(function* () {
26
- const parsed = parseProgram(code);
27
- if (!parsed.ok)
28
- return { ok: false, error: parsed.error, toolCalls: [] };
29
- const services = yield* Effect.context();
30
- const ctx = new Interpreter({ tools, services, builtins, logs, globals });
31
- runner = ctx.runner;
32
- const outcome = yield* runner.run(ctx.main(parsed.program));
33
- if (!outcome.ok) {
34
- return { ok: false, error: normalizeError(outcome.error), ...logged(), toolCalls: tools.calls };
35
- }
36
- const result = outcome.value ?? null;
37
- returned = { value: result, runner };
38
- // Host work the program left running is interrupted, not awaited.
39
- yield* runner.interrupt();
40
- const warnings = runner.diagnostics();
41
- return {
42
- ok: true,
43
- value: result,
44
- ...(warnings.length > 0 ? { warnings } : {}),
45
- ...logged(),
46
- toolCalls: tools.calls,
47
- };
48
- }).pipe(Effect.ensuring(Effect.suspend(() => runner?.interrupt() ?? Effect.void)));
49
- const timeoutMs = limits.timeoutMs;
50
- const operation = timeoutMs === undefined
51
- ? base
52
- : base.pipe(Effect.timeoutOrElse({
53
- duration: timeoutMs,
54
- orElse: () => Effect.sync(() => {
55
- if (returned === undefined) {
56
- return {
57
- ok: false,
58
- error: { kind: "TimeoutExceeded", message: `Execution timed out after ${timeoutMs}ms.` },
59
- ...logged(),
60
- toolCalls: tools.calls,
61
- };
62
- }
63
- // Keep the timeout warning first so truncation preserves it.
64
- return {
65
- ok: true,
66
- value: returned.value,
67
- warnings: [
68
- {
69
- kind: "TimeoutExceeded",
70
- message: `The program returned, but background work was still running at the ${timeoutMs}ms timeout and was interrupted. Await all started promises.`,
71
- },
72
- ...returned.runner.diagnostics(),
73
- ],
74
- ...logged(),
75
- toolCalls: tools.calls,
76
- };
77
- }),
78
- }));
79
- return operation.pipe(Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause)
80
- ? Effect.interrupt
81
- : Effect.succeed({
82
- ok: false,
83
- error: normalizeError(Cause.squash(cause)),
84
- ...logged(),
85
- toolCalls: tools.calls,
86
- })), Effect.map((result) => limits.maxOutputBytes === undefined ? result : boundOutput(result, limits.maxOutputBytes)));
87
- });
88
- };
89
- export const parseProgram = (code) => {
90
- try {
91
- const program = parse(code, {
92
- ecmaVersion: "latest",
93
- sourceType: "script",
94
- allowReturnOutsideFunction: true,
95
- allowAwaitOutsideFunction: true,
96
- // Imports bind globals by module name; scripts keep sloppy-mode semantics, which module source would make strict.
97
- allowImportExportEverywhere: true,
98
- locations: true,
99
- });
100
- const exported = program.body.find((statement) => statement.type.startsWith("Export"));
101
- if (exported) {
102
- const location = sourceLocation(exported);
103
- return {
104
- ok: false,
105
- error: {
106
- kind: "ParseError",
107
- message: `SyntaxError: Exports aren't available. Return the result instead.${formatLocation(location)}`,
108
- location,
109
- },
110
- };
111
- }
112
- return { ok: true, program };
113
- }
114
- catch (error) {
115
- // Only acorn's own syntax errors become a located ParseError; anything else keeps the generic failure path.
116
- const acorn = error instanceof SyntaxError ? decodeAcornError(error) : Option.none();
117
- if (Option.isNone(acorn))
118
- throw error;
119
- return { ok: false, error: parseDiagnostic(acorn.value) };
120
- }
121
- };
122
- // Acorn appends ` (line:column)` to its messages; its lines are 1-based and its columns 0-based.
123
- const AcornError = Schema.Struct({
124
- message: Schema.String,
125
- loc: Schema.Struct({ line: Schema.Number, column: Schema.Number }),
126
- });
127
- const decodeAcornError = Schema.decodeUnknownOption(AcornError);
128
- const parseDiagnostic = (error) => {
129
- const location = { line: error.loc.line, column: error.loc.column + 1 };
130
- const reason = error.message.replace(/ \(\d+:\d+\)$/, "");
131
- const text = `${reason.endsWith(".") ? reason : `${reason}.`} Code must be plain JavaScript written as a program body.`;
132
- return { kind: "ParseError", message: `SyntaxError: ${text}${formatLocation(location)}`, location };
133
- };
134
- const utf8ByteLength = (value) => new TextEncoder().encode(value).byteLength;
135
- // Drop a replacement character produced by truncating inside a UTF-8 sequence.
136
- const utf8Truncate = (value, maxBytes) => {
137
- const bytes = new TextEncoder().encode(value);
138
- if (bytes.byteLength <= maxBytes)
139
- return value;
140
- const text = new TextDecoder("utf-8").decode(bytes.slice(0, Math.max(0, maxBytes)));
141
- return text.endsWith("\uFFFD") ? text.slice(0, -1) : text;
142
- };
143
- // Warnings have a separate budget so result data cannot starve diagnostics.
144
- const boundOutput = (result, maxOutputBytes) => {
145
- let truncated = false;
146
- let value = null;
147
- let valueBytes = 0;
148
- if (result.ok) {
149
- const serialized = JSON.stringify(result.value) ?? "null";
150
- const bytes = utf8ByteLength(serialized);
151
- if (bytes > maxOutputBytes) {
152
- truncated = true;
153
- value = `${utf8Truncate(serialized, maxOutputBytes)} [result truncated: ${bytes} bytes exceeds the ${maxOutputBytes}-byte output limit; return a smaller value]`;
154
- valueBytes = maxOutputBytes;
155
- }
156
- else {
157
- value = result.value;
158
- valueBytes = bytes;
159
- }
160
- }
161
- const warnings = result.ok ? (result.warnings ?? []) : [];
162
- const keptWarnings = [];
163
- let warningBytes = 0;
164
- for (const warning of warnings) {
165
- const bytes = utf8ByteLength(JSON.stringify(warning)) + 1;
166
- if (warningBytes + bytes > maxOutputBytes)
167
- break;
168
- warningBytes += bytes;
169
- keptWarnings.push(warning);
170
- }
171
- if (keptWarnings.length < warnings.length) {
172
- truncated = true;
173
- keptWarnings.push({
174
- kind: "Truncated",
175
- message: `${warnings.length - keptWarnings.length} additional warnings omitted by the output limit.`,
176
- });
177
- }
178
- const logs = result.logs ?? [];
179
- const kept = [];
180
- const logBudget = Math.max(0, maxOutputBytes - valueBytes);
181
- let logBytes = 0;
182
- for (const line of logs) {
183
- const lineBytes = utf8ByteLength(line) + 1;
184
- if (logBytes + lineBytes > logBudget)
185
- break;
186
- logBytes += lineBytes;
187
- kept.push(line);
188
- }
189
- if (kept.length < logs.length) {
190
- truncated = true;
191
- kept.push(`[logs truncated: showing ${kept.length} of ${logs.length} lines]`);
192
- }
193
- if (!truncated)
194
- return result;
195
- const warningsPart = keptWarnings.length > 0 ? { warnings: keptWarnings } : {};
196
- const logsPart = kept.length > 0 ? { logs: kept } : {};
197
- return result.ok
198
- ? {
199
- ok: true,
200
- value,
201
- ...warningsPart,
202
- ...logsPart,
203
- truncated: true,
204
- toolCalls: result.toolCalls,
205
- }
206
- : { ok: false, error: result.error, ...logsPart, truncated: true, toolCalls: result.toolCalls };
207
- };
@@ -1,9 +0,0 @@
1
- import { type Extension } from "../extension.js";
2
- import type { Interpreter } from "./interpreter.js";
3
- import { type Value } from "./objects.js";
4
- /**
5
- * The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and built-in
6
- * wrappers are copied, a host function becomes a program function whose calls cross the same way, and a host Promise
7
- * or Effect becomes a program promise.
8
- */
9
- export declare const extensionGlobals: <R>(ctx: Interpreter<R>, extensions: ReadonlyArray<Extension>) => ReadonlyArray<readonly [string, Value]>;
@@ -1,248 +0,0 @@
1
- import { Effect } from "effect";
2
- import { isAsync } from "../extension.js";
3
- import { hooked } from "../tool-runtime.js";
4
- import { errorMessage, errorType } from "./errors.js";
5
- import { createErrorValue } from "./intrinsics.js";
6
- import { MAX_ARRAY_LENGTH, MAX_VALUE_DEPTH } from "./limits.js";
7
- import { PendingThrow, rangeError, Throw, typeError } from "./model.js";
8
- import { fn } from "./native.js";
9
- import { define, get, has, hidden, keys, Arr, Bytes, DateObj, ErrorObj, HeadersObj, MapObj, Obj, RegExpObj, SetObj, URLObj, URLSearchParamsObj, coerceToString, } from "./objects.js";
10
- import { describeValue, isOpaque } from "./references.js";
11
- /**
12
- * The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and built-in
13
- * wrappers are copied, a host function becomes a program function whose calls cross the same way, and a host Promise
14
- * or Effect becomes a program promise.
15
- */
16
- export const extensionGlobals = (ctx, extensions) => {
17
- const builtins = ctx.builtins;
18
- const toHost = (value, label, depth = 0, seen = new Set()) => {
19
- if (depth > MAX_VALUE_DEPTH)
20
- throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
21
- if (isPrimitive(value))
22
- return value;
23
- if (!(value instanceof Obj) || isOpaque(value)) {
24
- throw typeError(`${label} contains ${describeValue(value)}, which cannot be passed to an extension.`);
25
- }
26
- if (seen.has(value))
27
- throw typeError(`${label} contains a circular value.`);
28
- seen.add(value);
29
- const next = (item) => toHost(item, label, depth + 1, seen);
30
- if (value instanceof ErrorObj) {
31
- const name = coerceToString(get(value, "name"));
32
- const message = get(value, "message");
33
- const text = message === undefined ? "" : coerceToString(message);
34
- const copied = name === "AggregateError" ? new AggregateError([], text) : new (hostErrors.get(name) ?? Error)(text);
35
- for (const key of new Set(["cause", ...keys(value)])) {
36
- if (uncrossed.has(key) || !has(value, key))
37
- continue;
38
- const item = crossing(() => next(get(value, key)));
39
- if (item === left)
40
- continue;
41
- Object.defineProperty(copied, key, {
42
- value: item,
43
- writable: true,
44
- configurable: true,
45
- enumerable: key !== "cause",
46
- });
47
- }
48
- seen.delete(value);
49
- return copied;
50
- }
51
- const copied = value.toHost(next);
52
- seen.delete(value);
53
- return copied;
54
- };
55
- // `extension` is set while converting a global object, whose functions are entry points like globals and fire the hooks.
56
- const fromHost = (value, label, depth = 0, seen = new Set(), extension) => {
57
- if (depth > MAX_VALUE_DEPTH)
58
- throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
59
- if (isPrimitive(value))
60
- return value;
61
- if (typeof value === "function")
62
- return wrap(value, label, extension === undefined ? undefined : (args) => ({ extension, name: label, args }));
63
- if (value !== null && typeof value === "object") {
64
- const next = (item, path) => fromHost(item, path, depth + 1, seen, extension);
65
- // Nothing a host value hands back is kept: results are read as primitives or copied. Where the value's own
66
- // method could hand back host storage or an object (`getTime`, `slice`, `map`), its internal data is read.
67
- if (value instanceof Date)
68
- return new DateObj(builtins.Date, Date.prototype.getTime.call(value));
69
- if (value instanceof RegExp)
70
- return new RegExpObj(builtins.RegExp, value.source, value.flags);
71
- if (value instanceof Uint8Array)
72
- return new Bytes(builtins.Uint8Array, new Uint8Array(value));
73
- if (value instanceof ArrayBuffer) {
74
- const view = new Uint8Array(value);
75
- // Only a real buffer has bytes to view; anything else would be read as array-like and lose them silently.
76
- if (view.buffer !== value)
77
- throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
78
- return new Bytes(builtins.Uint8Array, new Uint8Array(view));
79
- }
80
- if (value instanceof Error) {
81
- if (seen.has(value))
82
- throw typeError(`${label} produced a circular value.`);
83
- seen.add(value);
84
- const copied = createErrorValue(builtins[errorType(value)], errorMessage(value));
85
- const fields = value;
86
- for (const key of new Set(["cause", ...Object.keys(value)])) {
87
- if (uncrossed.has(key) || !(key in value))
88
- continue;
89
- // Read once: a getter could pass the check and then hand back a function.
90
- const field = fields[key];
91
- if (typeof field === "function")
92
- continue;
93
- const item = crossing(() => next(field, `${label}.${key}`));
94
- if (item === left)
95
- continue;
96
- define(copied, key, item, key === "cause" ? hidden : undefined);
97
- }
98
- seen.delete(value);
99
- return copied;
100
- }
101
- if (value instanceof URL)
102
- return new URLObj(builtins.URL, builtins.URLSearchParams, new URL(value.href));
103
- if (value instanceof URLSearchParams) {
104
- return new URLSearchParamsObj(builtins.URLSearchParams, new URLSearchParams(value));
105
- }
106
- if (value instanceof Headers)
107
- return new HeadersObj(builtins.Headers, new Headers(value));
108
- if (value instanceof Map) {
109
- const wrapped = new MapObj(builtins.Map);
110
- for (const [key, item] of value)
111
- wrapped.map.set(next(key, label), next(item, label));
112
- return wrapped;
113
- }
114
- if (value instanceof Set) {
115
- const wrapped = new SetObj(builtins.Set);
116
- for (const item of value)
117
- wrapped.set.add(next(item, label));
118
- return wrapped;
119
- }
120
- if (seen.has(value))
121
- throw typeError(`${label} produced a circular value.`);
122
- seen.add(value);
123
- if (Array.isArray(value)) {
124
- const length = value.length;
125
- if (length > MAX_ARRAY_LENGTH) {
126
- throw rangeError(`${label} produced an array of ${length} items; at most ${MAX_ARRAY_LENGTH} can cross.`);
127
- }
128
- // Filled in order so the copy stays a dense array; holes stay holes, as a copy made with `map` would leave them.
129
- const items = [];
130
- for (let index = 0; index < length; index += 1) {
131
- if (index in value)
132
- items[index] = next(value[index], `${label}[${index}]`);
133
- }
134
- items.length = length;
135
- seen.delete(value);
136
- return new Arr(builtins.Array, items);
137
- }
138
- const prototype = Object.getPrototypeOf(value);
139
- if (prototype === Object.prototype || prototype === null) {
140
- const copied = new Obj(builtins.Object);
141
- for (const [key, item] of Object.entries(value))
142
- define(copied, key, next(item, `${label}.${key}`));
143
- seen.delete(value);
144
- return copied;
145
- }
146
- }
147
- throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
148
- };
149
- // A host function as a program function. Arguments cross in; for a global or a global object's function, the
150
- // `extension.before` hook runs before the host function is called, so a call it denies never reaches the host. The
151
- // host's result, or what it threw, crosses out so the program catches a copy, and `extension.after` sees how the
152
- // call ended. Functions inside results are part of a value's API and skip the hooks.
153
- const wrap = (value, label, describe) => {
154
- // The host function's own `name` and `length` can be anything, even getters: each is read once, and only text
155
- // and a count cross.
156
- const name = value.name;
157
- const length = value.length;
158
- return fn(builtins, typeof name === "string" ? name : "", typeof length === "number" && Number.isSafeInteger(length) && length >= 0 ? length : 0, function* (_, values, site) {
159
- const args = values.map((item, index) => toHost(item, `Argument ${index + 1} to ${label}`));
160
- const cross = (reason) => new Throw(fromHost(reason, label));
161
- const call = describe?.(args);
162
- const hooks = ctx.tools.hooks;
163
- const before = call && hooks["extension.before"]?.(call).pipe(Effect.mapError(cross));
164
- const after = call && hooks["extension.after"];
165
- const settle = (effect) => (after ? hooked(call, undefined, after, effect) : effect).pipe(Effect.mapBoth({ onFailure: cross, onSuccess: (result) => fromHost(result, label) }));
166
- // A denied call fails the way the global would: an async global rejects its promise, a sync one throws.
167
- if (isAsync(value))
168
- return pending(Effect.andThen(before ?? Effect.void, settle(Effect.suspend(() => callHost(value, args).effect))), site);
169
- if (before)
170
- yield ctx.runner.blocking(before);
171
- const host = callHost(value, args);
172
- if (host.async)
173
- return pending(settle(host.effect), site);
174
- return (yield ctx.runner.blocking(settle(host.effect)));
175
- });
176
- };
177
- // An asynchronous host call: the program holds a promise that settles when the host's work does.
178
- const pending = (work, site) => {
179
- const promise = ctx.runner.newPromise();
180
- const resolving = ctx.runner.resolving(promise, site);
181
- ctx.runner.host(work, (settled) => (settled.ok ? resolving.resolve(settled.value) : resolving.reject(settled.error)), site);
182
- return promise;
183
- };
184
- return extensions.flatMap((extension) => Object.entries(extension.globals).map(([name, value]) => [
185
- name,
186
- typeof value === "function"
187
- ? wrap(value, name, (args) => ({ extension: extension.name, name, args }))
188
- : fromHost(value, name, 0, new Set(), extension.name),
189
- ]));
190
- };
191
- /**
192
- * Calls a host function and describes what the program waits on. A returned Effect or Promise settles later; a
193
- * returned value or a throw settles now.
194
- */
195
- const callHost = (value, args) => {
196
- try {
197
- const result = value.apply(undefined, args);
198
- // Extension.Services adds an Effect global's requirements to R.
199
- if (Effect.isEffect(result))
200
- return { async: true, effect: result };
201
- if (result instanceof Promise)
202
- return { async: true, effect: Effect.tryPromise({ try: () => result, catch: (reason) => reason }) };
203
- return { async: false, effect: Effect.succeed(result) };
204
- }
205
- catch (reason) {
206
- return { async: false, effect: Effect.fail(reason) };
207
- }
208
- };
209
- /**
210
- * An error crosses as its name, message, `cause`, and own enumerable fields, such as Node's `code`, `errno`,
211
- * `syscall`, and `path`. `stack` stays on its own side, `message` crosses once as text, and no field may shadow an
212
- * Error method. A field that cannot cross (a socket, a handle, a function) is left behind so the error itself always
213
- * arrives.
214
- */
215
- const uncrossed = new Set(["stack", "message", "constructor", "toString", "__proto__"]);
216
- const left = Symbol("left behind");
217
- const crossing = (convert) => {
218
- try {
219
- return convert();
220
- }
221
- catch (reason) {
222
- if (reason instanceof PendingThrow)
223
- return left;
224
- throw reason;
225
- }
226
- };
227
- const hostErrors = new Map([
228
- ["TypeError", TypeError],
229
- ["RangeError", RangeError],
230
- ["SyntaxError", SyntaxError],
231
- ["ReferenceError", ReferenceError],
232
- ["EvalError", EvalError],
233
- ["URIError", URIError],
234
- ]);
235
- // The primitives the interpreter operates on; symbols and BigInts are not among them.
236
- const isPrimitive = (value) => value === null ||
237
- value === undefined ||
238
- typeof value === "string" ||
239
- typeof value === "number" ||
240
- typeof value === "boolean";
241
- const describeHost = (value) => {
242
- if (typeof value !== "object" || value === null)
243
- return `a ${typeof value}`;
244
- const name = value.constructor?.name;
245
- if (name === undefined || name === "")
246
- return "an object";
247
- return `${/^[AEIO]/.test(name) ? "an" : "a"} ${name}`;
248
- };
@@ -1,3 +0,0 @@
1
- import type { Interpreter } from "./interpreter.js";
2
- /** `next`/`return`/`throw` on the generator prototypes; async generators answer with promises. */
3
- export declare const generatorGlobals: <R>(ctx: Interpreter<R>) => void;
@@ -1,168 +0,0 @@
1
- import { fn, methods, receiver } from "./native.js";
2
- import { AsyncIteratorSymbol, IteratorSymbol, Throw, typeError } from "./model.js";
3
- import { define, hidden, GeneratorObj, iteratorResult } from "./objects.js";
4
- import { abrupt, Enter, normal, } from "./runner.js";
5
- /** `next`/`return`/`throw` on the generator prototypes; async generators answer with promises. */
6
- export const generatorGlobals = (ctx) => {
7
- const builtins = ctx.builtins;
8
- const sync = (kind) => [
9
- kind,
10
- 1,
11
- (thisValue, args) => {
12
- const method = `Generator.prototype.${kind}`;
13
- const generator = receiver(GeneratorObj, thisValue, method);
14
- if (generator.asynchronous)
15
- throw typeError(`${method} called on incompatible receiver an async generator.`);
16
- return step(ctx, generator, kind, args[0]);
17
- },
18
- ];
19
- const async = (kind) => [
20
- kind,
21
- 1,
22
- (thisValue, args) => request(ctx, thisValue, kind, args[0]),
23
- ];
24
- methods(builtins, builtins.Generator, [sync("next"), sync("return"), sync("throw")]);
25
- methods(builtins, builtins.AsyncGenerator, [async("next"), async("return"), async("throw")]);
26
- define(builtins.Iterator, IteratorSymbol, fn(builtins, "[Symbol.iterator]", 0, (thisValue) => thisValue), hidden);
27
- define(builtins.AsyncIterator, AsyncIteratorSymbol, fn(builtins, "[Symbol.asyncIterator]", 0, (thisValue) => thisValue), hidden);
28
- };
29
- const result = (ctx, value, done) => iteratorResult(ctx.builtins.Object, value, done);
30
- // Puts the suspended body back on the stack and continues it with `request`; the boundary answers the caller when
31
- // the body next yields or ends.
32
- const resume = (ctx, generator, request) => {
33
- const started = generator.state !== "suspendedStart";
34
- generator.state = "executing";
35
- if (!started) {
36
- return new Enter([{ body: generator.body, boundary: new GeneratorBoundary(ctx, generator) }], normal(undefined));
37
- }
38
- const entries = generator.entries;
39
- generator.entries = undefined;
40
- return new Enter(entries, normal(request));
41
- };
42
- // A synchronous generator step: the body runs on the caller's stack until it yields, returns, or throws.
43
- function* step(ctx, generator, kind, value) {
44
- if (generator.state === "executing")
45
- throw typeError("Generator is already running.");
46
- if (generator.state === "suspendedStart" && kind !== "next")
47
- generator.state = "completed";
48
- if (generator.state === "completed") {
49
- if (kind === "throw")
50
- throw new Throw(value);
51
- return result(ctx, kind === "return" ? value : undefined, true);
52
- }
53
- return (yield resume(ctx, generator, { kind, value }));
54
- }
55
- // AsyncGenerator.prototype.next/return/throw: queue the request with its promise, and run the body now if it is
56
- // waiting for one. A request that arrives while the body runs is answered when the body reaches it.
57
- function* request(ctx, thisValue, kind, value) {
58
- const runner = ctx.runner;
59
- const promise = runner.newPromise();
60
- const resolving = runner.resolving(promise);
61
- if (!(thisValue instanceof GeneratorObj) || !thisValue.asynchronous) {
62
- resolving.reject(typeError(`AsyncGenerator.prototype.${kind} called on incompatible receiver.`));
63
- return promise;
64
- }
65
- const generator = thisValue;
66
- const state = generator.state;
67
- if (kind === "next" && state === "completed") {
68
- resolving.resolve(result(ctx, undefined, true));
69
- return promise;
70
- }
71
- if (kind === "throw") {
72
- if (state === "suspendedStart")
73
- generator.state = "completed";
74
- if (generator.state === "completed") {
75
- resolving.reject(new Throw(value));
76
- return promise;
77
- }
78
- }
79
- const queued = { kind, value };
80
- generator.queue.push({ request: queued, resolving });
81
- if (kind === "return" && (state === "suspendedStart" || state === "completed")) {
82
- generator.state = "awaiting-return";
83
- awaitReturn(ctx, generator);
84
- return promise;
85
- }
86
- if (state === "suspendedStart" || state === "suspendedYield")
87
- yield resume(ctx, generator, queued);
88
- return promise;
89
- }
90
- // AsyncGeneratorCompleteStep: answer the oldest request.
91
- const completeStep = (ctx, generator, completion, done) => {
92
- const next = generator.queue.shift();
93
- if (completion.ok)
94
- next.resolving.resolve(result(ctx, completion.value, done));
95
- else
96
- next.resolving.reject(completion.error);
97
- };
98
- // AsyncGeneratorDrainQueue: once the body has ended, answer the remaining requests in order.
99
- const drainQueue = (ctx, generator) => {
100
- generator.state = "draining";
101
- while (true) {
102
- const next = generator.queue[0];
103
- if (next === undefined) {
104
- generator.state = "completed";
105
- return;
106
- }
107
- if (next.request.kind === "return") {
108
- generator.state = "awaiting-return";
109
- return awaitReturn(ctx, generator);
110
- }
111
- completeStep(ctx, generator, next.request.kind === "throw" ? abrupt(new Throw(next.request.value)) : normal(undefined), true);
112
- }
113
- };
114
- // AsyncGeneratorAwaitReturn: a `return(value)` on an ended or unstarted generator settles once `value` does.
115
- const awaitReturn = (ctx, generator) => {
116
- const runner = ctx.runner;
117
- const finish = (completion) => {
118
- completeStep(ctx, generator, completion, true);
119
- drainQueue(ctx, generator);
120
- };
121
- try {
122
- runner.then(runner.promiseResolve(generator.queue[0].request.value), finish);
123
- }
124
- catch (error) {
125
- finish(abrupt(error));
126
- }
127
- };
128
- /** Where a generator body splits off the stack when it yields, and how its end answers the request that ran it. */
129
- class GeneratorBoundary {
130
- ctx;
131
- target;
132
- generator = true;
133
- async;
134
- constructor(ctx, target) {
135
- this.ctx = ctx;
136
- this.target = target;
137
- this.async = target.asynchronous;
138
- }
139
- finish(completion) {
140
- const generator = this.target;
141
- if (!generator.asynchronous) {
142
- generator.state = "completed";
143
- return completion.ok ? normal(result(this.ctx, completion.value, true)) : completion;
144
- }
145
- completeStep(this.ctx, generator, completion, true);
146
- drainQueue(this.ctx, generator);
147
- return normal(undefined);
148
- }
149
- suspended() {
150
- return normal(undefined);
151
- }
152
- yielded(value, split) {
153
- const generator = this.target;
154
- if (!generator.asynchronous) {
155
- generator.entries = split();
156
- generator.state = "suspendedYield";
157
- return normal(result(this.ctx, value, false));
158
- }
159
- // AsyncGeneratorYield: answer the oldest request, and keep running if another is already waiting.
160
- completeStep(this.ctx, generator, normal(value), false);
161
- const next = generator.queue[0];
162
- if (next !== undefined)
163
- return normal(next.request);
164
- generator.entries = split();
165
- generator.state = "suspendedYield";
166
- return normal(undefined);
167
- }
168
- }