@opencode/codemode 2.2.4 → 2.2.6

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 (133) hide show
  1. package/README.md +70 -1
  2. package/dist/codemode.d.ts +55 -4
  3. package/dist/codemode.js +63 -8
  4. package/dist/extension.d.ts +14 -9
  5. package/dist/extension.js +2 -2
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/interpreter/execute.d.ts +1 -1
  9. package/dist/interpreter/execute.js +16 -4
  10. package/dist/interpreter/extensions.d.ts +3 -3
  11. package/dist/interpreter/extensions.js +17 -11
  12. package/dist/interpreter/globals.js +10 -0
  13. package/dist/interpreter/interpreter.d.ts +11 -1
  14. package/dist/interpreter/interpreter.js +86 -2
  15. package/dist/interpreter/modules.d.ts +4 -0
  16. package/dist/interpreter/modules.js +33 -0
  17. package/dist/suspend-error.d.ts +23 -0
  18. package/dist/suspend-error.js +25 -0
  19. package/dist/tool-runtime.d.ts +4 -1
  20. package/dist/vm/async.d.ts +78 -0
  21. package/dist/vm/async.js +335 -0
  22. package/dist/vm/code.d.ts +122 -0
  23. package/dist/vm/code.js +407 -0
  24. package/dist/vm/compiler/compile.d.ts +13 -0
  25. package/dist/vm/compiler/compile.js +1477 -0
  26. package/dist/vm/compiler/scope.d.ts +74 -0
  27. package/dist/vm/compiler/scope.js +515 -0
  28. package/dist/vm/data.d.ts +7 -0
  29. package/dist/vm/data.js +13 -0
  30. package/dist/vm/generators.d.ts +42 -0
  31. package/dist/vm/generators.js +413 -0
  32. package/dist/vm/host.d.ts +103 -0
  33. package/dist/vm/host.js +226 -0
  34. package/dist/vm/index.d.ts +6 -0
  35. package/dist/vm/index.js +6 -0
  36. package/dist/vm/internal-prelude.d.ts +45 -0
  37. package/dist/vm/internal-prelude.js +534 -0
  38. package/dist/vm/opcodes.d.ts +222 -0
  39. package/dist/vm/opcodes.js +235 -0
  40. package/dist/vm/prelude/bytecode.d.ts +18 -0
  41. package/dist/vm/prelude/bytecode.js +31 -0
  42. package/dist/vm/prelude/bytecode.json +1 -0
  43. package/dist/vm/prelude/helpers.d.ts +8 -0
  44. package/dist/vm/prelude/helpers.js +258 -0
  45. package/dist/vm/prelude/prelude.d.ts +21 -0
  46. package/dist/vm/prelude/prelude.js +53 -0
  47. package/dist/vm/prelude/source.d.ts +1 -0
  48. package/dist/vm/prelude/source.js +652 -0
  49. package/dist/vm/runtime/callback.d.ts +25 -0
  50. package/dist/vm/runtime/callback.js +51 -0
  51. package/dist/vm/runtime/driver.d.ts +58 -0
  52. package/dist/vm/runtime/driver.js +184 -0
  53. package/dist/vm/runtime/errors.d.ts +23 -0
  54. package/dist/vm/runtime/errors.js +169 -0
  55. package/dist/vm/runtime/execute.d.ts +80 -0
  56. package/dist/vm/runtime/execute.js +414 -0
  57. package/dist/vm/runtime/extensions.d.ts +16 -0
  58. package/dist/vm/runtime/extensions.js +270 -0
  59. package/dist/vm/runtime/generators.d.ts +6 -0
  60. package/dist/vm/runtime/generators.js +44 -0
  61. package/dist/vm/runtime/globals.d.ts +6 -0
  62. package/dist/vm/runtime/globals.js +137 -0
  63. package/dist/vm/runtime/interpreter.d.ts +50 -0
  64. package/dist/vm/runtime/interpreter.js +94 -0
  65. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  66. package/dist/vm/runtime/intrinsic-names.js +166 -0
  67. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  68. package/dist/vm/runtime/intrinsics.js +111 -0
  69. package/dist/vm/runtime/limits.d.ts +10 -0
  70. package/dist/vm/runtime/limits.js +19 -0
  71. package/dist/vm/runtime/model.d.ts +58 -0
  72. package/dist/vm/runtime/model.js +57 -0
  73. package/dist/vm/runtime/modules.d.ts +4 -0
  74. package/dist/vm/runtime/modules.js +33 -0
  75. package/dist/vm/runtime/native.d.ts +19 -0
  76. package/dist/vm/runtime/native.js +41 -0
  77. package/dist/vm/runtime/objects.d.ts +403 -0
  78. package/dist/vm/runtime/objects.js +784 -0
  79. package/dist/vm/runtime/operations.d.ts +49 -0
  80. package/dist/vm/runtime/operations.js +288 -0
  81. package/dist/vm/runtime/promises.d.ts +55 -0
  82. package/dist/vm/runtime/promises.js +232 -0
  83. package/dist/vm/runtime/references.d.ts +8 -0
  84. package/dist/vm/runtime/references.js +51 -0
  85. package/dist/vm/runtime/signals.d.ts +69 -0
  86. package/dist/vm/runtime/signals.js +68 -0
  87. package/dist/vm/runtime/source.d.ts +29 -0
  88. package/dist/vm/runtime/source.js +63 -0
  89. package/dist/vm/runtime/table.d.ts +43 -0
  90. package/dist/vm/runtime/table.js +132 -0
  91. package/dist/vm/scheduler.d.ts +178 -0
  92. package/dist/vm/scheduler.js +63 -0
  93. package/dist/vm/snapshot/codec.d.ts +87 -0
  94. package/dist/vm/snapshot/codec.js +751 -0
  95. package/dist/vm/snapshot/snapshot.d.ts +49 -0
  96. package/dist/vm/snapshot/snapshot.js +70 -0
  97. package/dist/vm/snapshot.d.ts +32 -0
  98. package/dist/vm/snapshot.js +306 -0
  99. package/dist/vm/stdlib/array.d.ts +16 -0
  100. package/dist/vm/stdlib/array.js +311 -0
  101. package/dist/vm/stdlib/bytes.d.ts +11 -0
  102. package/dist/vm/stdlib/bytes.js +222 -0
  103. package/dist/vm/stdlib/collections.d.ts +7 -0
  104. package/dist/vm/stdlib/collections.js +188 -0
  105. package/dist/vm/stdlib/console.d.ts +6 -0
  106. package/dist/vm/stdlib/console.js +93 -0
  107. package/dist/vm/stdlib/date.d.ts +2 -0
  108. package/dist/vm/stdlib/date.js +123 -0
  109. package/dist/vm/stdlib/headers.d.ts +2 -0
  110. package/dist/vm/stdlib/headers.js +92 -0
  111. package/dist/vm/stdlib/iterator.d.ts +2 -0
  112. package/dist/vm/stdlib/iterator.js +30 -0
  113. package/dist/vm/stdlib/json.d.ts +3 -0
  114. package/dist/vm/stdlib/json.js +42 -0
  115. package/dist/vm/stdlib/math.d.ts +3 -0
  116. package/dist/vm/stdlib/math.js +73 -0
  117. package/dist/vm/stdlib/number.d.ts +3 -0
  118. package/dist/vm/stdlib/number.js +72 -0
  119. package/dist/vm/stdlib/object.d.ts +6 -0
  120. package/dist/vm/stdlib/object.js +201 -0
  121. package/dist/vm/stdlib/regexp.d.ts +8 -0
  122. package/dist/vm/stdlib/regexp.js +119 -0
  123. package/dist/vm/stdlib/string.d.ts +2 -0
  124. package/dist/vm/stdlib/string.js +272 -0
  125. package/dist/vm/stdlib/url.d.ts +25 -0
  126. package/dist/vm/stdlib/url.js +255 -0
  127. package/dist/vm/stdlib/value.d.ts +6 -0
  128. package/dist/vm/stdlib/value.js +32 -0
  129. package/dist/vm/stdlib/web.d.ts +5 -0
  130. package/dist/vm/stdlib/web.js +97 -0
  131. package/dist/vm/vm.d.ts +225 -0
  132. package/dist/vm/vm.js +2931 -0
  133. package/package.json +6 -3
@@ -0,0 +1,311 @@
1
+ import { Invoke } from "../runtime/signals.js";
2
+ import { builtinCursor } from "../runtime/operations.js";
3
+ import { constructor, methods, prototypeFrom, receiver, iteratorMethods } from "../runtime/native.js";
4
+ import { checkArrayLength, checkStringLength, MAX_ARRAY_LENGTH } from "../runtime/limits.js";
5
+ import { invalidData, IteratorSymbol, rangeError, typeError } from "../runtime/model.js";
6
+ import { changed, define, get, hidden, Arr, Bytes, GeneratorObj, Obj, PromiseObj, coerceToInteger, coerceToNumber, coerceToString, rejectAddition, } from "../runtime/objects.js";
7
+ import { describeValue, rejectCircularInsertion } from "../runtime/references.js";
8
+ import { requireCallback, withPrimitives } from "../runtime/callback.js";
9
+ import { compareText } from "../../tool-runtime.js";
10
+ const arrayLikeSource = (source) => {
11
+ // JS would treat a promise as an empty array-like; that would hide a missing `await`.
12
+ if (source instanceof Obj && !(source instanceof PromiseObj)) {
13
+ const length = Math.max(0, coerceToInteger(get(source, "length")));
14
+ checkArrayLength(length);
15
+ return { length, source };
16
+ }
17
+ throw invalidData(`Array.from expects an iterable or array-like value, received ${describeValue(source)}.`);
18
+ };
19
+ const iterable = (builtins, value) => {
20
+ if (builtinCursor(builtins, value) !== undefined)
21
+ return true;
22
+ if (!(value instanceof Obj))
23
+ return false;
24
+ const method = get(value, IteratorSymbol);
25
+ return method !== undefined && method !== null;
26
+ };
27
+ const arrayFrom = (ctx, args) => {
28
+ const source = args[0];
29
+ const mapper = args.length < 2 || args[1] === undefined ? undefined : requireCallback(args[1], "Array.from");
30
+ if (iterable(ctx.builtins, source)) {
31
+ return new Invoke(ctx.prelude.fn("arrayFromIterable"), undefined, [source, mapper, args[2]], undefined);
32
+ }
33
+ if (source instanceof GeneratorObj) {
34
+ throw typeError(`Array.from expects a synchronous iterable or array-like value, received ${describeValue(source)}.`);
35
+ }
36
+ const arrayLike = arrayLikeSource(source);
37
+ if (mapper === undefined) {
38
+ return new Arr(ctx.builtins.Array, Array.from({ length: arrayLike.length }, (_, index) => get(arrayLike.source, index)));
39
+ }
40
+ return new Invoke(ctx.prelude.fn("arrayFromLike"), undefined, [arrayLike.source, arrayLike.length, mapper, args[2]], undefined);
41
+ };
42
+ /** The most values the default sort sorts in one native call; more sort in bounded steps (see `sortDefault`). */
43
+ export const SORT_RUN = 4096;
44
+ /**
45
+ * Sorts `target`'s values: at once without a comparator, unless there are many, otherwise in the prelude
46
+ * (`sortWith`), which calls it. The merges of a top-down merge sort are planned here, in post-order, so the prelude
47
+ * compares in the same order as the recursive sort. Holes and undefined values sort last without being compared.
48
+ */
49
+ export const sortArray = (ctx, target, comparator, into) => {
50
+ const builtins = ctx.builtins;
51
+ const items = target instanceof Arr ? [...target.items] : [...target.bytes];
52
+ // Counted before any comparator runs; a comparator that changes the array does not change where holes go.
53
+ let holes = 0;
54
+ if (target instanceof Arr)
55
+ for (let index = 0; index < items.length; index++)
56
+ if (!(index in target.items))
57
+ holes++;
58
+ const callback = comparator === undefined ? undefined : requireCallback(comparator, into);
59
+ if (callback === undefined && items.length <= SORT_RUN) {
60
+ return sorted(builtins, target, into, holes, items.sort((a, b) => compareText(coerceToString(a), coerceToString(b))));
61
+ }
62
+ const defined = new Arr(builtins.Array, items.filter((item) => item !== undefined));
63
+ const undefs = items.length - defined.items.length;
64
+ if (callback === undefined) {
65
+ return new Invoke(ctx.prelude.fn("sortDefault"), undefined, [target, into, holes, defined, undefs], undefined);
66
+ }
67
+ const merges = [];
68
+ const plan = (low, high) => {
69
+ if (high - low <= 1)
70
+ return;
71
+ const middle = low + Math.floor((high - low) / 2);
72
+ plan(low, middle);
73
+ plan(middle, high);
74
+ merges.push(low, middle, high);
75
+ };
76
+ plan(0, defined.items.length);
77
+ const args = [target, into, holes, callback, defined, undefs, new Arr(builtins.Array, merges)];
78
+ return new Invoke(ctx.prelude.fn("sortWith"), undefined, args, undefined);
79
+ };
80
+ export const sorted = (builtins, target, into, holes, result) => {
81
+ if (target instanceof Bytes) {
82
+ target.bytes.set(Uint8Array.from(result, coerceToNumber));
83
+ return target;
84
+ }
85
+ if (into === "Array.toSorted")
86
+ return new Arr(builtins.Array, result);
87
+ changed(target);
88
+ const items = target.items;
89
+ const count = result.length - holes;
90
+ result.slice(0, count).forEach((item, index) => {
91
+ items[index] = item;
92
+ });
93
+ Array.from({ length: holes }, (_, index) => count + index).forEach((index) => {
94
+ delete items[index];
95
+ });
96
+ return target;
97
+ };
98
+ // Array constructs identically with or without new, like JS.
99
+ export const arrayGlobal = (ctx) => {
100
+ const builtins = ctx.builtins;
101
+ const proto = builtins.Array;
102
+ const wrap = (items) => new Arr(proto, items);
103
+ const construct = (args, into) => {
104
+ if (args.length !== 1)
105
+ return new Arr(into, [...args]);
106
+ const first = args[0];
107
+ if (typeof first !== "number")
108
+ return new Arr(into, [first]);
109
+ if (!Number.isInteger(first) || first < 0 || first > MAX_ARRAY_LENGTH)
110
+ throw rangeError("Invalid array length.");
111
+ // Sparse like JS: Array(3) has holes, and combinator loops already skip them.
112
+ return new Arr(into, new Array(first));
113
+ };
114
+ const array = constructor(builtins, proto, {
115
+ name: "Array",
116
+ length: 1,
117
+ call: (_, args) => construct(args, proto),
118
+ construct: (args, newTarget) => construct(args, prototypeFrom(newTarget, proto)),
119
+ });
120
+ methods(builtins, array, [
121
+ ["isArray", 1, (_, args) => args[0] instanceof Arr],
122
+ ["of", 0, (_, args) => wrap([...args])],
123
+ ["from", 1, (_, args) => arrayFrom(ctx, args)],
124
+ ]);
125
+ const self = (thisValue, name) => receiver(Arr, thisValue, `Array.prototype.${name}`);
126
+ // A mutating method fails where its first element write, delete, or `length` write would on a frozen, sealed, or
127
+ // non-extensible array. `growth` is given by the methods that always write `length`, even when it is 0; holes a
128
+ // method would fill on a non-extensible array are not checked.
129
+ const mutable = (target, growth) => {
130
+ const length = target.items.length;
131
+ if ((growth ?? 0) > 0)
132
+ rejectAddition(target, length);
133
+ if ((growth ?? 0) < 0 && length > 0 && !target.elements.configurable) {
134
+ throw typeError(`Cannot delete property '${length - 1}'.`);
135
+ }
136
+ if (!target.elements.writable && (length > 0 || growth !== undefined)) {
137
+ throw typeError(`Cannot assign to read only property '${length > 0 ? 0 : "length"}'.`);
138
+ }
139
+ changed(target);
140
+ return target;
141
+ };
142
+ const optNumber = (value) => (value === undefined ? undefined : coerceToInteger(value));
143
+ methods(builtins, proto, [
144
+ [
145
+ "join",
146
+ 1,
147
+ (thisValue, args) => {
148
+ // .map would keep holes, which the conversion would then hand to the body as undefined.
149
+ const parts = Array.from(self(thisValue, "join").items, (item) => item ?? "");
150
+ return withPrimitives("string", [args[0] === undefined ? "," : args[0], ...parts], ([separator, ...items]) => {
151
+ const joined = items.map(coerceToString).join(coerceToString(separator));
152
+ checkStringLength(joined.length);
153
+ return joined;
154
+ });
155
+ },
156
+ ],
157
+ [
158
+ "toString",
159
+ 0,
160
+ (thisValue) => withPrimitives("string", Array.from(self(thisValue, "toString").items, (item) => item ?? ""), (items) => items.map(coerceToString).join(",")),
161
+ ],
162
+ [
163
+ "includes",
164
+ 1,
165
+ (thisValue, args) => {
166
+ return self(thisValue, "includes").items.includes(args[0], optNumber(args[1]));
167
+ },
168
+ ],
169
+ ["indexOf", 1, (thisValue, args) => self(thisValue, "indexOf").items.indexOf(args[0], optNumber(args[1]))],
170
+ [
171
+ "lastIndexOf",
172
+ 1,
173
+ (thisValue, args) => {
174
+ const target = self(thisValue, "lastIndexOf").items;
175
+ // An explicit undefined is a fromIndex of 0, unlike omitting it.
176
+ return args.length < 2 ? target.lastIndexOf(args[0]) : target.lastIndexOf(args[0], optNumber(args[1]));
177
+ },
178
+ ],
179
+ ["at", 1, (thisValue, args) => self(thisValue, "at").items.at(optNumber(args[0]) ?? 0)],
180
+ [
181
+ "slice",
182
+ 2,
183
+ (thisValue, args) => wrap(self(thisValue, "slice").items.slice(optNumber(args[0]), optNumber(args[1]))),
184
+ ],
185
+ [
186
+ "concat",
187
+ 1,
188
+ (thisValue, args) => {
189
+ const joined = self(thisValue, "concat").items.concat(...args.map((item) => (item instanceof Arr ? item.items : item)));
190
+ checkArrayLength(joined.length);
191
+ return wrap(joined);
192
+ },
193
+ ],
194
+ [
195
+ "flat",
196
+ 0,
197
+ (thisValue, args) => {
198
+ const flatten = (items, depth) => items.flatMap((item) => (item instanceof Arr && depth > 0 ? flatten(item.items, depth - 1) : [item]));
199
+ const flattened = flatten(self(thisValue, "flat").items, optNumber(args[0]) ?? 1);
200
+ checkArrayLength(flattened.length);
201
+ return wrap(flattened);
202
+ },
203
+ ],
204
+ [
205
+ "reverse",
206
+ 0,
207
+ (thisValue) => {
208
+ const target = self(thisValue, "reverse");
209
+ // Fewer than two elements means no writes at all, so a frozen one-element array reverses fine.
210
+ if (target.items.length > 1)
211
+ mutable(target);
212
+ target.items.reverse();
213
+ return target;
214
+ },
215
+ ],
216
+ ["sort", 1, (thisValue, args) => sortArray(ctx, mutable(self(thisValue, "sort")), args[0], "Array.sort")],
217
+ ["toSorted", 1, (thisValue, args) => sortArray(ctx, self(thisValue, "toSorted"), args[0], "Array.toSorted")],
218
+ ["toReversed", 0, (thisValue) => wrap([...self(thisValue, "toReversed").items].reverse())],
219
+ [
220
+ "with",
221
+ 2,
222
+ (thisValue, args) => {
223
+ const target = self(thisValue, "with").items;
224
+ const index = optNumber(args[0]) ?? 0;
225
+ const resolved = index < 0 ? target.length + index : index;
226
+ if (resolved < 0 || resolved >= target.length)
227
+ throw rangeError("Array.with index is out of range.");
228
+ const copied = [...target];
229
+ copied[resolved] = args[1];
230
+ return wrap(copied);
231
+ },
232
+ ],
233
+ [
234
+ "push",
235
+ 1,
236
+ (thisValue, args) => {
237
+ const target = mutable(self(thisValue, "push"), args.length);
238
+ // Validate all insertions before mutating to avoid partial cyclic updates.
239
+ for (const item of args)
240
+ rejectCircularInsertion(target, item, "Array.push result");
241
+ return target.items.push(...args);
242
+ },
243
+ ],
244
+ [
245
+ "unshift",
246
+ 1,
247
+ (thisValue, args) => {
248
+ const target = mutable(self(thisValue, "unshift"), args.length);
249
+ for (const item of args)
250
+ rejectCircularInsertion(target, item, "Array.unshift result");
251
+ return target.items.unshift(...args);
252
+ },
253
+ ],
254
+ ["pop", 0, (thisValue) => mutable(self(thisValue, "pop"), -1).items.pop()],
255
+ ["shift", 0, (thisValue) => mutable(self(thisValue, "shift"), -1).items.shift()],
256
+ [
257
+ "splice",
258
+ 2,
259
+ (thisValue, args) => {
260
+ const target = self(thisValue, "splice");
261
+ const length = target.items.length;
262
+ const start = optNumber(args[0]) ?? 0;
263
+ const from = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
264
+ const deleteCount = args.length === 1 ? length - from : Math.min(Math.max(optNumber(args[1]) ?? 0, 0), length - from);
265
+ const inserted = args.slice(2);
266
+ for (const item of inserted)
267
+ rejectCircularInsertion(target, item, "Array.splice result");
268
+ mutable(target, inserted.length - deleteCount);
269
+ return wrap(target.items.splice(from, deleteCount, ...inserted));
270
+ },
271
+ ],
272
+ [
273
+ "toSpliced",
274
+ 2,
275
+ (thisValue, args) => {
276
+ const copied = [...self(thisValue, "toSpliced").items];
277
+ if (args.length === 0)
278
+ return wrap(copied);
279
+ const start = optNumber(args[0]) ?? 0;
280
+ if (args.length === 1)
281
+ copied.splice(start);
282
+ else
283
+ copied.splice(start, optNumber(args[1]) ?? 0, ...args.slice(2));
284
+ return wrap(copied);
285
+ },
286
+ ],
287
+ [
288
+ "fill",
289
+ 1,
290
+ (thisValue, args) => {
291
+ const target = mutable(self(thisValue, "fill"));
292
+ rejectCircularInsertion(target, args[0], "Array.fill result");
293
+ target.items.fill(args[0], optNumber(args[1]), optNumber(args[2]));
294
+ return target;
295
+ },
296
+ ],
297
+ [
298
+ "copyWithin",
299
+ 2,
300
+ (thisValue, args) => {
301
+ const target = mutable(self(thisValue, "copyWithin"));
302
+ target.items.copyWithin(optNumber(args[0]) ?? 0, optNumber(args[1]) ?? 0, optNumber(args[2]));
303
+ return target;
304
+ },
305
+ ],
306
+ ...iteratorMethods(builtins, self),
307
+ // The callback methods are the prelude's.
308
+ ]);
309
+ define(proto, IteratorSymbol, get(proto, "values"), hidden);
310
+ return array;
311
+ };
@@ -0,0 +1,11 @@
1
+ import { Obj, type Value } from "../runtime/objects.js";
2
+ import type { Interpreter } from "../runtime/interpreter.js";
3
+ export declare const finishBytes: (bytes: Uint8Array, into: Obj, offset: number) => Value;
4
+ export declare const uint8ArrayGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
5
+ export declare const textEncoderGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
6
+ /** A `TextDecoder` holding the host decoder its label and options configured. */
7
+ export declare class TextDecoderObj extends Obj {
8
+ readonly decoder: TextDecoder;
9
+ constructor(proto: Obj, decoder: TextDecoder);
10
+ }
11
+ export declare const textDecoderGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -0,0 +1,222 @@
1
+ import { Invoke } from "../runtime/signals.js";
2
+ import { checkArrayLength, checkStringLength } from "../runtime/limits.js";
3
+ import { constructor, methods, prototypeFrom, receiver, requiresNew, iteratorMethods } from "../runtime/native.js";
4
+ import { IteratorSymbol, rangeError, syntaxError, typeError } from "../runtime/model.js";
5
+ import { define, defineAccessor, get, hidden, Bytes, Obj, coerceToInteger, coerceToNumber, coerceToString, } from "../runtime/objects.js";
6
+ import { describeValue } from "../runtime/references.js";
7
+ import { requireCallback } from "../runtime/callback.js";
8
+ import { sortArray } from "./array.js";
9
+ /**
10
+ * The bytes a Uint8Array, array, or other iterable of numbers describes, read in the prelude: a new Uint8Array with
11
+ * prototype `into`, or set into the Uint8Array `into` at `offset`. The host array clamps each value.
12
+ */
13
+ const collectBytes = (ctx, source, name, into, offset, mapper, thisArg) => {
14
+ const callback = mapper === undefined ? undefined : requireCallback(mapper, name);
15
+ if (source instanceof Bytes && callback === undefined)
16
+ return finishBytes(new Uint8Array(source.bytes), into, offset);
17
+ return new Invoke(ctx.prelude.fn("collectBytes"), undefined, [source, name, callback, thisArg, into, offset], undefined);
18
+ };
19
+ export const finishBytes = (bytes, into, offset) => {
20
+ if (!(into instanceof Bytes))
21
+ return new Bytes(into, bytes);
22
+ if (!Number.isInteger(offset) || offset < 0 || bytes.length + offset > into.bytes.length) {
23
+ throw rangeError("Uint8Array.set: the source does not fit at that offset.");
24
+ }
25
+ into.bytes.set(bytes, offset);
26
+ return undefined;
27
+ };
28
+ const constructBytes = (ctx, args, proto) => {
29
+ const source = args[0];
30
+ if (source !== null && typeof source === "object")
31
+ return collectBytes(ctx, source, "new Uint8Array(...)", proto, 0);
32
+ const length = source === undefined ? 0 : coerceToNumber(source);
33
+ if (!Number.isInteger(length) || length < 0)
34
+ throw rangeError(`Invalid typed array length: ${coerceToString(source)}`);
35
+ checkArrayLength(length);
36
+ return new Bytes(proto, new Uint8Array(length));
37
+ };
38
+ export const uint8ArrayGlobal = (ctx) => {
39
+ const builtins = ctx.builtins;
40
+ const proto = builtins.Uint8Array;
41
+ const wrap = (bytes) => new Bytes(proto, bytes);
42
+ const uint8Array = constructor(builtins, proto, {
43
+ name: "Uint8Array",
44
+ length: 3,
45
+ call: requiresNew("Uint8Array"),
46
+ construct: (args, newTarget) => constructBytes(ctx, args, prototypeFrom(newTarget, proto)),
47
+ });
48
+ const decode = (name, args, from) => {
49
+ if (typeof args[0] !== "string")
50
+ throw typeError(`Uint8Array.${name} expects a string.`);
51
+ try {
52
+ return wrap(from(args[0]));
53
+ }
54
+ catch {
55
+ throw syntaxError(`Uint8Array.${name}: the string is not valid ${name === "fromHex" ? "hex" : "base64"}.`);
56
+ }
57
+ };
58
+ methods(builtins, uint8Array, [
59
+ ["from", 1, (_, args) => collectBytes(ctx, args[0], "Uint8Array.from", proto, 0, args[1], args[2])],
60
+ ["of", 0, (_, args) => wrap(Uint8Array.from(args, coerceToNumber))],
61
+ ["fromBase64", 1, (_, args) => decode("fromBase64", args, (text) => Uint8Array.fromBase64(text))],
62
+ ["fromHex", 1, (_, args) => decode("fromHex", args, (text) => Uint8Array.fromHex(text))],
63
+ ]);
64
+ const self = (thisValue, name) => receiver(Bytes, thisValue, `Uint8Array.prototype.${name}`);
65
+ const optNumber = (value) => (value === undefined ? undefined : coerceToInteger(value));
66
+ // Uint8Array cannot contain NaN, so non-number search values never match a byte.
67
+ const search = (value) => (typeof value === "number" ? value : NaN);
68
+ defineAccessor(proto, "length", (thisValue) => self(thisValue, "length").bytes.length);
69
+ methods(builtins, proto, [
70
+ ["at", 1, (thisValue, args) => self(thisValue, "at").bytes.at(optNumber(args[0]) ?? 0)],
71
+ [
72
+ "slice",
73
+ 2,
74
+ (thisValue, args) => wrap(self(thisValue, "slice").bytes.slice(optNumber(args[0]), optNumber(args[1]))),
75
+ ],
76
+ // A view on the same bytes, as in JS: writes through one are visible through the other.
77
+ [
78
+ "subarray",
79
+ 2,
80
+ (thisValue, args) => wrap(self(thisValue, "subarray").bytes.subarray(optNumber(args[0]), optNumber(args[1]))),
81
+ ],
82
+ [
83
+ "set",
84
+ 1,
85
+ (thisValue, args) => {
86
+ const target = self(thisValue, "set");
87
+ return collectBytes(ctx, args[0], "Uint8Array.set", target, optNumber(args[1]) ?? 0);
88
+ },
89
+ ],
90
+ [
91
+ "fill",
92
+ 1,
93
+ (thisValue, args) => {
94
+ const target = self(thisValue, "fill");
95
+ target.bytes.fill(coerceToNumber(args[0]), optNumber(args[1]), optNumber(args[2]));
96
+ return target;
97
+ },
98
+ ],
99
+ [
100
+ "reverse",
101
+ 0,
102
+ (thisValue) => {
103
+ const target = self(thisValue, "reverse");
104
+ target.bytes.reverse();
105
+ return target;
106
+ },
107
+ ],
108
+ [
109
+ "sort",
110
+ 1,
111
+ (thisValue, args) => {
112
+ const target = self(thisValue, "sort");
113
+ // Without a comparator, typed arrays sort numerically rather than by string.
114
+ if (args[0] === undefined) {
115
+ target.bytes.sort();
116
+ return target;
117
+ }
118
+ return sortArray(ctx, target, args[0], "Uint8Array.sort");
119
+ },
120
+ ],
121
+ ["indexOf", 1, (thisValue, args) => self(thisValue, "indexOf").bytes.indexOf(search(args[0]), optNumber(args[1]))],
122
+ [
123
+ "lastIndexOf",
124
+ 1,
125
+ (thisValue, args) => {
126
+ const target = self(thisValue, "lastIndexOf").bytes;
127
+ return args.length < 2
128
+ ? target.lastIndexOf(search(args[0]))
129
+ : target.lastIndexOf(search(args[0]), optNumber(args[1]));
130
+ },
131
+ ],
132
+ [
133
+ "includes",
134
+ 1,
135
+ (thisValue, args) => self(thisValue, "includes").bytes.includes(search(args[0]), optNumber(args[1])),
136
+ ],
137
+ [
138
+ "join",
139
+ 1,
140
+ (thisValue, args) => {
141
+ const joined = self(thisValue, "join").bytes.join(args[0] === undefined ? "," : coerceToString(args[0]));
142
+ checkStringLength(joined.length);
143
+ return joined;
144
+ },
145
+ ],
146
+ ["toString", 0, (thisValue) => self(thisValue, "toString").bytes.join(",")],
147
+ ["toBase64", 0, (thisValue) => self(thisValue, "toBase64").bytes.toBase64()],
148
+ ["toHex", 0, (thisValue) => self(thisValue, "toHex").bytes.toHex()],
149
+ ...iteratorMethods(builtins, self),
150
+ // The callback methods are the prelude's.
151
+ ]);
152
+ define(proto, IteratorSymbol, get(proto, "values"), hidden);
153
+ return uint8Array;
154
+ };
155
+ export const textEncoderGlobal = (ctx) => {
156
+ const builtins = ctx.builtins;
157
+ const proto = builtins.TextEncoder;
158
+ const encoder = new TextEncoder();
159
+ defineAccessor(proto, "encoding", () => "utf-8");
160
+ methods(builtins, proto, [
161
+ [
162
+ "encode",
163
+ 0,
164
+ (_, args) => new Bytes(builtins.Uint8Array, encoder.encode(coerceToString(args[0] === undefined ? "" : args[0]))),
165
+ ],
166
+ ]);
167
+ return constructor(builtins, proto, {
168
+ name: "TextEncoder",
169
+ call: requiresNew("TextEncoder"),
170
+ construct: (_, newTarget) => new Obj(prototypeFrom(newTarget, proto)),
171
+ });
172
+ };
173
+ /** A `TextDecoder` holding the host decoder its label and options configured. */
174
+ export class TextDecoderObj extends Obj {
175
+ decoder;
176
+ constructor(proto, decoder) {
177
+ super(proto);
178
+ this.decoder = decoder;
179
+ }
180
+ }
181
+ // The WHATWG labels for UTF-8, the only encoding CodeMode decodes.
182
+ const utf8Labels = new Set(["unicode-1-1-utf-8", "unicode11utf8", "unicode20utf8", "utf-8", "utf8", "x-unicode20utf8"]);
183
+ export const textDecoderGlobal = (ctx) => {
184
+ const builtins = ctx.builtins;
185
+ const proto = builtins.TextDecoder;
186
+ const self = (thisValue, name) => receiver(TextDecoderObj, thisValue, `TextDecoder.prototype.${name}`);
187
+ defineAccessor(proto, "encoding", (thisValue) => self(thisValue, "encoding").decoder.encoding);
188
+ defineAccessor(proto, "fatal", (thisValue) => self(thisValue, "fatal").decoder.fatal);
189
+ defineAccessor(proto, "ignoreBOM", (thisValue) => self(thisValue, "ignoreBOM").decoder.ignoreBOM);
190
+ methods(builtins, proto, [
191
+ [
192
+ "decode",
193
+ 0,
194
+ (thisValue, args) => {
195
+ const decoder = self(thisValue, "decode").decoder;
196
+ if (args[0] === undefined)
197
+ return "";
198
+ if (!(args[0] instanceof Bytes)) {
199
+ throw typeError(`TextDecoder.decode expects a Uint8Array, received ${describeValue(args[0])}.`);
200
+ }
201
+ try {
202
+ return decoder.decode(args[0].bytes);
203
+ }
204
+ catch {
205
+ throw typeError(`TextDecoder.decode: the input is not valid ${decoder.encoding}.`);
206
+ }
207
+ },
208
+ ],
209
+ ]);
210
+ return constructor(builtins, proto, {
211
+ name: "TextDecoder",
212
+ call: requiresNew("TextDecoder"),
213
+ construct: (args, newTarget) => {
214
+ const label = args[0] === undefined ? "utf-8" : coerceToString(args[0]).trim().toLowerCase();
215
+ if (!utf8Labels.has(label))
216
+ throw rangeError(`The "${label}" encoding is not supported; only UTF-8 is.`);
217
+ const options = args[1] instanceof Obj ? args[1] : undefined;
218
+ const flag = (name) => options !== undefined && Boolean(get(options, name));
219
+ return new TextDecoderObj(prototypeFrom(newTarget, proto), new TextDecoder("utf-8", { fatal: flag("fatal"), ignoreBOM: flag("ignoreBOM") }));
220
+ },
221
+ });
222
+ };
@@ -0,0 +1,7 @@
1
+ import { Obj, type Value } from "../runtime/objects.js";
2
+ import type { Interpreter } from "../runtime/interpreter.js";
3
+ export declare const mapGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
4
+ export declare const setGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
5
+ export declare const weakKey: (value: Value, label: string) => Obj;
6
+ export declare const weakMapGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
7
+ export declare const weakSetGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;