@opencode/codemode 2.2.7 → 2.3.0

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 (197) hide show
  1. package/README.md +11 -13
  2. package/dist/{vm/async.d.ts → async.d.ts} +1 -1
  3. package/dist/codemode.d.ts +8 -22
  4. package/dist/codemode.js +17 -38
  5. package/dist/data.d.ts +4 -19
  6. package/dist/data.js +1 -82
  7. package/dist/extension.d.ts +8 -2
  8. package/dist/extension.js +9 -0
  9. package/dist/{vm/host.d.ts → host.d.ts} +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/{vm/opcodes.d.ts → opcodes.d.ts} +1 -1
  12. package/dist/{vm/prelude → prelude}/helpers.js +1 -1
  13. package/dist/{vm/runtime → runtime}/driver.d.ts +1 -1
  14. package/dist/{vm/runtime → runtime}/driver.js +1 -1
  15. package/dist/{vm/runtime → runtime}/errors.js +2 -2
  16. package/dist/{vm/runtime → runtime}/execute.d.ts +17 -8
  17. package/dist/{vm/runtime → runtime}/execute.js +11 -9
  18. package/dist/{vm/runtime → runtime}/extensions.d.ts +1 -1
  19. package/dist/{vm/runtime → runtime}/extensions.js +39 -4
  20. package/dist/{vm/runtime → runtime}/globals.js +1 -1
  21. package/dist/{vm/runtime → runtime}/interpreter.d.ts +1 -1
  22. package/dist/{vm/runtime → runtime}/model.d.ts +1 -1
  23. package/dist/{vm/runtime → runtime}/objects.d.ts +1 -1
  24. package/dist/{vm/runtime → runtime}/objects.js +1 -1
  25. package/dist/{vm/runtime → runtime}/operations.d.ts +1 -1
  26. package/dist/{vm/runtime → runtime}/operations.js +1 -1
  27. package/dist/scan.js +2 -2
  28. package/dist/{vm/scheduler.d.ts → scheduler.d.ts} +1 -1
  29. package/dist/{vm/snapshot → snapshot}/codec.d.ts +6 -5
  30. package/dist/{vm/snapshot → snapshot}/codec.js +12 -5
  31. package/dist/{vm/snapshot → snapshot}/snapshot.d.ts +8 -5
  32. package/dist/{vm/snapshot → snapshot}/snapshot.js +14 -3
  33. package/dist/{vm/snapshot.js → snapshot.js} +1 -1
  34. package/dist/stdlib/array.d.ts +14 -9
  35. package/dist/stdlib/array.js +89 -276
  36. package/dist/stdlib/bytes.d.ts +11 -7
  37. package/dist/stdlib/bytes.js +112 -79
  38. package/dist/stdlib/collections.d.ts +7 -7
  39. package/dist/stdlib/collections.js +30 -339
  40. package/dist/stdlib/console.d.ts +2 -2
  41. package/dist/stdlib/console.js +3 -3
  42. package/dist/stdlib/date.d.ts +2 -2
  43. package/dist/stdlib/date.js +21 -30
  44. package/dist/stdlib/headers.d.ts +2 -2
  45. package/dist/stdlib/headers.js +15 -33
  46. package/dist/stdlib/iterator.d.ts +2 -2
  47. package/dist/stdlib/iterator.js +10 -302
  48. package/dist/stdlib/json.d.ts +2 -2
  49. package/dist/stdlib/json.js +15 -31
  50. package/dist/stdlib/math.d.ts +2 -7
  51. package/dist/stdlib/math.js +6 -30
  52. package/dist/stdlib/number.d.ts +3 -3
  53. package/dist/stdlib/number.js +8 -8
  54. package/dist/stdlib/object.d.ts +4 -4
  55. package/dist/stdlib/object.js +12 -30
  56. package/dist/stdlib/regexp.d.ts +6 -5
  57. package/dist/stdlib/regexp.js +18 -13
  58. package/dist/stdlib/string.d.ts +2 -2
  59. package/dist/stdlib/string.js +53 -53
  60. package/dist/stdlib/url.d.ts +21 -9
  61. package/dist/stdlib/url.js +55 -55
  62. package/dist/stdlib/value.d.ts +3 -4
  63. package/dist/stdlib/value.js +5 -6
  64. package/dist/stdlib/web.d.ts +4 -4
  65. package/dist/stdlib/web.js +7 -7
  66. package/dist/tool-runtime.d.ts +14 -13
  67. package/dist/tool-runtime.js +245 -53
  68. package/dist/tool-schema.d.ts +5 -0
  69. package/dist/tool-schema.js +36 -16
  70. package/dist/tool.d.ts +24 -9
  71. package/dist/tool.js +15 -22
  72. package/dist/{vm/vm.d.ts → vm.d.ts} +3 -3
  73. package/dist/{vm/vm.js → vm.js} +1 -1
  74. package/package.json +3 -5
  75. package/dist/interpreter/callback.d.ts +0 -35
  76. package/dist/interpreter/callback.js +0 -98
  77. package/dist/interpreter/errors.js +0 -173
  78. package/dist/interpreter/execute.d.ts +0 -14
  79. package/dist/interpreter/execute.js +0 -207
  80. package/dist/interpreter/extensions.d.ts +0 -9
  81. package/dist/interpreter/extensions.js +0 -248
  82. package/dist/interpreter/generators.d.ts +0 -3
  83. package/dist/interpreter/generators.js +0 -168
  84. package/dist/interpreter/globals.js +0 -144
  85. package/dist/interpreter/interpreter.d.ts +0 -48
  86. package/dist/interpreter/interpreter.js +0 -2253
  87. package/dist/interpreter/intrinsics.d.ts +0 -15
  88. package/dist/interpreter/intrinsics.js +0 -105
  89. package/dist/interpreter/model.d.ts +0 -68
  90. package/dist/interpreter/model.js +0 -54
  91. package/dist/interpreter/native.d.ts +0 -17
  92. package/dist/interpreter/native.js +0 -35
  93. package/dist/interpreter/objects.d.ts +0 -301
  94. package/dist/interpreter/objects.js +0 -592
  95. package/dist/interpreter/promises.d.ts +0 -18
  96. package/dist/interpreter/promises.js +0 -292
  97. package/dist/interpreter/runner.d.ts +0 -178
  98. package/dist/interpreter/runner.js +0 -480
  99. package/dist/interpreter/scope.d.ts +0 -16
  100. package/dist/interpreter/scope.js +0 -79
  101. package/dist/suspend-error.d.ts +0 -24
  102. package/dist/suspend-error.js +0 -25
  103. package/dist/vm/data.d.ts +0 -7
  104. package/dist/vm/data.js +0 -13
  105. package/dist/vm/index.d.ts +0 -6
  106. package/dist/vm/index.js +0 -6
  107. package/dist/vm/runtime/errors.d.ts +0 -23
  108. package/dist/vm/runtime/globals.d.ts +0 -6
  109. package/dist/vm/runtime/limits.d.ts +0 -10
  110. package/dist/vm/runtime/limits.js +0 -19
  111. package/dist/vm/runtime/modules.d.ts +0 -4
  112. package/dist/vm/runtime/modules.js +0 -33
  113. package/dist/vm/runtime/references.d.ts +0 -8
  114. package/dist/vm/runtime/references.js +0 -51
  115. package/dist/vm/stdlib/array.d.ts +0 -16
  116. package/dist/vm/stdlib/array.js +0 -311
  117. package/dist/vm/stdlib/bytes.d.ts +0 -11
  118. package/dist/vm/stdlib/bytes.js +0 -222
  119. package/dist/vm/stdlib/collections.d.ts +0 -7
  120. package/dist/vm/stdlib/collections.js +0 -188
  121. package/dist/vm/stdlib/console.d.ts +0 -6
  122. package/dist/vm/stdlib/console.js +0 -93
  123. package/dist/vm/stdlib/date.d.ts +0 -2
  124. package/dist/vm/stdlib/date.js +0 -123
  125. package/dist/vm/stdlib/headers.d.ts +0 -2
  126. package/dist/vm/stdlib/headers.js +0 -92
  127. package/dist/vm/stdlib/iterator.d.ts +0 -2
  128. package/dist/vm/stdlib/iterator.js +0 -30
  129. package/dist/vm/stdlib/json.d.ts +0 -3
  130. package/dist/vm/stdlib/json.js +0 -42
  131. package/dist/vm/stdlib/math.d.ts +0 -3
  132. package/dist/vm/stdlib/math.js +0 -73
  133. package/dist/vm/stdlib/number.d.ts +0 -3
  134. package/dist/vm/stdlib/number.js +0 -72
  135. package/dist/vm/stdlib/object.d.ts +0 -6
  136. package/dist/vm/stdlib/object.js +0 -201
  137. package/dist/vm/stdlib/regexp.d.ts +0 -8
  138. package/dist/vm/stdlib/regexp.js +0 -119
  139. package/dist/vm/stdlib/string.d.ts +0 -2
  140. package/dist/vm/stdlib/string.js +0 -272
  141. package/dist/vm/stdlib/url.d.ts +0 -25
  142. package/dist/vm/stdlib/url.js +0 -255
  143. package/dist/vm/stdlib/value.d.ts +0 -6
  144. package/dist/vm/stdlib/value.js +0 -32
  145. package/dist/vm/stdlib/web.d.ts +0 -5
  146. package/dist/vm/stdlib/web.js +0 -97
  147. /package/dist/{vm/async.js → async.js} +0 -0
  148. /package/dist/{vm/code.d.ts → code.d.ts} +0 -0
  149. /package/dist/{vm/code.js → code.js} +0 -0
  150. /package/dist/{vm/compiler → compiler}/compile.d.ts +0 -0
  151. /package/dist/{vm/compiler → compiler}/compile.js +0 -0
  152. /package/dist/{vm/compiler → compiler}/scope.d.ts +0 -0
  153. /package/dist/{vm/compiler → compiler}/scope.js +0 -0
  154. /package/dist/{vm/generators.d.ts → generators.d.ts} +0 -0
  155. /package/dist/{vm/generators.js → generators.js} +0 -0
  156. /package/dist/{vm/host.js → host.js} +0 -0
  157. /package/dist/{vm/internal-prelude.d.ts → internal-prelude.d.ts} +0 -0
  158. /package/dist/{vm/internal-prelude.js → internal-prelude.js} +0 -0
  159. /package/dist/{vm/opcodes.js → opcodes.js} +0 -0
  160. /package/dist/{vm/prelude → prelude}/bytecode.d.ts +0 -0
  161. /package/dist/{vm/prelude → prelude}/bytecode.js +0 -0
  162. /package/dist/{vm/prelude → prelude}/bytecode.json +0 -0
  163. /package/dist/{vm/prelude → prelude}/helpers.d.ts +0 -0
  164. /package/dist/{vm/prelude → prelude}/prelude.d.ts +0 -0
  165. /package/dist/{vm/prelude → prelude}/prelude.js +0 -0
  166. /package/dist/{vm/prelude → prelude}/source.d.ts +0 -0
  167. /package/dist/{vm/prelude → prelude}/source.js +0 -0
  168. /package/dist/{vm/runtime → runtime}/callback.d.ts +0 -0
  169. /package/dist/{vm/runtime → runtime}/callback.js +0 -0
  170. /package/dist/{interpreter → runtime}/errors.d.ts +0 -0
  171. /package/dist/{vm/runtime → runtime}/generators.d.ts +0 -0
  172. /package/dist/{vm/runtime → runtime}/generators.js +0 -0
  173. /package/dist/{interpreter → runtime}/globals.d.ts +0 -0
  174. /package/dist/{vm/runtime → runtime}/interpreter.js +0 -0
  175. /package/dist/{vm/runtime → runtime}/intrinsic-names.d.ts +0 -0
  176. /package/dist/{vm/runtime → runtime}/intrinsic-names.js +0 -0
  177. /package/dist/{vm/runtime → runtime}/intrinsics.d.ts +0 -0
  178. /package/dist/{vm/runtime → runtime}/intrinsics.js +0 -0
  179. /package/dist/{interpreter → runtime}/limits.d.ts +0 -0
  180. /package/dist/{interpreter → runtime}/limits.js +0 -0
  181. /package/dist/{vm/runtime → runtime}/model.js +0 -0
  182. /package/dist/{interpreter → runtime}/modules.d.ts +0 -0
  183. /package/dist/{interpreter → runtime}/modules.js +0 -0
  184. /package/dist/{vm/runtime → runtime}/native.d.ts +0 -0
  185. /package/dist/{vm/runtime → runtime}/native.js +0 -0
  186. /package/dist/{vm/runtime → runtime}/promises.d.ts +0 -0
  187. /package/dist/{vm/runtime → runtime}/promises.js +0 -0
  188. /package/dist/{interpreter → runtime}/references.d.ts +0 -0
  189. /package/dist/{interpreter → runtime}/references.js +0 -0
  190. /package/dist/{vm/runtime → runtime}/signals.d.ts +0 -0
  191. /package/dist/{vm/runtime → runtime}/signals.js +0 -0
  192. /package/dist/{vm/runtime → runtime}/source.d.ts +0 -0
  193. /package/dist/{vm/runtime → runtime}/source.js +0 -0
  194. /package/dist/{vm/runtime → runtime}/table.d.ts +0 -0
  195. /package/dist/{vm/runtime → runtime}/table.js +0 -0
  196. /package/dist/{vm/scheduler.js → scheduler.js} +0 -0
  197. /package/dist/{vm/snapshot.d.ts → snapshot.d.ts} +0 -0
@@ -1,92 +0,0 @@
1
- import { constructor, methods, prototypeFrom, receiver, requiresNew, iteratorMethods } from "../runtime/native.js";
2
- import { IteratorSymbol, typeError } from "../runtime/model.js";
3
- import { define, get, hidden, Arr, HeadersObj, Obj, coerceToString } from "../runtime/objects.js";
4
- import { requireCallback } from "../runtime/callback.js";
5
- import { attempt, pairsForEach, readPairs } from "./url.js";
6
- const constructHeaders = (ctx, init, proto) => {
7
- if (init === undefined)
8
- return new HeadersObj(proto, new Headers());
9
- if (init instanceof Obj)
10
- return readPairs(ctx, init, "new Headers(...)", { kind: "Headers", proto });
11
- throw typeError("new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.");
12
- };
13
- export const headersGlobal = (ctx) => {
14
- const builtins = ctx.builtins;
15
- const proto = builtins.Headers;
16
- const headers = constructor(builtins, proto, {
17
- name: "Headers",
18
- call: requiresNew("Headers"),
19
- construct: (args, newTarget) => constructHeaders(ctx, args[0], prototypeFrom(newTarget, proto)),
20
- });
21
- const self = (thisValue, name) => receiver(HeadersObj, thisValue, `Headers.prototype.${name}`);
22
- const wrap = (items) => new Arr(builtins.Array, items);
23
- const arg = (args, index) => coerceToString(args[index]);
24
- const requireArgs = (name, args, count) => {
25
- if (args.length < count)
26
- throw typeError(`Headers.${name} requires ${count} argument${count === 1 ? "" : "s"}.`);
27
- };
28
- methods(builtins, proto, [
29
- [
30
- "append",
31
- 2,
32
- (thisValue, args) => {
33
- requireArgs("append", args, 2);
34
- const target = self(thisValue, "append").headers;
35
- attempt(() => target.append(arg(args, 0), arg(args, 1)));
36
- return undefined;
37
- },
38
- ],
39
- [
40
- "delete",
41
- 1,
42
- (thisValue, args) => {
43
- requireArgs("delete", args, 1);
44
- const target = self(thisValue, "delete").headers;
45
- attempt(() => target.delete(arg(args, 0)));
46
- return undefined;
47
- },
48
- ],
49
- [
50
- "get",
51
- 1,
52
- (thisValue, args) => {
53
- requireArgs("get", args, 1);
54
- const target = self(thisValue, "get").headers;
55
- return attempt(() => target.get(arg(args, 0)));
56
- },
57
- ],
58
- ["getSetCookie", 0, (thisValue) => wrap(self(thisValue, "getSetCookie").headers.getSetCookie())],
59
- [
60
- "has",
61
- 1,
62
- (thisValue, args) => {
63
- requireArgs("has", args, 1);
64
- const target = self(thisValue, "has").headers;
65
- return attempt(() => target.has(arg(args, 0)));
66
- },
67
- ],
68
- [
69
- "set",
70
- 2,
71
- (thisValue, args) => {
72
- requireArgs("set", args, 2);
73
- const target = self(thisValue, "set").headers;
74
- attempt(() => target.set(arg(args, 0), arg(args, 1)));
75
- return undefined;
76
- },
77
- ],
78
- ...iteratorMethods(builtins, self),
79
- [
80
- "forEach",
81
- 1,
82
- (thisValue, args) => {
83
- requireArgs("forEach", args, 1);
84
- const target = self(thisValue, "forEach");
85
- const callback = requireCallback(args[0], "Headers.forEach");
86
- return pairsForEach(ctx, target, Array.from(target.headers.entries()), callback, args[1]);
87
- },
88
- ],
89
- ]);
90
- define(proto, IteratorSymbol, get(proto, "entries"), hidden);
91
- return headers;
92
- };
@@ -1,2 +0,0 @@
1
- import type { Interpreter } from "../runtime/interpreter.js";
2
- export declare const iteratorGlobals: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -1,30 +0,0 @@
1
- import { typeError } from "../runtime/model.js";
2
- import { constructor, methods, receiver, requiresNew } from "../runtime/native.js";
3
- import { iteratorResult, IteratorObj, Position } from "../runtime/objects.js";
4
- // Every built-in iterator and helper shares the Iterator prototype; JS gives each collection its own, which is only
5
- // observable through getPrototypeOf. The helpers (`map`, `take`, `Iterator.from`, ...) are the prelude's.
6
- export const iteratorGlobals = (ctx) => {
7
- const builtins = ctx.builtins;
8
- const proto = builtins.Iterator;
9
- methods(builtins, proto, [
10
- [
11
- "next",
12
- 0,
13
- (thisValue) => {
14
- const cursor = receiver(IteratorObj, thisValue, "Iterator.prototype.next").cursor;
15
- if (!(cursor instanceof Position))
16
- throw typeError("Iterator.prototype.next called on an internal iterator.");
17
- const step = cursor.step();
18
- return iteratorResult(builtins.Object, step.value, step.done);
19
- },
20
- ],
21
- ]);
22
- return constructor(builtins, proto, {
23
- name: "Iterator",
24
- length: 0,
25
- call: requiresNew("Iterator"),
26
- construct: () => {
27
- throw typeError("Iterator is abstract; use Iterator.from(...) or a built-in iterator.");
28
- },
29
- });
30
- };
@@ -1,3 +0,0 @@
1
- import type { Interpreter } from "../runtime/interpreter.js";
2
- import { Obj } from "../runtime/objects.js";
3
- export declare const jsonGlobal: <R>(ctx: Interpreter<R>) => Obj;
@@ -1,42 +0,0 @@
1
- import { methods } from "../runtime/native.js";
2
- import { requireCallback } from "../runtime/callback.js";
3
- import { syntaxError } from "../runtime/model.js";
4
- import { typeofValue } from "../runtime/references.js";
5
- import { fromJson } from "../data.js";
6
- import { Arr, Obj, coerceToString, record } from "../runtime/objects.js";
7
- import { Invoke, Push } from "../runtime/signals.js";
8
- export const jsonGlobal = (ctx) => {
9
- const json = new Obj(ctx.builtins.Object);
10
- methods(ctx.builtins, json, [
11
- ["parse", 2, (_, args) => parse(ctx, args)],
12
- ["stringify", 3, (_, args) => stringify(args)],
13
- ]);
14
- return json;
15
- };
16
- const parse = (ctx, args) => {
17
- const text = coerceToString(args[0]);
18
- const parsed = (() => {
19
- try {
20
- return fromJson(ctx, JSON.parse(text));
21
- }
22
- catch (error) {
23
- throw syntaxError(`JSON.parse received invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
24
- }
25
- })();
26
- if (typeofValue(args[1]) !== "function")
27
- return parsed;
28
- const reviver = requireCallback(args[1], "JSON.parse");
29
- return new Invoke(ctx.prelude.fn("revive"), undefined, [record(ctx.builtins.Object, { "": parsed }), "", reviver], undefined);
30
- };
31
- const stringify = (args) => {
32
- const space = args[2];
33
- const indent = typeof space === "number" || typeof space === "string" ? space : undefined;
34
- const replacer = args[1];
35
- const properties = replacer instanceof Arr
36
- ? replacer.items
37
- .filter((item) => typeof item === "string" || typeof item === "number")
38
- .map(String)
39
- : undefined;
40
- const callback = typeofValue(replacer) === "function" ? requireCallback(replacer, "JSON.stringify") : undefined;
41
- return new Push("JSON.stringify", [args[0], callback, properties, indent]);
42
- };
@@ -1,3 +0,0 @@
1
- import { Obj } from "../runtime/objects.js";
2
- import type { Interpreter } from "../runtime/interpreter.js";
3
- export declare const mathGlobal: <R>(ctx: Interpreter<R>) => Obj;
@@ -1,73 +0,0 @@
1
- import { constants, methods } from "../runtime/native.js";
2
- import { Obj, coerceToNumber } from "../runtime/objects.js";
3
- import { withPrimitives } from "../runtime/callback.js";
4
- export const mathGlobal = (ctx) => {
5
- const builtins = ctx.builtins;
6
- const math = new Obj(builtins.Object);
7
- // Convert only the arguments a method consumes; like JS, extras are ignored
8
- // (so built-ins work as callbacks receiving (element, index, array)).
9
- const unary = (name, op) => [
10
- name,
11
- 1,
12
- (_, args) => withPrimitives("number", [args[0]], ([a]) => op(coerceToNumber(a))),
13
- ];
14
- const binary = (name, op) => [
15
- name,
16
- 2,
17
- (_, args) => withPrimitives("number", [args[0], args[1]], ([a, b]) => op(coerceToNumber(a), coerceToNumber(b))),
18
- ];
19
- const variadic = (name, op) => [
20
- name,
21
- 2,
22
- (_, args) => withPrimitives("number", args, (values) => op(...values.map(coerceToNumber))),
23
- ];
24
- constants(math, {
25
- PI: Math.PI,
26
- E: Math.E,
27
- LN2: Math.LN2,
28
- LN10: Math.LN10,
29
- LOG2E: Math.LOG2E,
30
- LOG10E: Math.LOG10E,
31
- SQRT2: Math.SQRT2,
32
- SQRT1_2: Math.SQRT1_2,
33
- });
34
- methods(builtins, math, [
35
- ["random", 0, () => Math.random()],
36
- variadic("max", Math.max),
37
- variadic("min", Math.min),
38
- variadic("hypot", Math.hypot),
39
- unary("abs", Math.abs),
40
- unary("acos", Math.acos),
41
- unary("acosh", Math.acosh),
42
- unary("asin", Math.asin),
43
- unary("asinh", Math.asinh),
44
- unary("atan", Math.atan),
45
- binary("atan2", Math.atan2),
46
- unary("atanh", Math.atanh),
47
- unary("floor", Math.floor),
48
- unary("ceil", Math.ceil),
49
- unary("round", Math.round),
50
- unary("trunc", Math.trunc),
51
- unary("sign", Math.sign),
52
- unary("sqrt", Math.sqrt),
53
- unary("cbrt", Math.cbrt),
54
- binary("pow", Math.pow),
55
- unary("cos", Math.cos),
56
- unary("cosh", Math.cosh),
57
- unary("sin", Math.sin),
58
- unary("sinh", Math.sinh),
59
- unary("tan", Math.tan),
60
- unary("tanh", Math.tanh),
61
- unary("log", Math.log),
62
- unary("log2", Math.log2),
63
- unary("log10", Math.log10),
64
- unary("log1p", Math.log1p),
65
- unary("exp", Math.exp),
66
- unary("expm1", Math.expm1),
67
- unary("f16round", Math.f16round),
68
- unary("fround", Math.fround),
69
- unary("clz32", Math.clz32),
70
- binary("imul", Math.imul),
71
- ]);
72
- return math;
73
- };
@@ -1,3 +0,0 @@
1
- import type { Interpreter } from "../runtime/interpreter.js";
2
- export declare const numberGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
3
- export declare const booleanGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -1,72 +0,0 @@
1
- import { constructor, constants, methods } from "../runtime/native.js";
2
- import { coerceToNumber } from "../runtime/objects.js";
3
- import { typeError } from "../runtime/model.js";
4
- import { withPrimitives } from "../runtime/callback.js";
5
- import { coerce } from "./value.js";
6
- export const numberGlobal = (ctx) => {
7
- const builtins = ctx.builtins;
8
- const number = constructor(builtins, builtins.Number, {
9
- name: "Number",
10
- length: 1,
11
- call: (_, args) => coerce(ctx, "Number", args),
12
- });
13
- constants(number, {
14
- MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
15
- MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
16
- MAX_VALUE: Number.MAX_VALUE,
17
- MIN_VALUE: Number.MIN_VALUE,
18
- EPSILON: Number.EPSILON,
19
- NaN: Number.NaN,
20
- POSITIVE_INFINITY: Number.POSITIVE_INFINITY,
21
- NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY,
22
- });
23
- methods(builtins, number, [
24
- ["isInteger", 1, (_, args) => Number.isInteger(args[0])],
25
- ["isFinite", 1, (_, args) => Number.isFinite(args[0])],
26
- ["isNaN", 1, (_, args) => Number.isNaN(args[0])],
27
- ["isSafeInteger", 1, (_, args) => Number.isSafeInteger(args[0])],
28
- ["parseInt", 2, (_, args) => coerce(ctx, "parseInt", args)],
29
- ["parseFloat", 1, (_, args) => coerce(ctx, "parseFloat", args)],
30
- ]);
31
- const self = (thisValue, name) => {
32
- if (typeof thisValue === "number")
33
- return thisValue;
34
- throw typeError(`Number.prototype.${name} requires that 'this' be a Number.`);
35
- };
36
- // The receiver is checked first, then the one argument converts through ToPrimitive with the number hint.
37
- const formatting = (name, op) => [
38
- name,
39
- 1,
40
- (thisValue, args) => {
41
- const value = self(thisValue, name);
42
- return withPrimitives("number", [args[0]], ([digits]) => op(value, digits === undefined ? undefined : coerceToNumber(digits)));
43
- },
44
- ];
45
- methods(builtins, builtins.Number, [
46
- formatting("toFixed", (value, digits) => value.toFixed(digits)),
47
- ["toLocaleString", 0, (thisValue) => self(thisValue, "toLocaleString").toLocaleString("en-US")],
48
- formatting("toExponential", (value, digits) => value.toExponential(digits)),
49
- formatting("toPrecision", (value, digits) => (digits === undefined ? value.toString() : value.toPrecision(digits))),
50
- formatting("toString", (value, radix) => value.toString(radix)),
51
- ["valueOf", 0, (thisValue) => self(thisValue, "valueOf")],
52
- ]);
53
- return number;
54
- };
55
- export const booleanGlobal = (ctx) => {
56
- const builtins = ctx.builtins;
57
- const boolean = constructor(builtins, builtins.Boolean, {
58
- name: "Boolean",
59
- length: 1,
60
- call: (_, args) => coerce(ctx, "Boolean", args),
61
- });
62
- const self = (thisValue, name) => {
63
- if (typeof thisValue === "boolean")
64
- return thisValue;
65
- throw typeError(`Boolean.prototype.${name} requires that 'this' be a Boolean.`);
66
- };
67
- methods(builtins, builtins.Boolean, [
68
- ["toString", 0, (thisValue) => String(self(thisValue, "toString"))],
69
- ["valueOf", 0, (thisValue) => self(thisValue, "valueOf")],
70
- ]);
71
- return boolean;
72
- };
@@ -1,6 +0,0 @@
1
- import { type AstNode } from "../runtime/model.js";
2
- import { Obj, type Value } from "../runtime/objects.js";
3
- import type { Interpreter } from "../runtime/interpreter.js";
4
- export declare const enumerableSource: <R>(ctx: Interpreter<R>, label: string, value: Value, node?: AstNode) => Obj;
5
- export declare const objectAssign: <R>(ctx: Interpreter<R>, args: Array<Value>) => Value;
6
- export declare const objectGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -1,201 +0,0 @@
1
- import { constructor, methods, receiver } from "../runtime/native.js";
2
- import { AsyncIteratorSymbol, invalidData, IteratorSymbol, typeError } from "../runtime/model.js";
3
- import { changed, entries, enumerableKeys, getOwn, hasOwn, hasPrototype, keys, own, ownKeys, Arr, Bytes, Obj, PromiseObj, set, coerceToString, } from "../runtime/objects.js";
4
- import { primitivePrototype } from "../runtime/intrinsics.js";
5
- import { describeValue, rejectCircularInsertion } from "../runtime/references.js";
6
- import { invokeMethod } from "../runtime/callback.js";
7
- import { ToolReference } from "../../tool-runtime.js";
8
- // ToObject for enumeration.
9
- export const enumerableSource = (ctx, label, value, node) => {
10
- if (value === null || value === undefined) {
11
- throw typeError(`${label} cannot convert ${describeValue(value)} to an object.`, node);
12
- }
13
- if (value instanceof PromiseObj) {
14
- throw invalidData(`${label} received an un-awaited Promise; await it before inspecting the result.`, node);
15
- }
16
- if (value instanceof ToolReference) {
17
- throw invalidData(`${label} cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or search({ query }) for signatures.`, node);
18
- }
19
- if (typeof value === "string")
20
- return new Arr(ctx.builtins.Array, [...value]);
21
- if (value instanceof Obj)
22
- return value;
23
- return new Obj(ctx.builtins.Object);
24
- };
25
- export const objectAssign = (ctx, args) => {
26
- const target = args[0];
27
- // JS would box a primitive target; wrappers and primitives cannot hold fields here.
28
- if (!(target instanceof Obj)) {
29
- throw typeError(`Object.assign expects a data object or array target, received ${describeValue(target)}.`);
30
- }
31
- const seen = new Set();
32
- for (const source of args.slice(1)) {
33
- if (source === null || source === undefined)
34
- continue;
35
- const from = enumerableSource(ctx, "Object.assign(...)", source);
36
- for (const key of enumerableKeys(from)) {
37
- rejectCircularInsertion(target, getOwn(from, key), "Object.assign result", seen);
38
- if (!set(target, key, getOwn(from, key))) {
39
- throw typeError(`Cannot assign to read only property '${String(key)}'.`);
40
- }
41
- }
42
- }
43
- return target;
44
- };
45
- const classTag = (value) => {
46
- if (value === null)
47
- return "Null";
48
- if (value === undefined)
49
- return "Undefined";
50
- if (value instanceof Obj)
51
- return value.tag;
52
- if (typeof value === "string")
53
- return "String";
54
- if (typeof value === "number")
55
- return "Number";
56
- if (typeof value === "boolean")
57
- return "Boolean";
58
- return "Object";
59
- };
60
- const propertyKey = (value) => value === AsyncIteratorSymbol || value === IteratorSymbol ? value : coerceToString(value);
61
- // SetIntegrityLevel: primitives pass through. A typed array's bytes cannot carry attributes, so JS throws after
62
- // already making it non-extensible.
63
- const restrict = (level, value) => {
64
- if (!(value instanceof Obj))
65
- return value;
66
- changed(value);
67
- value.extensible = false;
68
- if (level === "preventExtensions")
69
- return value;
70
- if (value instanceof Bytes && value.bytes.length > 0) {
71
- throw typeError(`Cannot ${level} array buffer views with elements.`);
72
- }
73
- for (const slot of value.props.values()) {
74
- slot.configurable = false;
75
- if (level === "freeze" && "value" in slot)
76
- slot.writable = false;
77
- }
78
- if (value instanceof Arr)
79
- value.elements = { writable: level === "seal", enumerable: true, configurable: false };
80
- return value;
81
- };
82
- // TestIntegrityLevel: array elements and `length` answer through `own`, so a non-extensible empty array is sealed
83
- // but not frozen, as in JS.
84
- const integrity = (value, frozen) => {
85
- if (!(value instanceof Obj))
86
- return true;
87
- if (value.extensible)
88
- return false;
89
- return ownKeys(value).every((key) => {
90
- const slot = own(value, key);
91
- return slot !== undefined && !slot.configurable && !(frozen && "value" in slot && slot.writable);
92
- });
93
- };
94
- // Object constructs identically with or without new, like JS. Only `keys` copies its result into the
95
- // program; `values`, `entries`, `assign`, and `fromEntries` hand back the program's own values.
96
- export const objectGlobal = (ctx) => {
97
- const builtins = ctx.builtins;
98
- const construct = (args) => {
99
- const first = args[0];
100
- if (first === null || first === undefined)
101
- return new Obj(builtins.Object);
102
- if (first instanceof Obj)
103
- return first;
104
- throw typeError(`Object(${typeof first}) wrapper objects are not supported; use the primitive value directly.`);
105
- };
106
- const object = constructor(builtins, builtins.Object, {
107
- name: "Object",
108
- length: 1,
109
- call: (_, args) => construct(args),
110
- construct: (args) => construct(args),
111
- });
112
- methods(builtins, object, [
113
- [
114
- "keys",
115
- 1,
116
- (_, args) => new Arr(builtins.Array, args[0] instanceof ToolReference
117
- ? [...ctx.tools.keys(args[0].path)]
118
- : keys(enumerableSource(ctx, "Object.keys(...)", args[0]))),
119
- ],
120
- [
121
- "values",
122
- 1,
123
- (_, args) => new Arr(builtins.Array, entries(enumerableSource(ctx, "Object.values(...)", args[0])).map((entry) => entry[1])),
124
- ],
125
- [
126
- "entries",
127
- 1,
128
- (_, args) => new Arr(builtins.Array, entries(enumerableSource(ctx, "Object.entries(...)", args[0])).map((entry) => new Arr(builtins.Array, entry))),
129
- ],
130
- ["hasOwn", 2, (_, args) => hasOwn(enumerableSource(ctx, "Object.hasOwn(...)", args[0]), propertyKey(args[1]))],
131
- ["is", 2, (_, args) => Object.is(args[0], args[1])],
132
- ["assign", 2, (_, args) => objectAssign(ctx, args)],
133
- ["freeze", 1, (_, args) => restrict("freeze", args[0])],
134
- ["seal", 1, (_, args) => restrict("seal", args[0])],
135
- ["preventExtensions", 1, (_, args) => restrict("preventExtensions", args[0])],
136
- ["isFrozen", 1, (_, args) => integrity(args[0], true)],
137
- ["isSealed", 1, (_, args) => integrity(args[0], false)],
138
- ["isExtensible", 1, (_, args) => args[0] instanceof Obj && args[0].extensible],
139
- [
140
- "getPrototypeOf",
141
- 1,
142
- (_, args) => {
143
- if (args[0] instanceof Obj)
144
- return args[0].proto;
145
- const proto = primitivePrototype(builtins, args[0]);
146
- if (proto === undefined) {
147
- throw typeError(`Object.getPrototypeOf cannot convert ${describeValue(args[0])} to an object.`);
148
- }
149
- return proto;
150
- },
151
- ],
152
- [
153
- "create",
154
- 2,
155
- (_, args) => {
156
- if (args[0] !== null && !(args[0] instanceof Obj)) {
157
- throw typeError("Object prototype may only be an Object or null.");
158
- }
159
- if (args[1] !== undefined) {
160
- throw typeError("Object.create property descriptors are not supported; assign the fields after creating the object.");
161
- }
162
- return new Obj(args[0]);
163
- },
164
- ],
165
- ]);
166
- methods(builtins, builtins.Object, [
167
- [
168
- "hasOwnProperty",
169
- 1,
170
- (thisValue, args) => hasOwn(receiver(Obj, thisValue, "Object.prototype.hasOwnProperty"), propertyKey(args[0])),
171
- ],
172
- [
173
- "isPrototypeOf",
174
- 1,
175
- (thisValue, args) => hasPrototype(args[0], receiver(Obj, thisValue, "Object.prototype.isPrototypeOf")),
176
- ],
177
- [
178
- "propertyIsEnumerable",
179
- 1,
180
- (thisValue, args) => own(receiver(Obj, thisValue, "Object.prototype.propertyIsEnumerable"), propertyKey(args[0]))?.enumerable ===
181
- true,
182
- ],
183
- ["toString", 0, (thisValue) => `[object ${classTag(thisValue)}]`],
184
- [
185
- "toLocaleString",
186
- 0,
187
- (thisValue) => invokeMethod(ctx.builtins, thisValue, "toString", "Object.prototype.toLocaleString"),
188
- ],
189
- [
190
- "valueOf",
191
- 0,
192
- (thisValue) => {
193
- if (thisValue === null || thisValue === undefined) {
194
- throw typeError("Object.prototype.valueOf called on null or undefined.");
195
- }
196
- return thisValue;
197
- },
198
- ],
199
- ]);
200
- return object;
201
- };
@@ -1,8 +0,0 @@
1
- import type { Builtins } from "../runtime/intrinsics.js";
2
- import { Arr, Obj, RegExpObj, type Value } from "../runtime/objects.js";
3
- import type { Interpreter } from "../runtime/interpreter.js";
4
- /** Runs host regex work on a RegExp argument, sharing its `lastIndex`, or on a pattern string compiled for the call. */
5
- export declare const withHostRegex: <T>(arg: Value, method: string, extraFlags: string, work: (regex: RegExp) => T) => T;
6
- export declare const matchToValue: (builtins: Builtins, match: RegExpMatchArray) => Arr;
7
- export declare const constructRegExp: (builtins: Builtins, args: Array<Value>, proto?: Obj) => RegExpObj;
8
- export declare const regexpGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -1,119 +0,0 @@
1
- import { constructor, methods, prototypeFrom, receiver } from "../runtime/native.js";
2
- import { syntaxError, typeError } from "../runtime/model.js";
3
- import { define, defineAccessor, Arr, Obj, RegExpObj, record, coerceToNumber, coerceToString, } from "../runtime/objects.js";
4
- const flagProperties = [
5
- "hasIndices",
6
- "global",
7
- "ignoreCase",
8
- "multiline",
9
- "sticky",
10
- "unicode",
11
- "unicodeSets",
12
- "dotAll",
13
- ];
14
- const regexFailureReason = (error) => (error instanceof Error ? error.message : String(error)).replace(/^Invalid regular expression:\s*/i, "");
15
- const escapeRegexHint = 'To match special characters like ( ) [ ] { } + * ? . literally, escape them with a backslash (e.g. "\\\\(") or test for them with String.includes instead.';
16
- /** Runs host regex work on a RegExp argument, sharing its `lastIndex`, or on a pattern string compiled for the call. */
17
- export const withHostRegex = (arg, method, extraFlags, work) => {
18
- if (arg instanceof RegExpObj)
19
- return arg.use(work);
20
- // Anything else is a pattern string, as `new RegExp(arg)` would read it: undefined is the empty pattern.
21
- const source = arg === undefined ? "" : coerceToString(arg);
22
- return work(compilePattern(source, method, extraFlags));
23
- };
24
- const compilePattern = (source, method, extraFlags) => {
25
- try {
26
- return new RegExp(source, extraFlags);
27
- }
28
- catch (error) {
29
- throw syntaxError(`String.${method} received the string ${JSON.stringify(source)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`);
30
- }
31
- };
32
- export const matchToValue = (builtins, match) => {
33
- const result = new Arr(builtins.Array, Array.from(match, (group) => group));
34
- if (match.index !== undefined)
35
- define(result, "index", match.index);
36
- if (match.input !== undefined)
37
- define(result, "input", match.input);
38
- if (match.groups)
39
- define(result, "groups", record(builtins.Object, match.groups));
40
- if (match.indices)
41
- define(result, "indices", indicesToValue(builtins, match.indices));
42
- return result;
43
- };
44
- export const constructRegExp = (builtins, args, proto = builtins.RegExp) => {
45
- const first = args[0];
46
- const pattern = first instanceof RegExpObj ? first.source : first === undefined ? "" : coerceToString(first);
47
- const flagsArg = args[1];
48
- if (flagsArg !== undefined && typeof flagsArg !== "string") {
49
- throw syntaxError(`RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`);
50
- }
51
- const flags = flagsArg ?? (first instanceof RegExpObj ? first.flags : "");
52
- try {
53
- return new RegExpObj(proto, pattern, flags);
54
- }
55
- catch (error) {
56
- const reason = regexFailureReason(error);
57
- throw syntaxError(/flag/i.test(reason)
58
- ? `new RegExp(...) received invalid flags ${JSON.stringify(flags)} (${reason}). Valid flags are d, g, i, m, s, u, v, and y.`
59
- : `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`);
60
- }
61
- };
62
- // RegExp constructs identically with or without new, like JS.
63
- export const regexpGlobal = (ctx) => {
64
- const builtins = ctx.builtins;
65
- const proto = builtins.RegExp;
66
- const regexp = constructor(builtins, proto, {
67
- name: "RegExp",
68
- length: 2,
69
- call: (_, args) => constructRegExp(builtins, args),
70
- construct: (args, newTarget) => constructRegExp(builtins, args, prototypeFrom(newTarget, proto)),
71
- });
72
- methods(builtins, regexp, [
73
- [
74
- "escape",
75
- 1,
76
- (_, args) => {
77
- if (typeof args[0] !== "string")
78
- throw typeError("RegExp.escape expects a string.");
79
- return RegExp.escape(args[0]);
80
- },
81
- ],
82
- ]);
83
- const self = (thisValue, name) => receiver(RegExpObj, thisValue, `RegExp.prototype.${name}`);
84
- defineAccessor(proto, "source", (thisValue) => self(thisValue, "source").source);
85
- defineAccessor(proto, "flags", (thisValue) => self(thisValue, "flags").flags);
86
- // One lastIndex per RegExp, so exec/test and the String methods share one counter.
87
- defineAccessor(proto, "lastIndex", (thisValue) => self(thisValue, "lastIndex").lastIndex, (thisValue, value) => {
88
- self(thisValue, "lastIndex").lastIndex = coerceToNumber(value);
89
- });
90
- for (const name of flagProperties)
91
- defineAccessor(proto, name, (thisValue) => self(thisValue, name).regex[name]);
92
- const run = (name) => [
93
- name,
94
- 1,
95
- (thisValue, args) => {
96
- const value = self(thisValue, name);
97
- const input = coerceToString(args[0]);
98
- const matched = value.use((regex) => regex.exec(input));
99
- if (name === "test")
100
- return matched !== null;
101
- return matched === null ? null : matchToValue(builtins, matched);
102
- },
103
- ];
104
- methods(builtins, proto, [
105
- run("exec"),
106
- run("test"),
107
- ["toString", 0, (thisValue) => coerceToString(self(thisValue, "toString"))],
108
- ]);
109
- return regexp;
110
- };
111
- const indicesToValue = (builtins, indices) => {
112
- const range = (pair) => pair === undefined ? undefined : new Arr(builtins.Array, [...pair]);
113
- const result = new Arr(builtins.Array, Array.from(indices, range));
114
- const groups = indices.groups;
115
- define(result, "groups", groups === undefined
116
- ? undefined
117
- : record(builtins.Object, Object.fromEntries(Object.entries(groups).map(([key, pair]) => [key, range(pair)]))));
118
- return result;
119
- };