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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +3 -0
  2. package/dist/codemode.d.ts +2 -0
  3. package/dist/codemode.js +10 -4
  4. package/dist/vm/async.d.ts +78 -0
  5. package/dist/vm/async.js +335 -0
  6. package/dist/vm/code.d.ts +122 -0
  7. package/dist/vm/code.js +407 -0
  8. package/dist/vm/compiler/compile.d.ts +13 -0
  9. package/dist/vm/compiler/compile.js +1477 -0
  10. package/dist/vm/compiler/scope.d.ts +74 -0
  11. package/dist/vm/compiler/scope.js +515 -0
  12. package/dist/vm/data.d.ts +7 -0
  13. package/dist/vm/data.js +13 -0
  14. package/dist/vm/generators.d.ts +42 -0
  15. package/dist/vm/generators.js +413 -0
  16. package/dist/vm/host.d.ts +103 -0
  17. package/dist/vm/host.js +226 -0
  18. package/dist/vm/index.d.ts +3 -0
  19. package/dist/vm/index.js +3 -0
  20. package/dist/vm/internal-prelude.d.ts +45 -0
  21. package/dist/vm/internal-prelude.js +534 -0
  22. package/dist/vm/opcodes.d.ts +222 -0
  23. package/dist/vm/opcodes.js +235 -0
  24. package/dist/vm/prelude/bytecode.d.ts +18 -0
  25. package/dist/vm/prelude/bytecode.js +31 -0
  26. package/dist/vm/prelude/bytecode.json +1 -0
  27. package/dist/vm/prelude/helpers.d.ts +8 -0
  28. package/dist/vm/prelude/helpers.js +258 -0
  29. package/dist/vm/prelude/prelude.d.ts +21 -0
  30. package/dist/vm/prelude/prelude.js +53 -0
  31. package/dist/vm/prelude/source.d.ts +1 -0
  32. package/dist/vm/prelude/source.js +652 -0
  33. package/dist/vm/runtime/callback.d.ts +25 -0
  34. package/dist/vm/runtime/callback.js +51 -0
  35. package/dist/vm/runtime/driver.d.ts +41 -0
  36. package/dist/vm/runtime/driver.js +142 -0
  37. package/dist/vm/runtime/errors.d.ts +23 -0
  38. package/dist/vm/runtime/errors.js +169 -0
  39. package/dist/vm/runtime/execute.d.ts +22 -0
  40. package/dist/vm/runtime/execute.js +278 -0
  41. package/dist/vm/runtime/extensions.d.ts +16 -0
  42. package/dist/vm/runtime/extensions.js +270 -0
  43. package/dist/vm/runtime/generators.d.ts +6 -0
  44. package/dist/vm/runtime/generators.js +44 -0
  45. package/dist/vm/runtime/globals.d.ts +6 -0
  46. package/dist/vm/runtime/globals.js +137 -0
  47. package/dist/vm/runtime/interpreter.d.ts +50 -0
  48. package/dist/vm/runtime/interpreter.js +94 -0
  49. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  50. package/dist/vm/runtime/intrinsic-names.js +166 -0
  51. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  52. package/dist/vm/runtime/intrinsics.js +111 -0
  53. package/dist/vm/runtime/limits.d.ts +10 -0
  54. package/dist/vm/runtime/limits.js +19 -0
  55. package/dist/vm/runtime/model.d.ts +58 -0
  56. package/dist/vm/runtime/model.js +57 -0
  57. package/dist/vm/runtime/modules.d.ts +4 -0
  58. package/dist/vm/runtime/modules.js +33 -0
  59. package/dist/vm/runtime/native.d.ts +19 -0
  60. package/dist/vm/runtime/native.js +41 -0
  61. package/dist/vm/runtime/objects.d.ts +403 -0
  62. package/dist/vm/runtime/objects.js +784 -0
  63. package/dist/vm/runtime/operations.d.ts +49 -0
  64. package/dist/vm/runtime/operations.js +288 -0
  65. package/dist/vm/runtime/promises.d.ts +55 -0
  66. package/dist/vm/runtime/promises.js +232 -0
  67. package/dist/vm/runtime/references.d.ts +8 -0
  68. package/dist/vm/runtime/references.js +51 -0
  69. package/dist/vm/runtime/signals.d.ts +69 -0
  70. package/dist/vm/runtime/signals.js +68 -0
  71. package/dist/vm/runtime/source.d.ts +29 -0
  72. package/dist/vm/runtime/source.js +63 -0
  73. package/dist/vm/runtime/table.d.ts +43 -0
  74. package/dist/vm/runtime/table.js +132 -0
  75. package/dist/vm/scheduler.d.ts +178 -0
  76. package/dist/vm/scheduler.js +63 -0
  77. package/dist/vm/snapshot/codec.d.ts +88 -0
  78. package/dist/vm/snapshot/codec.js +752 -0
  79. package/dist/vm/snapshot/snapshot.d.ts +39 -0
  80. package/dist/vm/snapshot/snapshot.js +69 -0
  81. package/dist/vm/snapshot.d.ts +29 -0
  82. package/dist/vm/snapshot.js +304 -0
  83. package/dist/vm/stdlib/array.d.ts +16 -0
  84. package/dist/vm/stdlib/array.js +311 -0
  85. package/dist/vm/stdlib/bytes.d.ts +11 -0
  86. package/dist/vm/stdlib/bytes.js +222 -0
  87. package/dist/vm/stdlib/collections.d.ts +7 -0
  88. package/dist/vm/stdlib/collections.js +188 -0
  89. package/dist/vm/stdlib/console.d.ts +6 -0
  90. package/dist/vm/stdlib/console.js +93 -0
  91. package/dist/vm/stdlib/date.d.ts +2 -0
  92. package/dist/vm/stdlib/date.js +123 -0
  93. package/dist/vm/stdlib/headers.d.ts +2 -0
  94. package/dist/vm/stdlib/headers.js +92 -0
  95. package/dist/vm/stdlib/iterator.d.ts +2 -0
  96. package/dist/vm/stdlib/iterator.js +30 -0
  97. package/dist/vm/stdlib/json.d.ts +3 -0
  98. package/dist/vm/stdlib/json.js +42 -0
  99. package/dist/vm/stdlib/math.d.ts +3 -0
  100. package/dist/vm/stdlib/math.js +73 -0
  101. package/dist/vm/stdlib/number.d.ts +3 -0
  102. package/dist/vm/stdlib/number.js +72 -0
  103. package/dist/vm/stdlib/object.d.ts +6 -0
  104. package/dist/vm/stdlib/object.js +201 -0
  105. package/dist/vm/stdlib/regexp.d.ts +8 -0
  106. package/dist/vm/stdlib/regexp.js +119 -0
  107. package/dist/vm/stdlib/string.d.ts +2 -0
  108. package/dist/vm/stdlib/string.js +272 -0
  109. package/dist/vm/stdlib/url.d.ts +25 -0
  110. package/dist/vm/stdlib/url.js +255 -0
  111. package/dist/vm/stdlib/value.d.ts +6 -0
  112. package/dist/vm/stdlib/value.js +32 -0
  113. package/dist/vm/stdlib/web.d.ts +5 -0
  114. package/dist/vm/stdlib/web.js +97 -0
  115. package/dist/vm/vm.d.ts +224 -0
  116. package/dist/vm/vm.js +2921 -0
  117. package/package.json +5 -2
@@ -0,0 +1,97 @@
1
+ import { fn, methods } from "../runtime/native.js";
2
+ import { typeError } from "../runtime/model.js";
3
+ import { define, entries, get, getOwn, hasOwn, hidden, isRuntimeReference, Arr, Bytes, DateObj, ErrorObj, MapObj, Obj, RegExpObj, SetObj, WeakMapObj, WeakSetObj, coerceToString, } from "../runtime/objects.js";
4
+ import { createErrorValue, isErrorType } from "../runtime/intrinsics.js";
5
+ import { describeValue } from "../runtime/references.js";
6
+ import { ToolReference } from "../../tool-runtime.js";
7
+ // WebIDL DOMString conversion: a missing argument is a TypeError, anything else stringifies. Invalid input is a
8
+ // TypeError as well; browsers throw a DOMException named InvalidCharacterError, which CodeMode does not have.
9
+ export const base64Global = (ctx, name) => fn(ctx.builtins, name, 1, (_, args) => {
10
+ if (args.length === 0)
11
+ throw typeError(`${name} requires 1 argument (a string)`);
12
+ const input = coerceToString(args[0]);
13
+ try {
14
+ return name === "atob" ? atob(input) : btoa(input);
15
+ }
16
+ catch {
17
+ throw typeError("The string contains invalid characters.");
18
+ }
19
+ });
20
+ // HTML structured clone over CodeMode's data kinds. Shared references survive through the memo; prototypes and
21
+ // frozen state do not, as in JS. Without a DOMException, DataCloneError is a TypeError carrying that prefix.
22
+ export const structuredCloneGlobal = (ctx) => fn(ctx.builtins, "structuredClone", 1, (_, args) => {
23
+ if (args.length === 0)
24
+ throw typeError("structuredClone requires 1 argument");
25
+ const builtins = ctx.builtins;
26
+ const memo = new Map();
27
+ const clone = (value) => {
28
+ if (typeof value === "symbol" || value instanceof ToolReference) {
29
+ throw typeError(`DataCloneError: ${describeValue(value)} could not be cloned.`);
30
+ }
31
+ if (!(value instanceof Obj))
32
+ return value;
33
+ const seen = memo.get(value);
34
+ if (seen !== undefined)
35
+ return seen;
36
+ const remember = (copy) => {
37
+ memo.set(value, copy);
38
+ return copy;
39
+ };
40
+ if (value instanceof MapObj) {
41
+ const copy = remember(new MapObj(builtins.Map));
42
+ for (const [key, item] of value.map)
43
+ copy.map.set(clone(key), clone(item));
44
+ return copy;
45
+ }
46
+ if (value instanceof SetObj) {
47
+ const copy = remember(new SetObj(builtins.Set));
48
+ for (const item of value.set.liveKeys())
49
+ copy.set.add(clone(item));
50
+ return copy;
51
+ }
52
+ if (value instanceof DateObj)
53
+ return remember(new DateObj(builtins.Date, value.time));
54
+ if (value instanceof RegExpObj) {
55
+ return remember(new RegExpObj(builtins.RegExp, value.source, value.flags));
56
+ }
57
+ if (value instanceof Bytes)
58
+ return remember(new Bytes(builtins.Uint8Array, new Uint8Array(value.bytes)));
59
+ if (value instanceof ErrorObj) {
60
+ const name = get(value, "name");
61
+ const message = get(value, "message");
62
+ const copy = remember(createErrorValue(builtins[typeof name === "string" && isErrorType(name) ? name : "Error"], message === undefined ? undefined : coerceToString(message)));
63
+ const stack = getOwn(value, "stack");
64
+ if (typeof stack === "string")
65
+ define(copy, "stack", stack, hidden);
66
+ if (hasOwn(value, "cause"))
67
+ define(copy, "cause", clone(getOwn(value, "cause")), hidden);
68
+ return copy;
69
+ }
70
+ if (isRuntimeReference(value) || value instanceof WeakMapObj || value instanceof WeakSetObj) {
71
+ throw typeError(`DataCloneError: ${describeValue(value)} could not be cloned.`);
72
+ }
73
+ const copy = remember(value instanceof Arr ? new Arr(builtins.Array, new Array(value.items.length)) : new Obj(builtins.Object));
74
+ for (const [key, item] of entries(value))
75
+ define(copy, key, clone(item));
76
+ return copy;
77
+ };
78
+ return clone(args[0]);
79
+ });
80
+ export const cryptoGlobal = (ctx) => {
81
+ const object = new Obj(ctx.builtins.Object);
82
+ methods(ctx.builtins, object, [
83
+ ["randomUUID", 0, () => crypto.randomUUID()],
84
+ [
85
+ "getRandomValues",
86
+ 1,
87
+ (_, args) => {
88
+ if (!(args[0] instanceof Bytes)) {
89
+ throw typeError(`crypto.getRandomValues expects a Uint8Array, received ${describeValue(args[0])}.`);
90
+ }
91
+ crypto.getRandomValues(args[0].bytes);
92
+ return args[0];
93
+ },
94
+ ],
95
+ ]);
96
+ return object;
97
+ };
@@ -0,0 +1,224 @@
1
+ import type { Diagnostic } from "../codemode.js";
2
+ import type { Interpreter } from "./runtime/interpreter.js";
3
+ import { type AstNode } from "./runtime/model.js";
4
+ import { Arr, Fn, Obj, type Value } from "./runtime/objects.js";
5
+ import { type Completion } from "./runtime/signals.js";
6
+ import { Source } from "./runtime/source.js";
7
+ import type { HostCall, Stop } from "./scheduler.js";
8
+ import { VmScheduler } from "./async.js";
9
+ import type { Code } from "./code.js";
10
+ import { type CaptureOptions, type RestoreOptions } from "./snapshot.js";
11
+ import { HostCalls } from "./host.js";
12
+ import { Cell } from "./opcodes.js";
13
+ export declare const Mode: {
14
+ readonly CALLER: 0;
15
+ readonly ASYNC: 1;
16
+ readonly GENERATOR: 2;
17
+ readonly SETTLE: 3;
18
+ readonly REJECT_ONLY: 4;
19
+ readonly PROGRAM: 5;
20
+ readonly BOUNDARY_OUT: 6;
21
+ };
22
+ export type FrameMode = (typeof Mode)[keyof typeof Mode];
23
+ /** Custom synchronous/async iterator state stored in a frame's hidden `%it` slot. */
24
+ export declare class CustomIter {
25
+ readonly iterator: Obj;
26
+ readonly next: Value;
27
+ done: boolean;
28
+ rawGen: boolean;
29
+ constructor(iterator: Obj, next: Value);
30
+ }
31
+ /** Single uniform activation record for the bytecode VM. */
32
+ export declare class Frame {
33
+ fn: Fn | null;
34
+ cells: ReadonlyArray<Cell>;
35
+ code: Code;
36
+ pc: number;
37
+ sp: number;
38
+ regs: Array<unknown>;
39
+ thisValue: Value;
40
+ args: Array<Value> | undefined;
41
+ mode: FrameMode;
42
+ target: unknown;
43
+ answer: unknown;
44
+ origin: AstNode | undefined;
45
+ counted: boolean;
46
+ constructor(code: Code, regs: Array<unknown>);
47
+ }
48
+ /** Internal closure wrapper that does not touch `builtins.Function` or `nativeRule.sealed`. */
49
+ export declare class VmInternalFn {
50
+ readonly code: Code;
51
+ readonly boundArgs?: ReadonlyArray<Value> | undefined;
52
+ constructor(code: Code, boundArgs?: ReadonlyArray<Value> | undefined);
53
+ }
54
+ /**
55
+ * Runs a runtime's program code: the job stack, the job queue, promises, and host calls. `execute.ts` and the driver
56
+ * use only its host surface:
57
+ *
58
+ * - **Starting.** Exactly one of `start(source)` (a new run) or `restore(saved, …)` (a saved one), once. Host call
59
+ * ids count up in program order.
60
+ * - **Running.** `run()` is synchronous, runs no host work, and returns a `Stop`:
61
+ * - `host(calls)`: start these queued calls now (they are `queued`; the driver marks them `running`),
62
+ * then call `run()` again; `host([])` means wait until `ready` (a blocking call or the inbox has input) and call
63
+ * `run()` again;
64
+ * - `slice`: the time slice is over; yield to the host scheduler and call `run()` again;
65
+ * - `done(completion)`: the program's body ended; host calls may still be running (`diagnostics()` reports
66
+ * unhandled rejections);
67
+ * - `stuck(node)`: nothing is queued or running, and the body awaits something that can never settle.
68
+ * - **Host calls.** `complete(id, completion)` reports how a handed-over call ended, at any time between `run()`s: a
69
+ * blocking call's outcome continues the job that made it; a concurrent call's waits in the inbox and settles its
70
+ * promise in a later job, in completion order. Unknown or completed ids are ignored. `call(id)`/`calls()` list the
71
+ * calls handed over and not completed, in the order they were made.
72
+ * - **Snapshots.** `capture` and `restore` run only between `run()`s, synchronously. A capture changes nothing a
73
+ * later `run()` sees; it fails (throws) only on a codec gap. A state holding live host values (`calls()` with an
74
+ * extension call, or `activeExtension`) can't be restored faithfully.
75
+ */
76
+ export declare class Vm {
77
+ readonly ctx: Interpreter<unknown>;
78
+ readonly frames: Array<Frame>;
79
+ private readonly pool;
80
+ readonly sourceCodes: Map<string, readonly Code[]>;
81
+ readonly templates: Map<string, Arr>;
82
+ readonly intrinsics: Map<string, unknown>;
83
+ readonly scheduler: VmScheduler;
84
+ /** Host calls: queued, running, completed, and the blocking one the job on the stack waits on. */
85
+ readonly hosts: HostCalls;
86
+ depth: number;
87
+ fuel: number;
88
+ sliceStart: number;
89
+ sliced: boolean;
90
+ outcome: Completion | undefined;
91
+ /** Round-trip test mode (task C): slice after this many fuel ticks, so the run is saved and restored all through. */
92
+ tripEvery: number;
93
+ constructor(ctx: Interpreter<unknown>);
94
+ private initIntrinsics;
95
+ private getIntrinsic;
96
+ /** Queues the program's body as the root frame. */
97
+ start(source: Source): void;
98
+ /**
99
+ * Runs until it has to stop (`Stop`), in this order: hand over queued host calls; a due slice; continue the job a
100
+ * completed blocking call waits on; wait while the job on the stack is blocked; continue a sliced job before any
101
+ * other; the outcome; the next job; one inbox completion; wait for running calls; stuck.
102
+ */
103
+ run(): Stop;
104
+ private resumeBlocked;
105
+ /** Reports how host work handed over by a `host` stop ended. */
106
+ complete(id: number, completion: Completion): void;
107
+ /** Whether `run` has something to do: a blocking call's outcome, or one in the inbox while no job runs. */
108
+ get ready(): boolean;
109
+ /** A host call handed over and not yet completed, by id. */
110
+ call(id: number): HostCall | undefined;
111
+ /** The host calls handed over and not yet completed, in the order they were made. */
112
+ calls(): Array<HostCall>;
113
+ compact(): void;
114
+ /** Unhandled rejections, in promise creation order, once inbox completions are delivered. */
115
+ diagnostics(): Array<Diagnostic>;
116
+ /**
117
+ * A synchronous extension call the program is in the middle of, from its `before` hook until its result is a
118
+ * program value or its concurrent call is running: it holds live host values.
119
+ */
120
+ get activeExtension(): {
121
+ readonly path: string;
122
+ } | undefined;
123
+ /** Saves the run's state as it is now. */
124
+ capture(options: CaptureOptions): {
125
+ readonly snapshot: import("./snapshot/snapshot.js").Snapshot;
126
+ readonly lost: ReadonlyArray<string>;
127
+ };
128
+ /** Restores a saved state into this fresh VM, after checking it belongs to this build and runtime. */
129
+ restore(saved: unknown, options: RestoreOptions): import("./snapshot/snapshot.js").Snapshot;
130
+ deliverAnswer(frame: Frame): void;
131
+ acquire(code: Code): Frame;
132
+ release(frame: Frame): void;
133
+ private codesOf;
134
+ /**
135
+ * Nearest non-internal frame's AST site, or the bottom internal frame's `origin` (§3.6). A failure the host
136
+ * boundary's own walk raises (copying out the result, or a tool call's arguments) has no location: the call that
137
+ * crosses reports it.
138
+ */
139
+ currentSite(): AstNode | undefined;
140
+ private exec;
141
+ private copyParams;
142
+ private failCallDepth;
143
+ private failStringLength;
144
+ private execInstanceof;
145
+ private execBinopSlow;
146
+ private execThrow;
147
+ private execForIn;
148
+ private onGeneratorStart;
149
+ private onYield;
150
+ private onResume;
151
+ private onAwait;
152
+ private onYstar;
153
+ private onYstarResult;
154
+ private failOpcode;
155
+ private execRot;
156
+ private failTdz;
157
+ private failPut;
158
+ private execGetGlobal;
159
+ private execArgs;
160
+ private execSetName;
161
+ private execToKey;
162
+ private execIn;
163
+ private execNewArray;
164
+ private execArrayAppend;
165
+ private execDefineField;
166
+ private execCopyDataProps;
167
+ private execCopyRest;
168
+ private execRegExp;
169
+ private execBinopNum;
170
+ private execToNumericSlow;
171
+ private execIncSlow;
172
+ private execToStringSlow;
173
+ private execConcat;
174
+ private execThrowError;
175
+ private execEndFinally;
176
+ private execReturnSlow;
177
+ private execCallSpread;
178
+ private execNew;
179
+ private execNewSpread;
180
+ private execIterStepSlow;
181
+ private execIterResult;
182
+ private execIterClose;
183
+ private execIterAppendAll;
184
+ private readObjProp;
185
+ unwind(rawError: unknown): boolean;
186
+ private finishProgram;
187
+ private makeClosure;
188
+ private getTemplateObject;
189
+ private execImport;
190
+ private execGetProp;
191
+ private execGetElem;
192
+ private readMember;
193
+ private resolveMember;
194
+ private execPutProp;
195
+ private execPutElem;
196
+ private execDeleteProp;
197
+ private execDeleteElem;
198
+ private execCheckBase;
199
+ private execBinarySlow;
200
+ private execUnarySlow;
201
+ private execCallSlow;
202
+ /**
203
+ * Dispatches a call to `callee`. Returns `0` if synchronous value pushed, `1` if a frame was entered, `2` if the job
204
+ * blocks on a host call.
205
+ */
206
+ private invokeCallable;
207
+ private execConstruct;
208
+ private settleNativeResult;
209
+ private hostResult;
210
+ /**
211
+ * Enters the program function `fn`, from the call at `origin`. A frame in another `mode` than `CALLER` settles
212
+ * `target`, and hands the caller `answer` when it ends.
213
+ */
214
+ pushFn(fn: Fn, thisValue: Value, args: Array<Value>, origin: AstNode | undefined, mode: FrameMode, target?: unknown, answer?: Value): void;
215
+ private pushInternalCall;
216
+ /** Runs an internal prelude function at the call `origin`; see `HostVm.pushInternal`. */
217
+ pushInternal(code: Code, args: ReadonlyArray<unknown>, origin: AstNode | undefined, mode?: FrameMode, target?: unknown, answer?: Value): Frame;
218
+ private execIterOpen;
219
+ private execIterInit;
220
+ private openWithMethod;
221
+ private customIter;
222
+ private execExtra;
223
+ private execWide;
224
+ }