GeezerVison is showing github.com — feat(codemode): bind this and arguments in functions, add Function.pr… · Parad0X/opencode@5626212
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/codemode/interpreter-support.md +21-8Lines changed: 21 additions & 8 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -139,11 +139,24 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262 | 139 | 139 | arrow function. | 140 | 140 | - [x] Promise-returning string replacers are coerced synchronously to `"[object Promise]"`, like JavaScript; they are | 141 | 141 | not automatically awaited. | 142 | | -- [x] The optional `thisArg` of iteration methods is accepted and ignored: CodeMode functions have no `this`, so | 143 | | - ignoring it matches JS arrow-function semantics exactly. | 144 | | -- [ ] `this` in non-arrow CodeMode functions and callbacks. | | 142 | +- [x] `this` in non-arrow functions is the call's receiver: `obj.m()` and `obj["m"]()` see `obj`, a bare or detached | | 143 | + call (`f()`, `const m = obj.m; m()`, `(0, obj.m)()`) sees `undefined`, as in strict JS. Arrows read the enclosing | | 144 | + function's `this`. Program code has no receiver, so top-level `this` is `undefined`, as in a module. | | 145 | +- [x] `arguments` in non-arrow functions: an unmapped ordinary object with the call's arguments as indexed | | 146 | + properties and a hidden `length`; iterable, so spread, `for...of`, and `Array.from` work. It is not an Array | | 147 | + (`JSON.stringify` gives `{"0":1}`, `String` gives `[object Arguments]`). A parameter named `arguments` shadows | | 148 | + it; arrows read the enclosing function's; it is only created for functions whose body mentions it. `callee` | | 149 | + and `caller` are absent rather than poisoned. | | 150 | +- [ ] Array methods on `arguments` and other array-likes (`Array.prototype.slice.call(arguments, 1)`); use | | 151 | + `[...arguments]` or a rest parameter meanwhile. | | 152 | +- [x] `Function.prototype.call`, `apply`, and `bind` on program functions and built-ins: | | 153 | + `Array.prototype.push.call(arr, 1)`, `Math.max.apply(null, values)`, `fn.bind(obj, first)`. `apply` accepts an | | 154 | + array, an array-like object (its `length` clamped and capped like `Array.from`), or `null`/`undefined`. A | | 155 | + bound function is named `bound f`, has its remaining `length`, and is not constructible. | | 156 | +- [x] `JSON.parse` revivers and `JSON.stringify` function replacers see the holder object as `this`. | | 157 | +- [ ] The optional `thisArg` of iteration methods (`map`, `forEach`, `Map.prototype.forEach`, `Array.from`, …) is | | 158 | + accepted but not yet passed as `this`; callbacks run with `this` undefined. | 145 | 159 | - [ ] User-defined constructor calls. | 146 | | -- [ ] `Function.prototype.call`, `apply`, and `bind` for CodeMode functions. | 147 | 160 | - [ ] Classes and private fields. | 148 | 161 | - [x] Functions are objects: they hold own properties (`fn.count = 1`), enumerate them, and expose read-only `name` | 149 | 162 | and `length`. Names follow JavaScript's NamedEvaluation: declarations, named expressions, bindings, | @@ -178,7 +191,7 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262 | 178 | 191 | yielded promises; mixed async request queues; sync and async `yield*` forwarding; malformed methods/results; | 179 | 192 | and declaration, expression, and object-method forms with closure and parameter behavior. The adapted suite | 180 | 193 | deliberately skips Test262 variants whose observation mechanism requires unsupported getter definitions, | 181 | | - proxies, prototype inspection or mutation, non-arrow `this`, classes, or arbitrary symbols. It also skips tests | | 194 | + proxies, prototype inspection or mutation, classes, or arbitrary symbols. It also skips tests | 182 | 195 | asserting exact promise reaction-turn counts beyond the observable ordering guarantee documented below. These | 183 | 196 | are interpreter-surface boundaries, not claims that the corresponding full Test262 families pass unchanged. | 184 | 197 |
| @@ -269,7 +282,7 @@ reject }` object. | 269 | 282 | - [x] Recursive assimilation of objects with an own callable `then` field across `Promise.resolve`, combinators, | 270 | 283 | constructors, reactions, `finally`, `await`, and async returns. Thenable methods run deferred, receive | 271 | 284 | first-call-wins resolve/reject functions, and ignore throws after settlement. Inherited/accessor `then` fields | 272 | | - and a JavaScript `this` receiver remain outside the supported object/function model. | | 285 | + remain outside the supported object model. | 273 | 286 | - [x] Dotted tool names are canonicalized into namespace paths; a path can be both callable and a namespace, and the | 274 | 287 | last tool supplied for a canonical path wins. | 275 | 288 | - [x] Tool path segments may be named `constructor`, `prototype`, or `__proto__` because paths use inert Map keys. | @@ -419,9 +432,9 @@ reject }` object. | 419 | 432 | - [x] `JSON.parse` and `JSON.stringify` for supported data objects. | 420 | 433 | - [x] Numeric/string indentation for `JSON.stringify`. | 421 | 434 | - [x] `JSON.parse` reviver callbacks, including postorder traversal, deletion through `undefined`, and root replacement. | 422 | | - Revivers receive `(key, value)` but no `this` holder because CodeMode functions intentionally have no `this`. | | 435 | + Revivers receive `(key, value)` with the holder as `this`. | 423 | 436 | - [x] `JSON.stringify` function and array replacers. Function replacers receive `(key, value)` in preorder, including | 424 | | - the root, but no `this` holder. Array replacers preserve requested property order, deduplicate names, coerce | | 437 | + the root, with the holder as `this`. Array replacers preserve requested property order, deduplicate names, coerce | 425 | 438 | number primitives, and ignore non-string/non-number entries. Primitive wrapper entries remain unsupported. | 426 | 439 | - [x] Captured `console.log`, `console.info`, `console.debug`, `console.warn`, and `console.error`. An Error prints as | 427 | 440 | `Error.prototype.toString` would show it (`Error: boom`), wherever it appears in the logged value. | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/data.ts +2-2Lines changed: 2 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -24,7 +24,7 @@ import { typeofValue } from "./interpreter/references.js" | 24 | 24 |
| 25 | 25 | export type Json = Schema.Json | 26 | 26 |
| 27 | | -type Replacer<R> = (args: Array<Value>) => Effect.Effect<Value, unknown, R> | | 27 | +type Replacer<R> = (args: Array<Value>, holder: Obj) => Effect.Effect<Value, unknown, R> | 28 | 28 |
| 29 | 29 | /** | 30 | 30 | * What `JSON.stringify` would serialize for a program value, as host JSON: `toJSON` is honored, functions and | @@ -60,7 +60,7 @@ const walk = <R>( | 60 | 60 | const settled = raw instanceof PromiseObj ? yield* ctx.await(raw) : raw | 61 | 61 | const toJSON = settled instanceof Obj ? get(settled, "toJSON") : undefined | 62 | 62 | const own = toJSON instanceof Callable ? yield* ctx.call(toJSON, settled, [key]) : settled | 63 | | - const value = replacer === undefined ? own : yield* replacer([key, own]) | | 63 | + const value = replacer === undefined ? own : yield* replacer([key, own], holder) | 64 | 64 | if (value === undefined || typeofValue(value) === "function") return undefined | 65 | 65 | if (typeof value === "number") return Number.isFinite(value) ? value : null | 66 | 66 | if (value === null || typeof value === "string" || typeof value === "boolean") return value | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/callback.ts +2-2Lines changed: 2 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -78,7 +78,7 @@ export const applyCollectionCallback = <R>( | 78 | 78 | ctx: Interpreter<R>, | 79 | 79 | callback: Value, | 80 | 80 | name: string, | 81 | | -): ((args: Array<Value>) => Effect.Effect<Value, unknown, R>) => { | | 81 | +): ((args: Array<Value>, thisValue?: Value) => Effect.Effect<Value, unknown, R>) => { | 82 | 82 | if (!isSupportedCallback(callback)) { | 83 | 83 | if (typeofValue(callback) === "function") { | 84 | 84 | throw typeError( | @@ -87,5 +87,5 @@ export const applyCollectionCallback = <R>( | 87 | 87 | } | 88 | 88 | throw typeError(`${name} expects a function callback.`) | 89 | 89 | } | 90 | | - return (callbackArgs) => ctx.call(callback, undefined, callbackArgs) | | 90 | + return (callbackArgs, thisValue) => ctx.call(callback, thisValue, callbackArgs) | 91 | 91 | } |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/globals.ts +31-2Lines changed: 31 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import { Effect } from "effect" | 2 | | -import type { Value } from "./objects.js" | | 2 | +import { Arr, Callable, coerceToInteger, coerceToString, get, Obj, type Value } from "./objects.js" | 3 | 3 | import { arrayGlobal } from "../stdlib/array.js" | 4 | 4 | import { textDecoderGlobal, textEncoderGlobal, uint8ArrayGlobal } from "../stdlib/bytes.js" | 5 | 5 | import { mapGlobal, setGlobal } from "../stdlib/collections.js" | @@ -19,8 +19,9 @@ import { base64Global, cryptoGlobal, structuredCloneGlobal } from "../stdlib/web | 19 | 19 | import { ToolReference } from "../tool-runtime.js" | 20 | 20 | import { errorGlobal } from "./errors.js" | 21 | 21 | import { errorTypes } from "./intrinsics.js" | 22 | | -import { constants, constructor, native } from "./native.js" | | 22 | +import { constants, constructor, methods, native, receiver } from "./native.js" | 23 | 23 | import { AsyncIteratorSymbol, IteratorSymbol, typeError } from "./model.js" | | 24 | +import { checkArrayLength } from "./limits.js" | 24 | 25 | import { generatorGlobals } from "./generators.js" | 25 | 26 | import { promiseGlobal } from "./promises.js" | 26 | 27 | import type { Interpreter } from "./interpreter.js" | @@ -31,6 +32,24 @@ const functionGlobal = <R>(ctx: Interpreter<R>) => { | 31 | 32 | Effect.sync(() => { | 32 | 33 | throw typeError("The Function constructor is not supported; write the function inline.") | 33 | 34 | }) | | 35 | + const target = (thisValue: Value, method: string) => receiver(Callable, thisValue, `Function.prototype.${method}`) | | 36 | + methods(ctx.builtins, ctx.builtins.Function, [ | | 37 | + ["call", 1, (thisValue, args) => ctx.call(target(thisValue, "call"), args[0], args.slice(1))], | | 38 | + ["apply", 2, (thisValue, args) => ctx.call(target(thisValue, "apply"), args[0], listFromArrayLike(args[1]))], | | 39 | + [ | | 40 | + "bind", | | 41 | + 1, | | 42 | + (thisValue, args) => { | | 43 | + const fn = target(thisValue, "bind") | | 44 | + const bound = args.slice(1) | | 45 | + return native<R>(ctx.builtins, { | | 46 | + name: `bound ${coerceToString(get(fn, "name"))}`, | | 47 | + length: Math.max(0, fn.length - bound.length), | | 48 | + call: (_, rest) => ctx.call(fn, args[0], [...bound, ...rest]), | | 49 | + }) | | 50 | + }, | | 51 | + ], | | 52 | + ]) | 34 | 53 | return constructor<R>(ctx.builtins, ctx.builtins.Function, { | 35 | 54 | name: "Function", | 36 | 55 | length: 1, | @@ -39,6 +58,16 @@ const functionGlobal = <R>(ctx: Interpreter<R>) => { | 39 | 58 | }) | 40 | 59 | } | 41 | 60 |
| | 61 | +// CreateListFromArrayLike: `apply` reads `length` and the indexed properties of any object. | | 62 | +const listFromArrayLike = (value: Value): Array<Value> => { | | 63 | + if (value === undefined || value === null) return [] | | 64 | + if (value instanceof Arr) return [...value.items] | | 65 | + if (!(value instanceof Obj)) throw typeError("Function.prototype.apply expects an array-like argument list.") | | 66 | + const length = Math.max(0, coerceToInteger(get(value, "length"))) | | 67 | + checkArrayLength(length) | | 68 | + return Array.from({ length }, (_, index) => get(value, String(index))) | | 69 | +} | | 70 | + | 42 | 71 | const symbolGlobal = <R>(ctx: Interpreter<R>) => { | 43 | 72 | const symbol = native<R>(ctx.builtins, { | 44 | 73 | name: "Symbol", | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/interpreter.ts +38-4Lines changed: 38 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import type { | | 2 | + AnyNode, | 2 | 3 | ArrayExpression, | 3 | 4 | ArrayPattern, | 4 | 5 | AssignmentPattern, | @@ -81,6 +82,7 @@ import { | 81 | 82 | keys, | 82 | 83 | Native, | 83 | 84 | parseArrayIndex, | | 85 | + Arguments, | 84 | 86 | Arr, | 85 | 87 | Fn, | 86 | 88 | GeneratorObj, | @@ -178,6 +180,24 @@ const collectPatternNames = (pattern: Pattern, out: Array<string> = []): Array<s | 178 | 180 | return out | 179 | 181 | } | 180 | 182 |
| | 183 | +// Whether a function body (or a parameter default) reads `arguments`, looking through arrows but not nested | | 184 | +// functions, which own theirs. Memoized so the object is only built for calls that can observe it. | | 185 | +const argumentsUse = new WeakMap<Fn["body"], boolean>() | | 186 | +const usesArguments = (fn: Fn): boolean => { | | 187 | + const cached = argumentsUse.get(fn.body) | | 188 | + if (cached !== undefined) return cached | | 189 | + const found = [...fn.parameters, fn.body].some(function visit(node: AnyNode | null): boolean { | | 190 | + if (node === null || typeof node !== "object") return false | | 191 | + if (node.type === "Identifier") return node.name === "arguments" | | 192 | + if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression") return false | | 193 | + return Object.values(node).some((child) => | | 194 | + Array.isArray(child) ? child.some((item) => visit(item)) : visit(child as AnyNode | null), | | 195 | + ) | | 196 | + }) | | 197 | + argumentsUse.set(fn.body, found) | | 198 | + return found | | 199 | +} | | 200 | + | 181 | 201 | // `var` names declared anywhere in a function body except inside nested functions, which own theirs. | 182 | 202 | // Memoized per body: a function's var names never change, and hoisting runs on every call. | 183 | 203 | const varNames = new WeakMap<ReadonlyArray<Statement | ModuleDeclaration>, ReadonlyArray<string>>() | @@ -287,7 +307,8 @@ export class Interpreter<R> { | 287 | 307 | this.pending = options.pending | 288 | 308 | this.builtins = options.builtins | 289 | 309 | this.logs = options.logs ?? [] | 290 | | - const globalScope = new Map<string, Binding>() | | 310 | + // Program code has no receiver: top-level `this` is undefined, as in a module. | | 311 | + const globalScope = new Map<string, Binding>([["this", { mutable: false, value: undefined }]]) | 291 | 312 | // Calling back into the program never reads frame state, so any frame serves; the root is always alive. | 292 | 313 | this.root = new Frame(this, new ScopeStack([globalScope])) | 293 | 314 | for (const [name, value] of [...globals(this), ...(options.globals?.(this) ?? [])]) { | @@ -468,6 +489,7 @@ class Frame<R> { | 468 | 489 | this.scopes.capture(), | 469 | 490 | node.async, | 470 | 491 | node.generator, | | 492 | + node.type === "ArrowFunctionExpression", | 471 | 493 | ) | 472 | 494 | // Each generator function gets its own prototype, so `g() instanceof g` holds as in JS. | 473 | 495 | if (node.generator) | @@ -1257,6 +1279,8 @@ class Frame<R> { | 1257 | 1279 | } | 1258 | 1280 | case "Identifier": | 1259 | 1281 | return Effect.sync(() => this.scopes.get(node.name, node)) | | 1282 | + case "ThisExpression": | | 1283 | + return Effect.sync(() => this.scopes.get("this", node)) | 1260 | 1284 | case "BinaryExpression": | 1261 | 1285 | return this.evaluateBinaryExpression(node) | 1262 | 1286 | case "LogicalExpression": | @@ -1622,7 +1646,7 @@ class Frame<R> { | 1622 | 1646 | } | 1623 | 1647 | return yield* self.createToolCallPromise(callable.path, args) | 1624 | 1648 | } | 1625 | | - if (callable instanceof Fn) return yield* self.invokeFunction(callable, args, node) | | 1649 | + if (callable instanceof Fn) return yield* self.invokeFunction(callable, thisValue, args, node) | 1626 | 1650 | if (callable instanceof Native) { | 1627 | 1651 | return yield* self.native(() => (callable as Native<R>).call(thisValue, args), node) | 1628 | 1652 | } | @@ -1664,14 +1688,24 @@ class Frame<R> { | 1664 | 1688 | } | 1665 | 1689 |
| 1666 | 1690 | // A callback invoked by a built-in runs below the call that invoked the built-in, so the deeper of the two counts. | 1667 | | - invokeFunction(fn: Fn, args: Array<Value>, node?: AstNode): Effect.Effect<Value, unknown, R> { | | 1691 | + invokeFunction(fn: Fn, thisValue: Value, args: Array<Value>, node?: AstNode): Effect.Effect<Value, unknown, R> { | 1668 | 1692 | const self = this | 1669 | 1693 | return Effect.flatMap(CallSite, (site) => { | 1670 | 1694 | const depth = Math.max(self.depth, site.depth) + 1 | 1671 | 1695 | if (depth > MAX_CALL_DEPTH) throw rangeError("Maximum call stack size exceeded", node) | 1672 | 1696 | const invocation = new Frame(this.ctx, new ScopeStack([...fn.capturedScopes, new Map()]), depth) | 1673 | | - // Seed all parameters first so defaults cannot fall through to same-named outer bindings. | 1674 | 1697 | const paramScope = invocation.scopes.current() | | 1698 | + // `this` and `arguments` are scope bindings so arrows resolve them lexically; a parameter named | | 1699 | + // `arguments` shadows the object, as in JS. | | 1700 | + if (!fn.arrow) paramScope.set("this", { mutable: false, value: thisValue, initialized: true }) | | 1701 | + if (!fn.arrow && usesArguments(fn)) { | | 1702 | + paramScope.set("arguments", { | | 1703 | + mutable: true, | | 1704 | + value: new Arguments(self.ctx.builtins.Object, args), | | 1705 | + initialized: true, | | 1706 | + }) | | 1707 | + } | | 1708 | + // Seed all parameters first so defaults cannot fall through to same-named outer bindings. | 1675 | 1709 | for (const parameter of fn.parameters) { | 1676 | 1710 | for (const name of collectPatternNames(parameter)) { | 1677 | 1711 | paramScope.set(name, { mutable: true, value: undefined, initialized: false }) | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/model.ts +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -72,7 +72,7 @@ export const uriError = failure("URIError") | 72 | 72 |
| 73 | 73 | // Orient the agent rather than enumerate JavaScript; interpreter-support.md is the full matrix. | 74 | 74 | export const supportedSyntaxMessage = | 75 | | - "This is a restricted JavaScript-like language. Supported: plain and async functions, data literals, destructuring, standard control flow, await and Promise, and built-ins such as Array, Object, Math, JSON, Date, RegExp, Map, Set, and URL. Unsupported: classes, this, getters/setters, BigInt, and custom Symbols. Use plain functions and data objects instead." | | 75 | + "This is a restricted JavaScript-like language. Supported: plain and async functions, data literals, destructuring, standard control flow, await and Promise, and built-ins such as Array, Object, Math, JSON, Date, RegExp, Map, Set, and URL. Unsupported: classes, getters/setters, BigInt, and custom Symbols. Use plain functions and data objects instead." | 76 | 76 |
| 77 | 77 | export const unsupportedSyntax = (kind: string, node: AstNode): PendingThrow => | 78 | 78 | new PendingThrow( | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/objects.ts +22-1Lines changed: 22 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -149,7 +149,11 @@ export abstract class Opaque extends Obj { | 149 | 149 |
| 150 | 150 | export abstract class Callable extends Opaque { | 151 | 151 | override readonly tag = "Function" | 152 | | - constructor(proto: Obj, name: string, length: number) { | | 152 | + constructor( | | 153 | + proto: Obj, | | 154 | + name: string, | | 155 | + readonly length: number, | | 156 | + ) { | 153 | 157 | super(proto) | 154 | 158 | define(this, "length", length, readonly) | 155 | 159 | define(this, "name", name, readonly) | @@ -168,12 +172,29 @@ export class Fn extends Callable { | 168 | 172 | readonly capturedScopes: Array<Map<string, Binding>>, | 169 | 173 | readonly async: boolean, | 170 | 174 | readonly generator: boolean, | | 175 | + /** Arrows have no `this` or `arguments` of their own; they read the enclosing function's. */ | | 176 | + readonly arrow: boolean, | 171 | 177 | ) { | 172 | 178 | const optional = parameters.findIndex((p) => p.type === "AssignmentPattern" || p.type === "RestElement") | 173 | 179 | super(proto, name, optional === -1 ? parameters.length : optional) | 174 | 180 | } | 175 | 181 | } | 176 | 182 |
| | 183 | +/** The strict `arguments` object: an ordinary object with indexed own properties and a hidden `length`. */ | | 184 | +export class Arguments extends Obj { | | 185 | + override readonly tag = "Arguments" | | 186 | + constructor(proto: Obj, args: Array<Value>) { | | 187 | + super(proto) | | 188 | + args.forEach((arg, index) => define(this, String(index), arg)) | | 189 | + define(this, "length", args.length, hidden) | | 190 | + } | | 191 | + override iterator() { | | 192 | + return keys(this) | | 193 | + .map((key) => get(this, key)) | | 194 | + .values() | | 195 | + } | | 196 | +} | | 197 | + | 177 | 198 | export type NativeCall<R> = (thisValue: Value, args: Array<Value>) => Effect.Effect<Value, unknown, R> | 178 | 199 | export type NativeConstruct<R> = (args: Array<Value>, newTarget: Callable) => Effect.Effect<Value, unknown, R> | 179 | 200 |
| |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/stdlib/json.ts +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -40,7 +40,7 @@ const parse = <R>(ctx: Interpreter<R>, args: Array<Value>): Effect.Effect<Value, | 40 | 40 | else set(value, name, revived) | 41 | 41 | } | 42 | 42 | } | 43 | | - return yield* apply([key, value]) | | 43 | + return yield* apply([key, value], holder) | 44 | 44 | }) | 45 | 45 | return visit(record(ctx.builtins.Object, { "": parsed }), "") | 46 | 46 | } | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/test/json-callbacks-test262.test.ts +8-5Lines changed: 8 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -210,11 +210,14 @@ describe("Test262 JSON.stringify replacer adaptations", () => { | 210 | 210 | }) | 211 | 211 |
| 212 | 212 | describe("CodeMode JSON callback boundaries", () => { | 213 | | - test("this remains unsupported rather than exposing callback holders", async () => { | 214 | | - const result = await Effect.runPromise( | 215 | | - CodeMode.execute({ code: `return JSON.parse("1", function (key, item) { return this })`, tools: {} }), | 216 | | - ) | 217 | | - expect(result).toMatchObject({ ok: false, error: { kind: "UnsupportedSyntax" } }) | | 213 | + test("revivers and replacers see the holder as this", async () => { | | 214 | + expect( | | 215 | + await value(` | | 216 | + const revived = JSON.parse('{"a":{"b":1}}', function (key, item) { return key === "b" ? this.b + 1 : item }) | | 217 | + const text = JSON.stringify({ a: 1, b: 2 }, function (key, item) { return key === "a" ? this.b : item }) | | 218 | + return [revived, text] | | 219 | + `), | | 220 | + ).toEqual([{ a: { b: 2 } }, '{"a":2,"b":2}']) | 218 | 221 | }) | 219 | 222 |
| 220 | 223 | test("prototype-named keys parse as own data and reach the reviver", async () => { | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/test/new-expression.test.ts +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -77,6 +77,6 @@ describe("new on a non-constructible callee", () => { | 77 | 77 | expect(failure.message).toStartWith( | 78 | 78 | "SyntaxError: Syntax 'ClassDeclaration' is not supported. This is a restricted JavaScript-like language. Supported: ", | 79 | 79 | ) | 80 | | - expect(failure.message).toContain("Unsupported: classes, this, getters/setters, BigInt, and custom Symbols.") | | 80 | + expect(failure.message).toContain("Unsupported: classes, getters/setters, BigInt, and custom Symbols.") | 81 | 81 | }) | 82 | 82 | }) |
|