@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,272 @@
1
+ import { Invoke } from "../runtime/signals.js";
2
+ import { constructor, fn, methods } from "../runtime/native.js";
3
+ import { checkArrayLength, checkStringLength } from "../runtime/limits.js";
4
+ import { invalidData, IteratorSymbol, rangeError, typeError } from "../runtime/model.js";
5
+ import { define, get, hidden, Arr, positionIterator, Obj, RegExpObj, record, coerceToInteger, coerceToNumber, coerceToString, } from "../runtime/objects.js";
6
+ import { containsOpaqueReference, typeofValue } from "../runtime/references.js";
7
+ import { isSupportedCallback, requireCallback, withPrimitives } from "../runtime/callback.js";
8
+ import { matchToValue, withHostRegex } from "./regexp.js";
9
+ import { coerce } from "./value.js";
10
+ // console is intercepted by the interpreter before reaching here.
11
+ const requireDataArgument = (name, index, arg) => {
12
+ if (containsOpaqueReference(arg)) {
13
+ throw invalidData(`String.${name} expects argument ${index + 1} to be a data value.`);
14
+ }
15
+ return arg;
16
+ };
17
+ const replaceAllNeedsGlobal = (pattern) => {
18
+ if (!pattern.global) {
19
+ throw typeError(`String.replaceAll requires a regular expression with the global (g) flag: write /${pattern.source}/${pattern.flags}g, or use String.replace to replace only the first match.`);
20
+ }
21
+ };
22
+ // The matches are found first, as the host replaces; then the callback runs for each in order.
23
+ const replaceWithCallback = (ctx, value, name, args) => {
24
+ const builtins = ctx.builtins;
25
+ const callback = requireCallback(args[1], `String.${name}`);
26
+ const matches = [];
27
+ // The host calls back with (match, ...captures, offset, string, groups?); only groups is not already a Value.
28
+ const collect = (...callbackArgs) => {
29
+ const match = callbackArgs[0];
30
+ const hasGroups = typeof callbackArgs.at(-1) === "object";
31
+ const offset = callbackArgs[callbackArgs.length - (hasGroups ? 3 : 2)];
32
+ if (typeof match !== "string" || typeof offset !== "number") {
33
+ throw typeError(`String.${name} produced an invalid replacement match.`);
34
+ }
35
+ const args = callbackArgs.map((arg) => (typeof arg === "object" ? record(builtins.Object, arg) : arg));
36
+ matches.push({ match, offset, args });
37
+ return match;
38
+ };
39
+ const pattern = args[0];
40
+ if (pattern instanceof RegExpObj) {
41
+ pattern.use((regex) => {
42
+ if (name === "replaceAll")
43
+ replaceAllNeedsGlobal(regex);
44
+ if (name === "replace")
45
+ value.replace(regex, collect);
46
+ else
47
+ value.replaceAll(regex, collect);
48
+ });
49
+ }
50
+ else {
51
+ const search = coerceToString(requireDataArgument(name, 0, pattern));
52
+ if (name === "replace")
53
+ value.replace(search, collect);
54
+ else
55
+ value.replaceAll(search, collect);
56
+ }
57
+ const pieces = matches.map((match, index) => new Arr(builtins.Array, [
58
+ value.slice(index === 0 ? 0 : matches[index - 1].offset + matches[index - 1].match.length, match.offset),
59
+ new Arr(builtins.Array, match.args),
60
+ ]));
61
+ const last = matches.at(-1);
62
+ const rest = value.slice(last === undefined ? 0 : last.offset + last.match.length);
63
+ return new Invoke(ctx.prelude.fn("replaceWith"), undefined, [new Arr(builtins.Array, pieces), rest, callback], undefined);
64
+ };
65
+ export const stringGlobal = (ctx) => {
66
+ const builtins = ctx.builtins;
67
+ const string = constructor(builtins, builtins.String, {
68
+ name: "String",
69
+ length: 1,
70
+ call: (_, args) => coerce(ctx, "String", args),
71
+ });
72
+ const codeUnits = (name, op) => [
73
+ name,
74
+ 1,
75
+ (_, args) => op(...args.map(coerceToNumber)),
76
+ ];
77
+ methods(builtins, string, [
78
+ codeUnits("fromCharCode", String.fromCharCode),
79
+ codeUnits("fromCodePoint", String.fromCodePoint),
80
+ [
81
+ "raw",
82
+ 1,
83
+ (_, args) => {
84
+ const template = args[0];
85
+ const raw = template instanceof Obj ? get(template, "raw") : undefined;
86
+ if (!(raw instanceof Obj))
87
+ throw typeError("String.raw expects a template object with a raw array.");
88
+ const count = Math.max(0, coerceToInteger(get(raw, "length")));
89
+ checkArrayLength(count);
90
+ // Each literal is followed by its substitution, except the last literal, or when substitutions run out.
91
+ const parts = Array.from({ length: count }, (_, index) => index + 1 < count && index + 1 < args.length ? [get(raw, index), args[index + 1]] : [get(raw, index)]).flat();
92
+ return withPrimitives("string", parts, (strings) => {
93
+ const output = strings.map(coerceToString).join("");
94
+ checkStringLength(output.length);
95
+ return output;
96
+ }, true);
97
+ },
98
+ ],
99
+ ]);
100
+ const self = (thisValue, name) => {
101
+ if (typeof thisValue === "string")
102
+ return thisValue;
103
+ if (thisValue === null || thisValue === undefined) {
104
+ throw typeError(`String.prototype.${name} called on null or undefined.`);
105
+ }
106
+ return coerceToString(thisValue);
107
+ };
108
+ // Coerce arguments like native JS; opaque runtime references still reject.
109
+ const str = (name, args, index) => coerceToString(requireDataArgument(name, index, args[index]));
110
+ const num = (name, args, index) => coerceToNumber(requireDataArgument(name, index, args[index]));
111
+ const optNum = (name, args, index) => args[index] === undefined ? undefined : num(name, args, index);
112
+ const optStr = (name, args, index) => args[index] === undefined ? undefined : str(name, args, index);
113
+ // ToPrimitive in spec order: the receiver, then the arguments the method consumes, one hint per position; the
114
+ // rest pass through as they are.
115
+ const simple = (name, length, op, hints = []) => [
116
+ name,
117
+ length,
118
+ (thisValue, args) => {
119
+ if (thisValue === null || thisValue === undefined) {
120
+ throw typeError(`String.prototype.${name} called on null or undefined.`);
121
+ }
122
+ return withPrimitives(["string", ...hints], [thisValue, ...args.slice(0, hints.length)], ([value, ...primitives]) => op(coerceToString(value), [...primitives, ...args.slice(hints.length)]));
123
+ },
124
+ ];
125
+ // includes, startsWith, and endsWith reject a RegExp before converting their search string and position.
126
+ const searching = (name, op) => simple(name, 1, (value, args) => {
127
+ if (args[0] instanceof RegExpObj) {
128
+ throw typeError(`String.${name} cannot take a regular expression; use regex.test(string) or String.search instead.`);
129
+ }
130
+ return withPrimitives(["string", "number"], args.slice(0, 2), (primitives) => op(value, str(name, primitives, 0), optNum(name, primitives, 1)));
131
+ });
132
+ // match, matchAll, and search read a RegExp as is and convert anything else to its pattern text.
133
+ const withPattern = (args, op) => args[0] instanceof RegExpObj ? op(args[0]) : withPrimitives("string", [args[0]], ([text]) => op(text));
134
+ const replace = (name) => simple(name, 2, (value, args) => {
135
+ const pattern = args[0];
136
+ const replacer = args[1];
137
+ // A RegExp pattern is used as is; a plain one converts to its search string, then a non-callable replacement.
138
+ return withPrimitives("string", [pattern instanceof RegExpObj ? undefined : pattern, isSupportedCallback(replacer) ? undefined : replacer], ([search, replacement]) => {
139
+ if (isSupportedCallback(replacer)) {
140
+ return replaceWithCallback(ctx, value, name, [pattern instanceof RegExpObj ? pattern : search, replacer]);
141
+ }
142
+ if (typeofValue(replacer) === "function") {
143
+ throw typeError(`String.${name} cannot use this callable as a replacer; wrap it in an arrow function, e.g. (match) => tools.ns.tool(match).`);
144
+ }
145
+ const primitives = [search, replacement];
146
+ if (pattern instanceof RegExpObj) {
147
+ const text = str(name, primitives, 1);
148
+ return pattern.use((regex) => {
149
+ if (name === "replaceAll")
150
+ replaceAllNeedsGlobal(regex);
151
+ return name === "replace" ? value.replace(regex, text) : value.replaceAll(regex, text);
152
+ });
153
+ }
154
+ if (name === "replace")
155
+ return value.replace(str(name, primitives, 0), str(name, primitives, 1));
156
+ return value.replaceAll(str(name, primitives, 0), str(name, primitives, 1));
157
+ });
158
+ });
159
+ methods(builtins, builtins.String, [
160
+ simple("toString", 0, (value) => value),
161
+ simple("valueOf", 0, (value) => value),
162
+ simple("toLowerCase", 0, (value) => value.toLowerCase()),
163
+ simple("toUpperCase", 0, (value) => value.toUpperCase()),
164
+ simple("toLocaleLowerCase", 0, (value) => value.toLowerCase()),
165
+ simple("toLocaleUpperCase", 0, (value) => value.toUpperCase()),
166
+ simple("trim", 0, (value) => value.trim()),
167
+ simple("trimStart", 0, (value) => value.trimStart()),
168
+ simple("trimLeft", 0, (value) => value.trimStart()),
169
+ simple("trimEnd", 0, (value) => value.trimEnd()),
170
+ simple("trimRight", 0, (value) => value.trimEnd()),
171
+ // Locale/options are deliberately unsupported; comparison uses the host default locale.
172
+ simple("localeCompare", 1, (value, args) => value.localeCompare(str("localeCompare", args, 0)), ["string"]),
173
+ simple("normalize", 0, (value, args) => {
174
+ const form = optStr("normalize", args, 0);
175
+ try {
176
+ return value.normalize(form);
177
+ }
178
+ catch {
179
+ throw rangeError(`String.normalize expects the form "NFC", "NFD", "NFKC", or "NFKD" (got ${JSON.stringify(form)}).`);
180
+ }
181
+ }, ["string"]),
182
+ simple("split", 2, (value, args) => {
183
+ const separator = args[0];
184
+ // A RegExp separator is used as is; the limit converts before a plain separator does, as in the spec.
185
+ return withPrimitives(["number", "string"], [args[1], separator instanceof RegExpObj ? undefined : separator], ([limit, pattern]) => {
186
+ const wrap = (parts) => new Arr(builtins.Array, parts);
187
+ // Native: an undefined separator returns the whole string, not a split on "undefined",
188
+ // unless the limit truncates to zero.
189
+ const requestedLimit = args[1] === undefined ? undefined : num("split", [pattern, limit], 1);
190
+ if (separator === undefined) {
191
+ return wrap(requestedLimit !== undefined && requestedLimit >>> 0 === 0 ? [] : [value]);
192
+ }
193
+ const parts = separator instanceof RegExpObj
194
+ ? separator.use((regex) => value.split(regex, requestedLimit))
195
+ : value.split(str("split", [pattern], 0), requestedLimit === undefined ? undefined : requestedLimit >>> 0);
196
+ checkArrayLength(parts.length);
197
+ return wrap(parts);
198
+ });
199
+ }),
200
+ simple("slice", 2, (value, args) => value.slice(optNum("slice", args, 0), optNum("slice", args, 1)), [
201
+ "number",
202
+ "number",
203
+ ]),
204
+ searching("includes", (value, search, position) => value.includes(search, position)),
205
+ searching("startsWith", (value, search, position) => value.startsWith(search, position)),
206
+ searching("endsWith", (value, search, position) => value.endsWith(search, position)),
207
+ simple("indexOf", 1, (value, args) => value.indexOf(str("indexOf", args, 0), optNum("indexOf", args, 1)), [
208
+ "string",
209
+ "number",
210
+ ]),
211
+ simple("lastIndexOf", 1, (value, args) => value.lastIndexOf(str("lastIndexOf", args, 0), optNum("lastIndexOf", args, 1)), ["string", "number"]),
212
+ replace("replace"),
213
+ replace("replaceAll"),
214
+ simple("match", 1, (value, args) => withPattern(args, (arg) => withHostRegex(arg, "match", "", (regex) => {
215
+ const matched = value.match(regex);
216
+ if (matched === null)
217
+ return null;
218
+ // Preserve the own `index` and `groups` properties on non-global matches.
219
+ if (regex.global)
220
+ return new Arr(builtins.Array, [...matched]);
221
+ return matchToValue(builtins, matched);
222
+ }))),
223
+ simple("matchAll", 1, (value, args) => withPattern(args, (arg) => withHostRegex(arg, "matchAll", "g", (regex) => {
224
+ if (!regex.global) {
225
+ throw typeError(`String.matchAll requires a regular expression with the global (g) flag: write /${regex.source}/${regex.flags}g, or use String.match for a single match.`);
226
+ }
227
+ const matches = [];
228
+ for (const match of value.matchAll(regex)) {
229
+ checkArrayLength(matches.length + 1);
230
+ matches.push(matchToValue(builtins, match));
231
+ }
232
+ return new Arr(builtins.Array, matches);
233
+ }))),
234
+ simple("search", 1, (value, args) => withPattern(args, (arg) => withHostRegex(arg, "search", "", (regex) => value.search(regex)))),
235
+ simple("repeat", 1, (value, args) => {
236
+ const count = num("repeat", args, 0);
237
+ if (!Number.isFinite(count) || count < 0) {
238
+ throw rangeError("String.repeat expects a finite non-negative count.");
239
+ }
240
+ checkStringLength(value.length * count);
241
+ return value.repeat(count);
242
+ }, ["number"]),
243
+ simple("padStart", 1, (value, args) => {
244
+ const length = num("padStart", args, 0);
245
+ checkStringLength(length);
246
+ return value.padStart(length, optStr("padStart", args, 1));
247
+ }, ["number", "string"]),
248
+ simple("padEnd", 1, (value, args) => {
249
+ const length = num("padEnd", args, 0);
250
+ checkStringLength(length);
251
+ return value.padEnd(length, optStr("padEnd", args, 1));
252
+ }, ["number", "string"]),
253
+ simple("charAt", 1, (value, args) => value.charAt(optNum("charAt", args, 0) ?? 0), ["number"]),
254
+ simple("at", 1, (value, args) => value.at(optNum("at", args, 0) ?? 0), ["number"]),
255
+ simple("substring", 2, (value, args) => value.substring(optNum("substring", args, 0) ?? 0, optNum("substring", args, 1)), ["number", "number"]),
256
+ simple("substr", 2, (value, args) => value.substr(optNum("substr", args, 0) ?? 0, optNum("substr", args, 1)), [
257
+ "number",
258
+ "number",
259
+ ]),
260
+ simple("isWellFormed", 0, (value) => value.isWellFormed()),
261
+ simple("toWellFormed", 0, (value) => value.toWellFormed()),
262
+ simple("charCodeAt", 1, (value, args) => value.charCodeAt(optNum("charCodeAt", args, 0) ?? 0), ["number"]),
263
+ simple("codePointAt", 1, (value, args) => value.codePointAt(optNum("codePointAt", args, 0) ?? 0), ["number"]),
264
+ simple("concat", 1, (value, args) => withPrimitives("string", args, (parts) => {
265
+ const joined = value.concat(...parts.map((_, index) => str("concat", parts, index)));
266
+ checkStringLength(joined.length);
267
+ return joined;
268
+ })),
269
+ ]);
270
+ define(builtins.String, IteratorSymbol, fn(builtins, "[Symbol.iterator]", 0, (thisValue) => positionIterator(builtins, self(thisValue, "[Symbol.iterator]"), "values")), hidden);
271
+ return string;
272
+ };
@@ -0,0 +1,25 @@
1
+ import { Invoke } from "../runtime/signals.js";
2
+ import { Obj, type Callable, type Value } from "../runtime/objects.js";
3
+ import type { Interpreter } from "../runtime/interpreter.js";
4
+ type UriFunction = "encodeURI" | "encodeURIComponent" | "decodeURI" | "decodeURIComponent";
5
+ export declare const uriGlobal: <R>(ctx: Interpreter<R>, name: UriFunction) => import("../runtime/objects.js").Native;
6
+ export declare const urlGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
7
+ /** What `readPairs` builds from `[name, value]` pairs, or from a record of names to values when `init` is no iterable. */
8
+ export type PairsInto = {
9
+ readonly kind: "Headers" | "URLSearchParams";
10
+ readonly proto: Obj;
11
+ };
12
+ /**
13
+ * Reads a synchronous iterable of `[name, value]` pairs as strings (in the prelude), then builds `into` from them; a
14
+ * record of names to values when `init` is not iterable. As in WebIDL, the whole sequence is converted before any
15
+ * pair's length is checked.
16
+ */
17
+ export declare const readPairs: <R>(ctx: Interpreter<R>, init: Value, label: string, into: PairsInto) => Invoke;
18
+ /** What `readPairs` makes of the pairs it read (an array of arrays of strings), or of a record. */
19
+ export declare const buildPairs: (into: PairsInto, value: Value, label: string) => Value;
20
+ /** The host validates header names and values and throws its own TypeError; the program gets one of its own. */
21
+ export declare const attempt: <T>(run: () => T) => T;
22
+ /** Headers and URLSearchParams `forEach`: the callback sees each `[name, value]` pair as listed when it started. */
23
+ export declare const pairsForEach: <R>(ctx: Interpreter<R>, target: Value, pairs: Array<[string, string]>, callback: Callable, thisArg: Value) => Invoke;
24
+ export declare const urlSearchParamsGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
25
+ export {};
@@ -0,0 +1,255 @@
1
+ import { Invoke } from "../runtime/signals.js";
2
+ import { constructor, fn, methods, prototypeFrom, receiver, requiresNew, iteratorMethods, } from "../runtime/native.js";
3
+ import { IteratorSymbol, PendingThrow, typeError, uriError } from "../runtime/model.js";
4
+ import { define, defineAccessor, entries, get, hidden, Arr, Obj, URLObj, URLSearchParamsObj, HeadersObj, coerceToString, isRuntimeReference, } from "../runtime/objects.js";
5
+ import { requireCallback } from "../runtime/callback.js";
6
+ const urlProperties = [
7
+ "href",
8
+ "origin",
9
+ "protocol",
10
+ "username",
11
+ "password",
12
+ "host",
13
+ "hostname",
14
+ "port",
15
+ "pathname",
16
+ "search",
17
+ "hash",
18
+ ];
19
+ const uriFunctions = {
20
+ encodeURI,
21
+ encodeURIComponent,
22
+ decodeURI,
23
+ decodeURIComponent,
24
+ };
25
+ export const uriGlobal = (ctx, name) => fn(ctx.builtins, name, 1, (_, args) => {
26
+ const value = coerceToString(args[0]);
27
+ try {
28
+ return uriFunctions[name](value);
29
+ }
30
+ catch (error) {
31
+ throw uriError(`${name} received malformed URI data: ${error instanceof Error ? error.message : String(error)}`);
32
+ }
33
+ });
34
+ const urlArgument = (value) => (value instanceof URLObj ? value.url.href : coerceToString(value));
35
+ export const urlGlobal = (ctx) => {
36
+ const builtins = ctx.builtins;
37
+ const proto = builtins.URL;
38
+ const construct = (args, into) => {
39
+ if (args.length === 0) {
40
+ throw typeError("new URL(...) requires a URL string and an optional base URL.");
41
+ }
42
+ const input = urlArgument(args[0]);
43
+ const base = args[1] === undefined ? undefined : urlArgument(args[1]);
44
+ try {
45
+ return new URLObj(into, builtins.URLSearchParams, new URL(input, base));
46
+ }
47
+ catch {
48
+ throw typeError(`new URL(...) received an invalid URL${base === undefined ? "" : " or base URL"}.`);
49
+ }
50
+ };
51
+ const url = constructor(builtins, proto, {
52
+ name: "URL",
53
+ length: 1,
54
+ call: requiresNew("URL"),
55
+ construct: (args, newTarget) => construct(args, prototypeFrom(newTarget, proto)),
56
+ });
57
+ const parse = (name) => [
58
+ name,
59
+ 1,
60
+ (_, args) => {
61
+ if (args.length === 0)
62
+ throw typeError(`URL.${name} requires a URL argument.`);
63
+ const input = urlArgument(args[0]);
64
+ const base = args[1] === undefined ? undefined : urlArgument(args[1]);
65
+ try {
66
+ const parsed = new URL(input, base);
67
+ return name === "canParse" ? true : new URLObj(proto, builtins.URLSearchParams, parsed);
68
+ }
69
+ catch {
70
+ return name === "canParse" ? false : null;
71
+ }
72
+ },
73
+ ];
74
+ methods(builtins, url, [parse("canParse"), parse("parse")]);
75
+ const self = (thisValue, name) => receiver(URLObj, thisValue, `URL.prototype.${name}`);
76
+ for (const name of urlProperties) {
77
+ defineAccessor(proto, name, (thisValue) => self(thisValue, name).url[name], name === "origin"
78
+ ? undefined
79
+ : (thisValue, value) => {
80
+ const target = self(thisValue, name);
81
+ try {
82
+ target.url[name] = coerceToString(value);
83
+ }
84
+ catch (error) {
85
+ if (error instanceof PendingThrow)
86
+ throw error;
87
+ throw typeError(`URL.${name} received an invalid value.`);
88
+ }
89
+ });
90
+ }
91
+ defineAccessor(proto, "searchParams", (thisValue) => self(thisValue, "searchParams").searchParams);
92
+ methods(builtins, proto, [
93
+ ["toString", 0, (thisValue) => self(thisValue, "toString").url.href],
94
+ ["toJSON", 0, (thisValue) => self(thisValue, "toJSON").url.href],
95
+ ]);
96
+ return url;
97
+ };
98
+ /**
99
+ * Reads a synchronous iterable of `[name, value]` pairs as strings (in the prelude), then builds `into` from them; a
100
+ * record of names to values when `init` is not iterable. As in WebIDL, the whole sequence is converted before any
101
+ * pair's length is checked.
102
+ */
103
+ export const readPairs = (ctx, init, label, into) => new Invoke(ctx.prelude.fn("readPairs"), undefined, [init, label, into.kind, into.proto], undefined);
104
+ /** What `readPairs` makes of the pairs it read (an array of arrays of strings), or of a record. */
105
+ export const buildPairs = (into, value, label) => {
106
+ if (!(value instanceof Arr))
107
+ return fromRecord(into, value);
108
+ const pairs = value.items.map((pair) => pair.items);
109
+ if (pairs.some((entry) => entry.length !== 2))
110
+ throw typeError(`${label} expects iterable [name, value] pairs.`);
111
+ if (into.kind === "URLSearchParams") {
112
+ return new URLSearchParamsObj(into.proto, new URLSearchParams(pairs));
113
+ }
114
+ return new HeadersObj(into.proto, attempt(() => new Headers(pairs)));
115
+ };
116
+ const fromRecord = (into, init) => {
117
+ if (into.kind === "Headers") {
118
+ if (!(init instanceof Obj) || isRuntimeReference(init)) {
119
+ throw typeError("new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.");
120
+ }
121
+ return new HeadersObj(into.proto, attempt(() => new Headers(Object.fromEntries(entries(init).map(([key, value]) => [key, coerceToString(value)])))));
122
+ }
123
+ if (isRuntimeReference(init)) {
124
+ throw typeError("new URLSearchParams(...) expects a query string, data object, or synchronous iterable pairs.");
125
+ }
126
+ if (!(init instanceof Obj)) {
127
+ throw typeError("new URLSearchParams(...) expects a query string, data object, iterable pairs, or URLSearchParams.");
128
+ }
129
+ return new URLSearchParamsObj(into.proto, new URLSearchParams(Object.fromEntries(entries(init).map(([key, value]) => [key, coerceToString(value)]))));
130
+ };
131
+ /** The host validates header names and values and throws its own TypeError; the program gets one of its own. */
132
+ export const attempt = (run) => {
133
+ try {
134
+ return run();
135
+ }
136
+ catch (error) {
137
+ throw typeError(error instanceof Error ? error.message : String(error));
138
+ }
139
+ };
140
+ /** Headers and URLSearchParams `forEach`: the callback sees each `[name, value]` pair as listed when it started. */
141
+ export const pairsForEach = (ctx, target, pairs, callback, thisArg) => {
142
+ const list = new Arr(ctx.builtins.Array, pairs.map((pair) => new Arr(ctx.builtins.Array, pair)));
143
+ return new Invoke(ctx.prelude.fn("pairsForEach"), undefined, [target, list, callback, thisArg], undefined);
144
+ };
145
+ const constructURLSearchParams = (ctx, init, proto) => {
146
+ const wrap = (params) => new URLSearchParamsObj(proto, params);
147
+ if (init === undefined)
148
+ return wrap(new URLSearchParams());
149
+ if (init instanceof URLSearchParamsObj)
150
+ return wrap(new URLSearchParams(init.params));
151
+ if (typeof init === "string")
152
+ return wrap(new URLSearchParams(init));
153
+ if (init === null || typeof init === "number" || typeof init === "boolean") {
154
+ return wrap(new URLSearchParams(coerceToString(init)));
155
+ }
156
+ return readPairs(ctx, init, "new URLSearchParams(...)", { kind: "URLSearchParams", proto });
157
+ };
158
+ export const urlSearchParamsGlobal = (ctx) => {
159
+ const builtins = ctx.builtins;
160
+ const proto = builtins.URLSearchParams;
161
+ const searchParams = constructor(builtins, proto, {
162
+ name: "URLSearchParams",
163
+ call: requiresNew("URLSearchParams"),
164
+ construct: (args, newTarget) => constructURLSearchParams(ctx, args[0], prototypeFrom(newTarget, proto)),
165
+ });
166
+ const self = (thisValue, name) => receiver(URLSearchParamsObj, thisValue, `URLSearchParams.prototype.${name}`);
167
+ const wrap = (items) => new Arr(builtins.Array, items);
168
+ const arg = (args, index) => coerceToString(args[index]);
169
+ const requireArgs = (name, args, count) => {
170
+ if (args.length < count) {
171
+ throw typeError(`URLSearchParams.${name} requires ${count} argument${count === 1 ? "" : "s"}.`);
172
+ }
173
+ };
174
+ defineAccessor(proto, "size", (thisValue) => self(thisValue, "size").params.size);
175
+ methods(builtins, proto, [
176
+ [
177
+ "append",
178
+ 2,
179
+ (thisValue, args) => {
180
+ requireArgs("append", args, 2);
181
+ self(thisValue, "append").params.append(arg(args, 0), arg(args, 1));
182
+ return undefined;
183
+ },
184
+ ],
185
+ [
186
+ "delete",
187
+ 1,
188
+ (thisValue, args) => {
189
+ requireArgs("delete", args, 1);
190
+ const params = self(thisValue, "delete").params;
191
+ if (args[1] !== undefined)
192
+ params.delete(arg(args, 0), arg(args, 1));
193
+ else
194
+ params.delete(arg(args, 0));
195
+ return undefined;
196
+ },
197
+ ],
198
+ [
199
+ "get",
200
+ 1,
201
+ (thisValue, args) => {
202
+ requireArgs("get", args, 1);
203
+ return self(thisValue, "get").params.get(arg(args, 0));
204
+ },
205
+ ],
206
+ [
207
+ "getAll",
208
+ 1,
209
+ (thisValue, args) => {
210
+ requireArgs("getAll", args, 1);
211
+ return wrap(self(thisValue, "getAll").params.getAll(arg(args, 0)));
212
+ },
213
+ ],
214
+ [
215
+ "has",
216
+ 1,
217
+ (thisValue, args) => {
218
+ requireArgs("has", args, 1);
219
+ const params = self(thisValue, "has").params;
220
+ return args[1] !== undefined ? params.has(arg(args, 0), arg(args, 1)) : params.has(arg(args, 0));
221
+ },
222
+ ],
223
+ [
224
+ "set",
225
+ 2,
226
+ (thisValue, args) => {
227
+ requireArgs("set", args, 2);
228
+ self(thisValue, "set").params.set(arg(args, 0), arg(args, 1));
229
+ return undefined;
230
+ },
231
+ ],
232
+ [
233
+ "sort",
234
+ 0,
235
+ (thisValue) => {
236
+ self(thisValue, "sort").params.sort();
237
+ return undefined;
238
+ },
239
+ ],
240
+ ...iteratorMethods(builtins, self),
241
+ ["toString", 0, (thisValue) => self(thisValue, "toString").params.toString()],
242
+ [
243
+ "forEach",
244
+ 1,
245
+ (thisValue, args) => {
246
+ requireArgs("forEach", args, 1);
247
+ const target = self(thisValue, "forEach");
248
+ const callback = requireCallback(args[0], "URLSearchParams.forEach");
249
+ return pairsForEach(ctx, target, Array.from(target.params.entries()), callback, args[1]);
250
+ },
251
+ ],
252
+ ]);
253
+ define(proto, IteratorSymbol, get(proto, "entries"), hidden);
254
+ return searchParams;
255
+ };
@@ -0,0 +1,6 @@
1
+ import { type Native, type Value } from "../runtime/objects.js";
2
+ import type { Interpreter } from "../runtime/interpreter.js";
3
+ export type Coercion = "Number" | "String" | "Boolean" | "parseInt" | "parseFloat" | "isFinite" | "isNaN";
4
+ export declare const coerce: <R>(ctx: Interpreter<R>, name: Coercion, args: Array<Value>) => import("../runtime/objects.js").NativeResult;
5
+ /** A global coercion function such as `Number` or `parseInt`. */
6
+ export declare const coercion: <R>(ctx: Interpreter<R>, name: Coercion, length?: number) => Native;
@@ -0,0 +1,32 @@
1
+ import { fn } from "../runtime/native.js";
2
+ import { coerceToNumber, coerceToString } from "../runtime/objects.js";
3
+ import { withPrimitives } from "../runtime/callback.js";
4
+ export const coerce = (ctx, name, args) => {
5
+ // Native: Number() is 0 and String() is "", unlike their undefined-argument forms; the
6
+ // other coercers match native through the undefined-argument path below.
7
+ if (args.length === 0) {
8
+ if (name === "Number")
9
+ return 0;
10
+ if (name === "String")
11
+ return "";
12
+ }
13
+ const raw = args[0];
14
+ if (name === "Boolean")
15
+ return Boolean(raw);
16
+ if (name === "parseInt") {
17
+ return withPrimitives(["string", "number"], [raw, args[1]], ([text, radix]) => parseInt(coerceToString(text), coerceToNumber(radix)));
18
+ }
19
+ return withPrimitives(name === "String" || name === "parseFloat" ? "string" : "number", [raw], ([value]) => {
20
+ if (name === "Number")
21
+ return coerceToNumber(value);
22
+ if (name === "isFinite")
23
+ return Number.isFinite(coerceToNumber(value));
24
+ if (name === "isNaN")
25
+ return Number.isNaN(coerceToNumber(value));
26
+ if (name === "parseFloat")
27
+ return parseFloat(coerceToString(value));
28
+ return coerceToString(value);
29
+ });
30
+ };
31
+ /** A global coercion function such as `Number` or `parseInt`. */
32
+ export const coercion = (ctx, name, length = 1) => fn(ctx.builtins, name, length, (_, args) => coerce(ctx, name, args));
@@ -0,0 +1,5 @@
1
+ import { Obj } from "../runtime/objects.js";
2
+ import type { Interpreter } from "../runtime/interpreter.js";
3
+ export declare const base64Global: <R>(ctx: Interpreter<R>, name: "atob" | "btoa") => import("../runtime/objects.js").Native;
4
+ export declare const structuredCloneGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
5
+ export declare const cryptoGlobal: <R>(ctx: Interpreter<R>) => Obj;