From 3f0118022bc5f52dac772687120629e060cccfd1 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Mon, 21 Sep 2026 11:56:15 -0500 Subject: [PATCH] feat(codemode): add Promise.withResolvers, print errors in console, name values in iterable errors (#50389) --- packages/codemode/interpreter-support.md | 5 ++- packages/codemode/src/interpreter/objects.ts | 3 ++ packages/codemode/src/interpreter/promises.ts | 36 +++++++++++++------ packages/codemode/src/stdlib/array.ts | 8 ++--- packages/codemode/src/stdlib/collections.ts | 4 +-- packages/codemode/test/errors.test.ts | 2 +- packages/codemode/test/promise.test.ts | 23 ++++++++++-- packages/codemode/test/stdlib.test.ts | 7 ++++ 8 files changed, 66 insertions(+), 22 deletions(-) diff --git a/packages/codemode/interpreter-support.md b/packages/codemode/interpreter-support.md index 48fc15032cd..d646da292bd 100644 --- a/packages/codemode/interpreter-support.md +++ b/packages/codemode/interpreter-support.md @@ -238,6 +238,8 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262 resolving with the promise itself rejects with a `TypeError`. Resolver callables work anywhere callbacks are accepted, including `.then`/`.catch` handlers and collection callbacks, and vanish at the data boundary like any function. +- [x] `Promise.withResolvers()`: the same promise and resolver callables as the constructor, as a `{ promise, resolve, + reject }` object. - [x] Recursive assimilation of objects with an own callable `then` field across `Promise.resolve`, combinators, constructors, reactions, `finally`, `await`, and async returns. Thenable methods run deferred, receive first-call-wins resolve/reject functions, and ignore throws after settlement. Inherited/accessor `then` fields @@ -370,7 +372,8 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262 - [x] `JSON.stringify` function and array replacers. Function replacers receive `(key, value)` in preorder, including the root, but no `this` holder. Array replacers preserve requested property order, deduplicate names, coerce number primitives, and ignore non-string/non-number entries. Primitive wrapper entries remain unsupported. -- [x] Captured `console.log`, `console.info`, `console.debug`, `console.warn`, and `console.error`. +- [x] Captured `console.log`, `console.info`, `console.debug`, `console.warn`, and `console.error`. An Error prints as + `Error.prototype.toString` would show it (`Error: boom`), wherever it appears in the logged value. - [x] Captured `console.dir` and `console.table`. ## Date diff --git a/packages/codemode/src/interpreter/objects.ts b/packages/codemode/src/interpreter/objects.ts index d850f4583fb..32e4c32e0c2 100644 --- a/packages/codemode/src/interpreter/objects.ts +++ b/packages/codemode/src/interpreter/objects.ts @@ -129,6 +129,9 @@ export class ErrorObj extends Obj { if (shownName === "") return shownMessage return `${shownName}: ${shownMessage}` } + override inspect() { + return this.toString() + } } /** Interpreter machinery a program can hold but never inspect, serialize, or hand to the host. */ diff --git a/packages/codemode/src/interpreter/promises.ts b/packages/codemode/src/interpreter/promises.ts index 88dd49cb4a4..43a18097052 100644 --- a/packages/codemode/src/interpreter/promises.ts +++ b/packages/codemode/src/interpreter/promises.ts @@ -5,7 +5,7 @@ import { CallSite, Throw, rangeError, typeError } from "./model.js" import { Callable, define, get, hidden, Arr, Fn, Obj, PromiseObj, record, type Value } from "./objects.js" import { constructor, fn, methods, native, receiver, requiresNew } from "./native.js" import { createAggregateErrorValue, locate, materialize, normalizeError } from "./errors.js" -import { typeofValue } from "./references.js" +import { describeValue, typeofValue } from "./references.js" import { applyCollectionCallback, isSupportedCallback } from "./callback.js" import type { Interpreter } from "./interpreter.js" @@ -136,7 +136,7 @@ export const resolvePromise = (ctx: Interpreter, value: Value): Effect.Eff return ctx.pending.createWithSelf((self) => resolvePromiseValue(ctx, value, self)) } -const promiseStatics = ["all", "allSettled", "race", "any", "resolve", "reject"] as const +const promiseStatics = ["all", "allSettled", "race", "any", "resolve", "reject", "withResolvers"] as const const invokePromiseMethod = ( ctx: Interpreter, @@ -149,11 +149,18 @@ const invokePromiseMethod = ( if (name === "reject") { return ctx.pending.create(Effect.fail(new Throw(args[0]))) } + if (name === "withResolvers") { + return Effect.map(promiseCapability(ctx), (made) => + record(ctx.builtins.Object, { promise: made.promise, resolve: made.resolve, reject: made.reject }), + ) + } return ctx.pending.create( Effect.gen(function* () { const cursor = yield* ctx.iterate(args[0]) - if (cursor === undefined) throw typeError(`Promise.${name} expects an array or other synchronous iterable.`) + if (cursor === undefined) { + throw typeError(`Promise.${name} expects a synchronous iterable, received ${describeValue(args[0])}.`) + } const items: Array = [] while (true) { const step = yield* cursor.next @@ -237,23 +244,30 @@ const instanceMethod = ( return chainReaction(ctx, promise, onFulfilled, onRejected, method) } -const constructPromise = (ctx: Interpreter, executor: Value): Effect.Effect => { - if (!(executor instanceof Fn)) { - throw typeError("new Promise(...) expects an executor function (e.g. new Promise((resolve, reject) => { ... })).") - } - return Effect.gen(function* () { +/** NewPromiseCapability: a pending promise with the resolve/reject callables that settle it exactly once. */ +const promiseCapability = (ctx: Interpreter) => + Effect.gen(function* () { const deferred = Deferred.makeUnsafe() const promise = yield* ctx.pending.createWithSelf((self) => Effect.flatMap(Deferred.await(deferred), (value) => resolvePromiseValue(ctx, value, self)), ) const resolve = capability(ctx, "resolve", (value) => Deferred.doneUnsafe(deferred, Exit.succeed(value))) const reject = capability(ctx, "reject", (value) => Deferred.doneUnsafe(deferred, Exit.fail(new Throw(value)))) - const executed = yield* Effect.exit(ctx.call(executor, undefined, [resolve, reject])) + return { promise, resolve, reject, deferred } + }) + +const constructPromise = (ctx: Interpreter, executor: Value): Effect.Effect => { + if (!(executor instanceof Fn)) { + throw typeError("new Promise(...) expects an executor function (e.g. new Promise((resolve, reject) => { ... })).") + } + return Effect.gen(function* () { + const made = yield* promiseCapability(ctx) + const executed = yield* Effect.exit(ctx.call(executor, undefined, [made.resolve, made.reject])) if (!Exit.isSuccess(executed)) { if (Cause.hasInterruptsOnly(executed.cause)) return yield* Effect.failCause(executed.cause) - Deferred.doneUnsafe(deferred, Exit.fail(Cause.squash(executed.cause))) + Deferred.doneUnsafe(made.deferred, Exit.fail(Cause.squash(executed.cause))) } - return promise + return made.promise }) } diff --git a/packages/codemode/src/stdlib/array.ts b/packages/codemode/src/stdlib/array.ts index 3c3ebcb81eb..fed90d22cd6 100644 --- a/packages/codemode/src/stdlib/array.ts +++ b/packages/codemode/src/stdlib/array.ts @@ -26,9 +26,7 @@ const arrayLikeSource = (source: Value): { readonly length: number; readonly sou checkArrayLength(normalized) return { length: normalized, source } } - throw invalidData( - `Array.from expects an array, string, Map, Set, or array-like value, received ${describeValue(source)}.`, - ) + throw invalidData(`Array.from expects an iterable or array-like value, received ${describeValue(source)}.`) } const arrayFrom = (ctx: Interpreter, args: Array): Effect.Effect => { @@ -40,7 +38,9 @@ const arrayFrom = (ctx: Interpreter, args: Array): Effect.Effect = [] diff --git a/packages/codemode/src/stdlib/collections.ts b/packages/codemode/src/stdlib/collections.ts index 5234b4a9da3..f5ff48e0a1a 100644 --- a/packages/codemode/src/stdlib/collections.ts +++ b/packages/codemode/src/stdlib/collections.ts @@ -88,7 +88,7 @@ const constructMap = (ctx: Interpreter, init: Value, proto: Obj) => { return Effect.gen(function* () { const cursor = yield* ctx.iterate(init) if (cursor === undefined) { - throw typeError("new Map(...) expects an iterable of [key, value] pairs or no argument.") + throw typeError(`new Map(...) expects an iterable of [key, value] pairs, received ${describeValue(init)}.`) } while (true) { const step = yield* cursor.next @@ -112,7 +112,7 @@ const constructSet = (ctx: Interpreter, init: Value, proto: Obj) => { return Effect.gen(function* () { const cursor = yield* ctx.iterate(init) if (cursor === undefined) { - throw typeError("new Set(...) expects a synchronous iterable or no argument.") + throw typeError(`new Set(...) expects a synchronous iterable, received ${describeValue(init)}.`) } while (true) { const step = yield* cursor.next diff --git a/packages/codemode/test/errors.test.ts b/packages/codemode/test/errors.test.ts index d811dc43346..30b06ed2133 100644 --- a/packages/codemode/test/errors.test.ts +++ b/packages/codemode/test/errors.test.ts @@ -156,7 +156,7 @@ describe("host errors escaping built-ins", () => { test("an un-awaited rejection born inside promise machinery keeps its location in the warning", async () => { const result = await run(`Promise.all(1); return 1`) expect(result.ok && result.warnings?.[0]?.message).toEndWith( - "TypeError: Promise.all expects an array or other synchronous iterable. (line 1, col 1)", + "TypeError: Promise.all expects a synchronous iterable, received a number. (line 1, col 1)", ) }) diff --git a/packages/codemode/test/promise.test.ts b/packages/codemode/test/promise.test.ts index 74852d751ef..8f91a585f53 100644 --- a/packages/codemode/test/promise.test.ts +++ b/packages/codemode/test/promise.test.ts @@ -730,7 +730,7 @@ describe("Promise.all over arbitrary arrays", () => { test("a non-collection argument is a clear error", async () => { const diagnostic = await error(`return await Promise.all(42)`) - expect(diagnostic.message).toContain("Promise.all expects an array") + expect(diagnostic.message).toContain("Promise.all expects a synchronous iterable, received a number") }) test("exceeding maxToolCalls inside Promise.all is a ToolCallLimitExceeded diagnostic", async () => { @@ -1131,8 +1131,25 @@ describe("unsupported promise surface", () => { }) test("unknown Promise statics are not functions", async () => { - const diagnostic = await error(`return await Promise.withResolvers()`) - expect(diagnostic.message).toContain("Promise.withResolvers is not a function") + const diagnostic = await error(`return await Promise.try(() => 1)`) + expect(diagnostic.message).toContain("Promise.try is not a function") + }) +}) + +describe("Promise.withResolvers", () => { + test("returns a pending promise with resolvers that settle it once and adopt thenables", async () => { + expect( + await value(` + const first = Promise.withResolvers() + first.resolve(Promise.resolve("adopted")) + first.resolve("ignored") + const second = Promise.withResolvers() + second.reject(new Error("no")) + let caught + try { await second.promise } catch (e) { caught = e.message } + return [Object.keys(first), first.promise instanceof Promise, await first.promise, caught] + `), + ).toEqual([["promise", "resolve", "reject"], true, "adopted", "no"]) }) }) diff --git a/packages/codemode/test/stdlib.test.ts b/packages/codemode/test/stdlib.test.ts index 9af41ca852d..eba96d54c31 100644 --- a/packages/codemode/test/stdlib.test.ts +++ b/packages/codemode/test/stdlib.test.ts @@ -1293,6 +1293,13 @@ describe("Object.prototype.toString", () => { }) }) +describe("console.log of errors", () => { + test("prints name and message, nested too", async () => { + const result = await run(`console.log(new Error("boom"), { e: new RangeError("r") })`) + expect(result.logs).toEqual(['Error: boom {"e":RangeError: r}']) + }) +}) + describe("toLocaleString", () => { test("numbers and dates format as en-US in UTC; everything else falls back to toString", async () => { expect(