@opencode/codemode 0.0.0-beta-19365 → 0.0.0-beta-19381

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 (47) hide show
  1. package/dist/interpreter/errors.d.ts +4 -6
  2. package/dist/interpreter/errors.js +20 -4
  3. package/dist/interpreter/execute.js +2 -3
  4. package/dist/interpreter/globals.d.ts +13 -0
  5. package/dist/interpreter/globals.js +59 -0
  6. package/dist/interpreter/host.d.ts +41 -0
  7. package/dist/interpreter/host.js +44 -0
  8. package/dist/interpreter/methods.d.ts +3 -23
  9. package/dist/interpreter/methods.js +8 -183
  10. package/dist/interpreter/model.d.ts +0 -41
  11. package/dist/interpreter/model.js +0 -56
  12. package/dist/interpreter/promises.d.ts +7 -8
  13. package/dist/interpreter/promises.js +45 -22
  14. package/dist/interpreter/references.js +11 -28
  15. package/dist/interpreter/runner.d.ts +23 -0
  16. package/dist/interpreter/runner.js +42 -0
  17. package/dist/interpreter/runtime.d.ts +11 -92
  18. package/dist/interpreter/runtime.js +75 -452
  19. package/dist/stdlib/array.d.ts +3 -0
  20. package/dist/stdlib/array.js +73 -0
  21. package/dist/stdlib/collections.d.ts +6 -1
  22. package/dist/stdlib/collections.js +120 -1
  23. package/dist/stdlib/console.d.ts +3 -2
  24. package/dist/stdlib/console.js +11 -2
  25. package/dist/stdlib/date.d.ts +3 -2
  26. package/dist/stdlib/date.js +27 -11
  27. package/dist/stdlib/json.d.ts +4 -4
  28. package/dist/stdlib/json.js +6 -2
  29. package/dist/stdlib/math.d.ts +3 -7
  30. package/dist/stdlib/math.js +85 -153
  31. package/dist/stdlib/number.d.ts +1 -3
  32. package/dist/stdlib/number.js +28 -36
  33. package/dist/stdlib/object.d.ts +4 -6
  34. package/dist/stdlib/object.js +101 -71
  35. package/dist/stdlib/regexp.d.ts +2 -4
  36. package/dist/stdlib/regexp.js +32 -9
  37. package/dist/stdlib/string.d.ts +1 -3
  38. package/dist/stdlib/string.js +14 -16
  39. package/dist/stdlib/url.d.ts +8 -4
  40. package/dist/stdlib/url.js +97 -21
  41. package/dist/stdlib/value.d.ts +5 -3
  42. package/dist/stdlib/value.js +21 -19
  43. package/package.json +1 -1
  44. package/dist/interpreter/iterator.d.ts +0 -13
  45. package/dist/interpreter/iterator.js +0 -4
  46. package/dist/stdlib/promise.d.ts +0 -2
  47. package/dist/stdlib/promise.js +0 -1
@@ -1,9 +1,7 @@
1
- import { Effect } from "effect";
2
1
  import type { Diagnostic } from "../codemode.js";
3
- import { type SafeObject } from "../data.js";
4
- import { type AstNode } from "./model.js";
5
- import { type SyncIteratorRunner } from "./iterator.js";
2
+ import { HostFunction } from "./host.js";
3
+ import { type Runner } from "./runner.js";
6
4
  export declare const normalizeError: (error: unknown) => Diagnostic;
7
5
  export declare const caughtErrorValue: (thrown: unknown) => unknown;
8
- export declare const constructErrorValue: (name: string, args: Array<unknown>) => SafeObject;
9
- export declare const constructAggregateErrorValue: <R>(runner: SyncIteratorRunner<R>, args: Array<unknown>, node: AstNode) => Effect.Effect<SafeObject, unknown, R>;
6
+ /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
7
+ export declare const errorGlobal: <R>(name: string, runner: Runner<R>) => HostFunction<R>;
@@ -3,8 +3,9 @@ import { ToolError } from "../tool-error.js";
3
3
  import { toData, ToolRuntimeError } from "../data.js";
4
4
  import { formatLocation, InterpreterRuntimeError, ProgramThrow, sourceLocation } from "./model.js";
5
5
  import { containsRuntimeReference } from "./references.js";
6
- import {} from "./iterator.js";
7
- import { coerceToString, createAggregateErrorValue, createErrorValue, errorConstructors } from "../stdlib/value.js";
6
+ import { HostFunction } from "./host.js";
7
+ import {} from "./runner.js";
8
+ import { coerceToString, createAggregateErrorValue, createErrorValue, errorBrandName, errorConstructors, } from "../stdlib/value.js";
8
9
  export const normalizeError = (error) => {
9
10
  if (error instanceof InterpreterRuntimeError) {
10
11
  return {
@@ -74,8 +75,8 @@ export const caughtErrorValue = (thrown) => {
74
75
  const name = thrown instanceof Error && errorConstructors.has(thrown.name) ? thrown.name : "Error";
75
76
  return createErrorValue(name, normalizeError(thrown).message);
76
77
  };
77
- export const constructErrorValue = (name, args) => createErrorValue(name, args[0] === undefined ? "" : coerceToString(args[0]));
78
- export const constructAggregateErrorValue = (runner, args, node) => Effect.gen(function* () {
78
+ const constructErrorValue = (name, args) => createErrorValue(name, args[0] === undefined ? "" : coerceToString(args[0]));
79
+ const constructAggregateErrorValue = (runner, args, node) => Effect.gen(function* () {
79
80
  const cursor = yield* runner.syncIterator(args[0], node);
80
81
  if (cursor === undefined) {
81
82
  throw new InterpreterRuntimeError("new AggregateError(...) expects a synchronous iterable of errors.", node).as("TypeError");
@@ -89,3 +90,18 @@ export const constructAggregateErrorValue = (runner, args, node) => Effect.gen(f
89
90
  errors.push(step.value);
90
91
  }
91
92
  });
93
+ /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
94
+ export const errorGlobal = (name, runner) => {
95
+ const construct = (args, node) => name === "AggregateError"
96
+ ? constructAggregateErrorValue(runner, args, node)
97
+ : Effect.sync(() => constructErrorValue(name, args));
98
+ return new HostFunction({
99
+ name,
100
+ call: construct,
101
+ construct,
102
+ instanceOf: (value) => {
103
+ const brand = errorBrandName(value);
104
+ return brand !== undefined && (name === "Error" || brand === name);
105
+ },
106
+ });
107
+ };
@@ -8,7 +8,7 @@ import { ToolRuntime } from "../tool-runtime.js";
8
8
  import { normalizeError } from "./errors.js";
9
9
  import { InterpreterRuntimeError } from "./model.js";
10
10
  import { PromiseRuntime } from "./promises.js";
11
- import { Interpreter } from "./runtime.js";
11
+ import { Runtime } from "./runtime.js";
12
12
  export const executeProgram = (code, prepared, limits, hooks) => {
13
13
  if (code.trim().length === 0) {
14
14
  return Effect.succeed({
@@ -27,8 +27,7 @@ export const executeProgram = (code, prepared, limits, hooks) => {
27
27
  const base = Effect.acquireUseRelease(Scope.make("parallel"), (scope) => Effect.gen(function* () {
28
28
  const program = parseProgram(code);
29
29
  const promises = new PromiseRuntime(scope);
30
- const interpreter = new Interpreter(tools.execute, tools.search, tools.keys, promises, logs);
31
- const value = yield* interpreter.run(program);
30
+ const value = yield* new Runtime(tools.execute, tools.search, tools.keys, promises, logs).run(program);
32
31
  const result = toData(value, "Execution result", "result");
33
32
  returned = { value: result, promises };
34
33
  const warnings = yield* promises.interrupt();
@@ -0,0 +1,13 @@
1
+ import { Effect } from "effect";
2
+ import { type PromiseRuntime } from "./promises.js";
3
+ import type { Runner } from "./runner.js";
4
+ /** What the built-in globals need from the interpreter that owns them. */
5
+ export type Host<R> = {
6
+ readonly runner: Runner<R>;
7
+ readonly promises: PromiseRuntime<R>;
8
+ readonly search: (args: Array<unknown>) => Effect.Effect<unknown, unknown, R>;
9
+ readonly toolKeys: (path: ReadonlyArray<string>) => ReadonlyArray<string>;
10
+ readonly logs: Array<string>;
11
+ };
12
+ /** The immutable global bindings of every program, in declaration order. */
13
+ export declare const globals: <R>(host: Host<R>) => ReadonlyArray<readonly [string, unknown]>;
@@ -0,0 +1,59 @@
1
+ import { Effect } from "effect";
2
+ import { arrayGlobal } from "../stdlib/array.js";
3
+ import { mapGlobal, setGlobal } from "../stdlib/collections.js";
4
+ import { consoleGlobal } from "../stdlib/console.js";
5
+ import { dateGlobal } from "../stdlib/date.js";
6
+ import { jsonGlobal } from "../stdlib/json.js";
7
+ import { mathGlobal } from "../stdlib/math.js";
8
+ import { numberGlobal } from "../stdlib/number.js";
9
+ import { objectGlobal } from "../stdlib/object.js";
10
+ import { regexpGlobal } from "../stdlib/regexp.js";
11
+ import { stringGlobal } from "../stdlib/string.js";
12
+ import { uriGlobal, urlGlobal, urlSearchParamsGlobal } from "../stdlib/url.js";
13
+ import { coercion, errorConstructors } from "../stdlib/value.js";
14
+ import { ToolReference } from "../tool-runtime.js";
15
+ import { errorGlobal } from "./errors.js";
16
+ import { HostFunction } from "./host.js";
17
+ import { AsyncIteratorSymbol, InterpreterRuntimeError, IteratorSymbol } from "./model.js";
18
+ import { promiseGlobal } from "./promises.js";
19
+ const symbolGlobal = new HostFunction({
20
+ name: "Symbol",
21
+ call: (_, node) => Effect.sync(() => {
22
+ throw new InterpreterRuntimeError("Symbol is not callable; only Symbol.asyncIterator and Symbol.iterator are available.", node).as("TypeError");
23
+ }),
24
+ callback: false,
25
+ members: { asyncIterator: AsyncIteratorSymbol, iterator: IteratorSymbol },
26
+ });
27
+ /** The immutable global bindings of every program, in declaration order. */
28
+ export const globals = (host) => [
29
+ ["tools", new ToolReference([])],
30
+ ["search", new HostFunction({ name: "search", call: (args) => host.search(args), callback: false })],
31
+ ["undefined", undefined],
32
+ ["NaN", NaN],
33
+ ["Infinity", Infinity],
34
+ ["Object", objectGlobal(host.runner, host.toolKeys)],
35
+ ["Array", arrayGlobal(host.runner)],
36
+ ["Math", mathGlobal(host.runner)],
37
+ ["JSON", jsonGlobal(host.runner)],
38
+ ["console", consoleGlobal(host.logs)],
39
+ ["Promise", promiseGlobal(host.runner, host.promises)],
40
+ ["Symbol", symbolGlobal],
41
+ ["Number", numberGlobal],
42
+ ["String", stringGlobal],
43
+ ["Boolean", coercion("Boolean", { instanceOf: () => false })],
44
+ ["parseInt", coercion("parseInt")],
45
+ ["parseFloat", coercion("parseFloat")],
46
+ ["isFinite", coercion("isFinite")],
47
+ ["isNaN", coercion("isNaN")],
48
+ ["Date", dateGlobal(host.runner)],
49
+ ["RegExp", regexpGlobal],
50
+ ["Map", mapGlobal(host.runner)],
51
+ ["Set", setGlobal(host.runner)],
52
+ ["URL", urlGlobal],
53
+ ["URLSearchParams", urlSearchParamsGlobal(host.runner)],
54
+ ["encodeURI", uriGlobal("encodeURI")],
55
+ ["encodeURIComponent", uriGlobal("encodeURIComponent")],
56
+ ["decodeURI", uriGlobal("decodeURI")],
57
+ ["decodeURIComponent", uriGlobal("decodeURIComponent")],
58
+ ...[...errorConstructors].map((name) => [name, errorGlobal(name, host.runner)]),
59
+ ];
@@ -0,0 +1,41 @@
1
+ import { Effect } from "effect";
2
+ import { type AstNode } from "./model.js";
3
+ export type HostCall<R> = (args: Array<unknown>, node: AstNode) => Effect.Effect<unknown, unknown, R>;
4
+ type HostMember = (key: PropertyKey, node: AstNode) => unknown;
5
+ type HostFunctionOptions<R> = {
6
+ readonly name: string;
7
+ readonly call: HostCall<R>;
8
+ /** `new name(...)`; without it `new` is unsupported syntax. */
9
+ readonly construct?: HostCall<R>;
10
+ /** Static members read through `name.key`; unknown keys read as `undefined` unless the function decides otherwise. */
11
+ readonly members?: Record<string, unknown> | HostMember;
12
+ /** `value instanceof name`; without it the operator rejects this right-hand side. */
13
+ readonly instanceOf?: (value: unknown) => boolean;
14
+ /** Whether callback sites (array methods, replacers, promise reactions) admit this function. Defaults to true. */
15
+ readonly callback?: boolean;
16
+ };
17
+ /** A host-implemented function value. `typeof` is "function". */
18
+ export declare class HostFunction<R = never> {
19
+ readonly name: string;
20
+ readonly call: HostCall<R>;
21
+ readonly construct: HostCall<R> | undefined;
22
+ readonly member: HostMember;
23
+ readonly instanceOf: ((value: unknown) => boolean) | undefined;
24
+ readonly callback: boolean;
25
+ constructor(options: HostFunctionOptions<R>);
26
+ }
27
+ /** A host-implemented object of static members. `typeof` is "object" and it is not callable. */
28
+ export declare class HostNamespace {
29
+ readonly name: string;
30
+ readonly member: HostMember;
31
+ constructor(name: string, members: Record<string, unknown> | HostMember);
32
+ }
33
+ export type SyncOptions = Omit<HostFunctionOptions<never>, "name" | "call">;
34
+ type SyncImpl = (args: Array<unknown>, node: AstNode) => unknown;
35
+ /** Lifts a synchronous implementation, which may throw `InterpreterRuntimeError`, into a host call. */
36
+ export declare const syncCall: (impl: SyncImpl) => HostCall<never>;
37
+ /** A synchronous host function. */
38
+ export declare const sync: (name: string, impl: SyncImpl, options?: SyncOptions) => HostFunction<never>;
39
+ /** The `call` of a constructor that JS requires to be invoked with `new`. */
40
+ export declare const requiresNew: (name: string) => HostCall<never>;
41
+ export {};
@@ -0,0 +1,44 @@
1
+ import { Effect } from "effect";
2
+ import { InterpreterRuntimeError } from "./model.js";
3
+ /** A host-implemented function value. `typeof` is "function". */
4
+ export class HostFunction {
5
+ name;
6
+ call;
7
+ construct;
8
+ member;
9
+ instanceOf;
10
+ callback;
11
+ constructor(options) {
12
+ this.name = options.name;
13
+ this.call = options.call;
14
+ this.construct = options.construct;
15
+ this.member = memberLookup(options.members);
16
+ this.instanceOf = options.instanceOf;
17
+ this.callback = options.callback ?? true;
18
+ }
19
+ }
20
+ /** A host-implemented object of static members. `typeof` is "object" and it is not callable. */
21
+ export class HostNamespace {
22
+ name;
23
+ member;
24
+ constructor(name, members) {
25
+ this.name = name;
26
+ this.member = memberLookup(members);
27
+ }
28
+ }
29
+ const memberLookup = (members) => {
30
+ if (members === undefined)
31
+ return () => undefined;
32
+ if (typeof members === "function")
33
+ return members;
34
+ const table = new Map(Object.entries(members));
35
+ return (key) => (typeof key === "string" ? table.get(key) : undefined);
36
+ };
37
+ /** Lifts a synchronous implementation, which may throw `InterpreterRuntimeError`, into a host call. */
38
+ export const syncCall = (impl) => (args, node) => Effect.sync(() => impl(args, node));
39
+ /** A synchronous host function. */
40
+ export const sync = (name, impl, options = {}) => new HostFunction({ name, call: syncCall(impl), ...options });
41
+ /** The `call` of a constructor that JS requires to be invoked with `new`. */
42
+ export const requiresNew = (name) => (_, node) => Effect.sync(() => {
43
+ throw new InterpreterRuntimeError(`Constructor ${name} requires 'new'.`, node).as("TypeError");
44
+ });
@@ -1,24 +1,4 @@
1
1
  import { Effect } from "effect";
2
- import { type AstNode, CodeModeFunction, CoercionFunction, ErrorConstructorReference, GlobalMethodReference, GlobalNamespace, IntrinsicReference, JsonMethodReference, PromiseCapabilityFunction, PromiseNamespace, UriFunction } from "./model.js";
3
- import { Values } from "../values.js";
4
- import { type SyncIteratorRunner } from "./iterator.js";
5
- export type CallbackRunner<R> = {
6
- readonly invokeFunction: (fn: CodeModeFunction, args: Array<unknown>) => Effect.Effect<unknown, unknown, R>;
7
- readonly invokeCallable: (callable: unknown, args: Array<unknown>, node: AstNode) => Effect.Effect<unknown, unknown, R>;
8
- readonly settlePromise: (promise: Values.Promise) => Effect.Effect<unknown, unknown, never>;
9
- };
10
- export type SupportedCallback = CodeModeFunction | CoercionFunction | UriFunction | PromiseCapabilityFunction | GlobalMethodReference | JsonMethodReference | IntrinsicReference | ErrorConstructorReference | GlobalNamespace | PromiseNamespace;
11
- export declare const isSupportedCallback: (value: unknown) => value is SupportedCallback;
12
- export declare const invokeIntrinsic: <R>(runner: CallbackRunner<R>, ref: IntrinsicReference, args: Array<unknown>, node: AstNode) => Effect.Effect<unknown, unknown, R>;
13
- /**
14
- * ToPrimitive: tries an object's own `valueOf`/`toString` in hint order and returns the first
15
- * primitive result. Runtime values behave like their JS counterparts (Date yields its time under a
16
- * number hint; the rest yield their string form). An inherited `toString` yields the default
17
- * string form, so plain objects become "[object Object]" and arrays join.
18
- */
19
- export declare const toPrimitive: <R>(runner: CallbackRunner<R>, value: unknown, hint: "number" | "string", node: AstNode) => Effect.Effect<unknown, unknown, R>;
20
- export declare const invokeGlobalMethod: (ref: GlobalMethodReference, args: Array<unknown>, node: AstNode) => unknown;
21
- export declare const arrayStatics: Set<string>;
22
- export declare const invokeArrayFrom: <R>(runner: CallbackRunner<R> & SyncIteratorRunner<R>, args: Array<unknown>, node: AstNode) => Effect.Effect<unknown, unknown, R>;
23
- export declare const invokeGroupBy: <R>(runner: CallbackRunner<R> & SyncIteratorRunner<R>, namespace: "Map" | "Object", args: Array<unknown>, node: AstNode) => Effect.Effect<unknown, unknown, R>;
24
- export declare const applyCollectionCallback: <R>(runner: CallbackRunner<R>, callback: unknown, name: string, node: AstNode) => ((args: Array<unknown>) => Effect.Effect<unknown, unknown, R>);
2
+ import { type AstNode, IntrinsicReference } from "./model.js";
3
+ import { type Runner } from "./runner.js";
4
+ export declare const invokeIntrinsic: <R>(runner: Runner<R>, ref: IntrinsicReference, args: Array<unknown>, node: AstNode) => Effect.Effect<unknown, unknown, R>;
@@ -1,30 +1,15 @@
1
1
  import { Effect } from "effect";
2
- import { CodeModeFunction, CodeModeGenerator, CoercionFunction, ErrorConstructorReference, GlobalMethodReference, GlobalNamespace, IntrinsicReference, InterpreterRuntimeError, JsonMethodReference, PromiseCapabilityFunction, PromiseNamespace, UriFunction, } from "./model.js";
3
- import { containsOpaqueReference, isRuntimeReference, rejectCircularInsertion, typeofValue } from "./references.js";
4
2
  import { isBlockedMember, toProgram } from "../data.js";
3
+ import { dateSetterArgumentCount, invokeDateMethod } from "../stdlib/date.js";
4
+ import { invokeNumberMethod } from "../stdlib/number.js";
5
+ import { invokeRegExpMethod, matchToValue, toHostRegex } from "../stdlib/regexp.js";
6
+ import { invokeURLMethod, uriArgument } from "../stdlib/url.js";
7
+ import { coerceToNumber, coerceToString, errorBrandName } from "../stdlib/value.js";
5
8
  import { compareText } from "../tool-runtime.js";
6
9
  import { Values } from "../values.js";
7
- import { dateSetterArgumentCount, invokeDateMethod, invokeDateStatic } from "../stdlib/date.js";
8
- import { invokeMathMethod } from "../stdlib/math.js";
9
- import { invokeNumberMethod, invokeNumberStatic } from "../stdlib/number.js";
10
- import { invokeObjectMethod } from "../stdlib/object.js";
11
- import { invokeRegExpMethod, invokeRegExpStatic, matchToValue, toHostRegex } from "../stdlib/regexp.js";
12
- import { invokeStringStatic } from "../stdlib/string.js";
13
- import { invokeURLMethod, invokeURLStatic, uriArgument } from "../stdlib/url.js";
14
- import { coerceToNumber, coerceToString, errorBrandName } from "../stdlib/value.js";
15
- import { preserveConsumerError } from "./iterator.js";
16
- export const isSupportedCallback = (value) => value instanceof CodeModeFunction ||
17
- value instanceof CoercionFunction ||
18
- value instanceof UriFunction ||
19
- value instanceof PromiseCapabilityFunction ||
20
- value instanceof GlobalMethodReference ||
21
- value instanceof JsonMethodReference ||
22
- value instanceof IntrinsicReference ||
23
- value instanceof ErrorConstructorReference ||
24
- // Callable namespaces dispatch like JS: Array/Object/Date/RegExp construct,
25
- // new-requiring constructors throw a TypeError. Math/JSON/console stay non-callable.
26
- (value instanceof GlobalNamespace && typeofValue(value) === "function") ||
27
- value instanceof PromiseNamespace;
10
+ import { IntrinsicReference, InterpreterRuntimeError } from "./model.js";
11
+ import { containsOpaqueReference, rejectCircularInsertion, typeofValue } from "./references.js";
12
+ import { applyCollectionCallback, isSupportedCallback, toPrimitive } from "./runner.js";
28
13
  export const invokeIntrinsic = (runner, ref, args, node) => {
29
14
  if (typeof ref.receiver === "string") {
30
15
  if (ref.name === "replace" || ref.name === "replaceAll") {
@@ -76,48 +61,8 @@ export const invokeIntrinsic = (runner, ref, args, node) => {
76
61
  * number hint; the rest yield their string form). An inherited `toString` yields the default
77
62
  * string form, so plain objects become "[object Object]" and arrays join.
78
63
  */
79
- export const toPrimitive = (runner, value, hint, node) => {
80
- if (value === null || typeof value !== "object")
81
- return Effect.succeed(value);
82
- if (Values.isValue(value)) {
83
- return Effect.succeed(value instanceof Values.Date && hint === "number" ? value.time : coerceToString(value));
84
- }
85
- const object = value;
86
- const order = hint === "number" ? ["valueOf", "toString"] : ["toString", "valueOf"];
87
- return Effect.gen(function* () {
88
- for (const method of order) {
89
- if (method === "toString" && !Object.hasOwn(object, "toString"))
90
- return coerceToString(value);
91
- if (!Object.hasOwn(object, method) || typeofValue(object[method]) !== "function")
92
- continue;
93
- const result = yield* runner.invokeCallable(object[method], [], node);
94
- if (result === null || (typeof result !== "object" && typeof result !== "function"))
95
- return result;
96
- }
97
- throw new InterpreterRuntimeError("Cannot convert object to primitive value.", node).as("TypeError");
98
- });
99
- };
100
64
  const coerceNumericArgument = (runner, value, node) => Effect.map(toPrimitive(runner, value, "number", node), coerceToNumber);
101
65
  // console is intercepted by the interpreter before reaching here.
102
- export const invokeGlobalMethod = (ref, args, node) => {
103
- if (ref.namespace === "Object")
104
- return invokeObjectMethod(ref.name, args, node);
105
- if (ref.namespace === "Math")
106
- return invokeMathMethod(ref.name, args, node);
107
- if (ref.namespace === "Array")
108
- return invokeArrayStatic(ref.name, args, node);
109
- if (ref.namespace === "Number")
110
- return invokeNumberStatic(ref.name, args, node);
111
- if (ref.namespace === "String")
112
- return invokeStringStatic(ref.name, args, node);
113
- if (ref.namespace === "URL")
114
- return invokeURLStatic(ref.name, args, node);
115
- if (ref.namespace === "Date")
116
- return invokeDateStatic(ref.name, args, node);
117
- if (ref.namespace === "RegExp")
118
- return invokeRegExpStatic(ref.name, args, node);
119
- throw new InterpreterRuntimeError(`${ref.namespace}.${ref.name} is not available.`, node);
120
- };
121
66
  const requireDataArgument = (name, index, arg, node) => {
122
67
  if (containsOpaqueReference(arg)) {
123
68
  throw new InterpreterRuntimeError(`String.${name} expects argument ${index + 1} to be a data value.`, node, "InvalidDataValue");
@@ -282,117 +227,6 @@ const invokeStringMethod = (value, name, args, node) => {
282
227
  }
283
228
  return toProgram(result, `String.${name} result`);
284
229
  };
285
- export const arrayStatics = new Set(["isArray", "of", "from"]);
286
- const invokeArrayStatic = (name, args, node) => {
287
- switch (name) {
288
- case "isArray":
289
- return Array.isArray(args[0]);
290
- case "of":
291
- return [...args];
292
- default:
293
- throw new InterpreterRuntimeError(`Array.${name} is not available.`, node);
294
- }
295
- };
296
- const arrayLikeSource = (source, node) => {
297
- if (source instanceof Values.Promise) {
298
- throw new InterpreterRuntimeError("Array.from received an un-awaited Promise; await it before creating the array.", node, "InvalidDataValue");
299
- }
300
- if (source !== null &&
301
- typeof source === "object" &&
302
- (Object.getPrototypeOf(source) === Object.prototype || Object.getPrototypeOf(source) === null) &&
303
- typeof source.length === "number") {
304
- const length = source.length;
305
- const normalized = Number.isNaN(length) || length <= 0 ? 0 : Math.trunc(length);
306
- if (normalized > 4_294_967_295)
307
- throw new RangeError("Invalid array length");
308
- return { length: normalized, source };
309
- }
310
- throw new InterpreterRuntimeError("Array.from expects an array, string, Map, Set, or array-like value.", node, "InvalidDataValue");
311
- };
312
- export const invokeArrayFrom = (runner, args, node) => {
313
- const source = args[0];
314
- const apply = args.length < 2 || args[1] === undefined ? undefined : applyCollectionCallback(runner, args[1], "Array.from", node);
315
- return Effect.gen(function* () {
316
- const cursor = yield* runner.syncIterator(source, node);
317
- if (cursor === undefined) {
318
- if (source instanceof CodeModeGenerator) {
319
- throw new InterpreterRuntimeError("Array.from expects a synchronous iterable or array-like value.", node).as("TypeError");
320
- }
321
- const arrayLike = arrayLikeSource(source, node);
322
- const values = [];
323
- for (let index = 0; index < arrayLike.length; index += 1) {
324
- const item = Reflect.get(arrayLike.source, index);
325
- values.push(apply === undefined ? item : yield* apply([item, index]));
326
- }
327
- return values;
328
- }
329
- const values = [];
330
- let index = 0;
331
- while (true) {
332
- const step = yield* cursor.next;
333
- if (step.done)
334
- return values;
335
- values.push(apply === undefined ? step.value : yield* preserveConsumerError(cursor, apply([step.value, index])));
336
- index += 1;
337
- }
338
- });
339
- };
340
- export const invokeGroupBy = (runner, namespace, args, node) => {
341
- const source = args[0];
342
- if (source === null || source === undefined) {
343
- throw new InterpreterRuntimeError(`${namespace}.groupBy expects an iterable collection.`, node).as("TypeError");
344
- }
345
- const apply = applyCollectionCallback(runner, args[1], `${namespace}.groupBy`, node);
346
- return Effect.gen(function* () {
347
- const cursor = yield* runner.syncIterator(source, node);
348
- if (cursor === undefined) {
349
- throw new InterpreterRuntimeError(`${namespace}.groupBy expects an iterable collection.`, node).as("TypeError");
350
- }
351
- if (namespace === "Map") {
352
- const result = new Values.Map();
353
- let index = 0;
354
- while (true) {
355
- const step = yield* cursor.next;
356
- if (step.done)
357
- return result;
358
- const item = step.value;
359
- const key = yield* preserveConsumerError(cursor, apply([item, index]));
360
- const group = result.map.get(key);
361
- if (group === undefined)
362
- result.map.set(key, [item]);
363
- else
364
- group.push(item);
365
- index += 1;
366
- }
367
- }
368
- const result = Object.create(null);
369
- let index = 0;
370
- while (true) {
371
- const step = yield* cursor.next;
372
- if (step.done)
373
- return result;
374
- const item = step.value;
375
- const key = yield* preserveConsumerError(cursor, Effect.flatMap(apply([item, index]), (value) => coerceGroupByPropertyKey(runner, value, node)));
376
- if (isBlockedMember(key)) {
377
- return yield* preserveConsumerError(cursor, Effect.fail(new InterpreterRuntimeError(`Property '${key}' is not available.`, node)));
378
- }
379
- const group = result[key];
380
- if (group === undefined)
381
- result[key] = [item];
382
- else
383
- group.push(item);
384
- index += 1;
385
- }
386
- });
387
- };
388
- const coerceGroupByPropertyKey = (runner, value, node) => {
389
- if (value instanceof Values.Promise)
390
- return Effect.succeed("[object Promise]");
391
- if (!Values.isValue(value) && isRuntimeReference(value)) {
392
- throw new InterpreterRuntimeError("Object.groupBy callback must return a data value.", node, "InvalidDataValue");
393
- }
394
- return Effect.map(toPrimitive(runner, value, "string", node), coerceToString);
395
- };
396
230
  const invokeStringReplacer = (runner, value, name, args, node) => {
397
231
  const apply = applyCollectionCallback(runner, args[1], `String.${name}`, node);
398
232
  const matches = [];
@@ -449,15 +283,6 @@ const invokeStringReplacer = (runner, value, name, args, node) => {
449
283
  return toProgram(output.join(""), `String.${name} result`);
450
284
  });
451
285
  };
452
- export const applyCollectionCallback = (runner, callback, name, node) => {
453
- if (!isSupportedCallback(callback)) {
454
- if (typeofValue(callback) === "function") {
455
- throw new InterpreterRuntimeError(`${name} cannot use this callable as a callback; wrap it in an arrow function, e.g. (value) => tools.ns.tool(value).`, node);
456
- }
457
- throw new InterpreterRuntimeError(`${name} expects a function callback.`, node).as("TypeError");
458
- }
459
- return (callbackArgs) => runner.invokeCallable(callback, callbackArgs, node);
460
- };
461
286
  const invokeMapMethod = (runner, target, name, args, node) => {
462
287
  switch (name) {
463
288
  case "get":
@@ -54,52 +54,15 @@ export declare class ComputedValue {
54
54
  readonly value: unknown;
55
55
  constructor(value: unknown);
56
56
  }
57
- export declare class PromiseNamespace {
58
- }
59
- export declare class SymbolNamespace {
60
- }
61
57
  export declare const AsyncIteratorSymbol: unique symbol;
62
58
  export declare const IteratorSymbol: unique symbol;
63
59
  export declare const IteratorSymbols: readonly [typeof AsyncIteratorSymbol, typeof IteratorSymbol];
64
- export type PromiseMethodName = "all" | "allSettled" | "race" | "any" | "resolve" | "reject";
65
- export declare class PromiseMethodReference {
66
- readonly name: PromiseMethodName;
67
- constructor(name: PromiseMethodName);
68
- }
69
60
  export type PromiseInstanceMethodName = "then" | "catch" | "finally";
70
61
  export declare class PromiseInstanceMethodReference {
71
62
  readonly promise: Values.Promise;
72
63
  readonly name: PromiseInstanceMethodName;
73
64
  constructor(promise: Values.Promise, name: PromiseInstanceMethodName);
74
65
  }
75
- export declare class PromiseCapabilityFunction {
76
- readonly settle: (value: unknown) => void;
77
- constructor(settle: (value: unknown) => void);
78
- }
79
- export type GlobalNamespaceName = "Object" | "Math" | "JSON" | "Array" | "console" | "Date" | "RegExp" | "Map" | "Set" | "URL" | "URLSearchParams";
80
- export declare class GlobalNamespace {
81
- readonly name: GlobalNamespaceName;
82
- constructor(name: GlobalNamespaceName);
83
- }
84
- export declare class GlobalMethodReference {
85
- readonly namespace: Exclude<GlobalNamespaceName, "JSON"> | "Number" | "String";
86
- readonly name: string;
87
- constructor(namespace: Exclude<GlobalNamespaceName, "JSON"> | "Number" | "String", name: string);
88
- }
89
- export declare class JsonMethodReference {
90
- readonly name: "parse" | "stringify";
91
- constructor(name: "parse" | "stringify");
92
- }
93
- export declare class CoercionFunction {
94
- readonly name: "Number" | "String" | "Boolean" | "parseInt" | "parseFloat" | "isFinite" | "isNaN";
95
- constructor(name: "Number" | "String" | "Boolean" | "parseInt" | "parseFloat" | "isFinite" | "isNaN");
96
- }
97
- export declare class UriFunction {
98
- readonly name: "encodeURI" | "encodeURIComponent" | "decodeURI" | "decodeURIComponent";
99
- constructor(name: "encodeURI" | "encodeURIComponent" | "decodeURI" | "decodeURIComponent");
100
- }
101
- export declare class SearchFunction {
102
- }
103
66
  export declare class ProgramThrow {
104
67
  readonly value: unknown;
105
68
  constructor(value: unknown);
@@ -108,10 +71,6 @@ export declare class GeneratorReturn {
108
71
  readonly value: unknown;
109
72
  constructor(value: unknown);
110
73
  }
111
- export declare class ErrorConstructorReference {
112
- readonly name: string;
113
- constructor(name: string);
114
- }
115
74
  export declare const OptionalShortCircuit: unique symbol;
116
75
  export declare const supportedSyntaxMessage = "Supported orchestration syntax: tools.* calls (they return promises - resolve them with await), data literals, destructuring, optional chaining, template literals, conditionals, switch, loops (incl. for...of and for...in over object/array/tools keys), arrow functions, spread, try/catch, array methods (map/filter/find/findIndex/some/every/reduce/flatMap/forEach/sort/slice/concat/indexOf/lastIndexOf/at/flat/reverse/includes/join), string methods (incl. match/matchAll/replace/split with regular expressions), Date/RegExp/Map/Set/URL/URLSearchParams, URI encoding helpers, Object/Math/JSON helpers, captured console.log/warn/error/dir/table, Promise.all/allSettled/race/any/resolve/reject over arrays mixing promises and plain values for parallel tool calls, promise chaining with .then/.catch/.finally, and new Promise((resolve, reject) => ...) construction.";
117
76
  export declare class InterpreterRuntimeError extends Error {
@@ -42,19 +42,9 @@ export class ComputedValue {
42
42
  this.value = value;
43
43
  }
44
44
  }
45
- export class PromiseNamespace {
46
- }
47
- export class SymbolNamespace {
48
- }
49
45
  export const AsyncIteratorSymbol = Symbol("codemode.async-iterator");
50
46
  export const IteratorSymbol = Symbol("codemode.iterator");
51
47
  export const IteratorSymbols = [AsyncIteratorSymbol, IteratorSymbol];
52
- export class PromiseMethodReference {
53
- name;
54
- constructor(name) {
55
- this.name = name;
56
- }
57
- }
58
48
  export class PromiseInstanceMethodReference {
59
49
  promise;
60
50
  name;
@@ -63,46 +53,6 @@ export class PromiseInstanceMethodReference {
63
53
  this.name = name;
64
54
  }
65
55
  }
66
- export class PromiseCapabilityFunction {
67
- settle;
68
- constructor(settle) {
69
- this.settle = settle;
70
- }
71
- }
72
- export class GlobalNamespace {
73
- name;
74
- constructor(name) {
75
- this.name = name;
76
- }
77
- }
78
- export class GlobalMethodReference {
79
- namespace;
80
- name;
81
- constructor(namespace, name) {
82
- this.namespace = namespace;
83
- this.name = name;
84
- }
85
- }
86
- export class JsonMethodReference {
87
- name;
88
- constructor(name) {
89
- this.name = name;
90
- }
91
- }
92
- export class CoercionFunction {
93
- name;
94
- constructor(name) {
95
- this.name = name;
96
- }
97
- }
98
- export class UriFunction {
99
- name;
100
- constructor(name) {
101
- this.name = name;
102
- }
103
- }
104
- export class SearchFunction {
105
- }
106
56
  export class ProgramThrow {
107
57
  value;
108
58
  constructor(value) {
@@ -115,12 +65,6 @@ export class GeneratorReturn {
115
65
  this.value = value;
116
66
  }
117
67
  }
118
- export class ErrorConstructorReference {
119
- name;
120
- constructor(name) {
121
- this.name = name;
122
- }
123
- }
124
68
  export const OptionalShortCircuit = Symbol("codemode.optional-short-circuit");
125
69
  export const supportedSyntaxMessage = "Supported orchestration syntax: tools.* calls (they return promises - resolve them with await), data literals, destructuring, optional chaining, template literals, conditionals, switch, loops (incl. for...of and for...in over object/array/tools keys), arrow functions, spread, try/catch, array methods (map/filter/find/findIndex/some/every/reduce/flatMap/forEach/sort/slice/concat/indexOf/lastIndexOf/at/flat/reverse/includes/join), string methods (incl. match/matchAll/replace/split with regular expressions), Date/RegExp/Map/Set/URL/URLSearchParams, URI encoding helpers, Object/Math/JSON helpers, captured console.log/warn/error/dir/table, Promise.all/allSettled/race/any/resolve/reject over arrays mixing promises and plain values for parallel tool calls, promise chaining with .then/.catch/.finally, and new Promise((resolve, reject) => ...) construction.";
126
70
  export class InterpreterRuntimeError extends Error {