@opencode/codemode 0.0.0-dev-1180 → 0.0.0-dev-1216

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