@opencode/codemode 2.2.0 → 2.2.2

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 (56) hide show
  1. package/README.md +33 -4
  2. package/dist/codemode.d.ts +9 -7
  3. package/dist/codemode.js +1 -1
  4. package/dist/data.d.ts +5 -4
  5. package/dist/data.js +7 -4
  6. package/dist/extension.d.ts +17 -4
  7. package/dist/extension.js +8 -0
  8. package/dist/interpreter/callback.d.ts +10 -10
  9. package/dist/interpreter/callback.js +43 -31
  10. package/dist/interpreter/errors.d.ts +1 -1
  11. package/dist/interpreter/errors.js +12 -15
  12. package/dist/interpreter/execute.js +59 -29
  13. package/dist/interpreter/extensions.d.ts +2 -2
  14. package/dist/interpreter/extensions.js +46 -18
  15. package/dist/interpreter/generators.js +162 -19
  16. package/dist/interpreter/globals.js +12 -9
  17. package/dist/interpreter/interpreter.d.ts +20 -13
  18. package/dist/interpreter/interpreter.js +1343 -1149
  19. package/dist/interpreter/intrinsics.js +1 -2
  20. package/dist/interpreter/model.d.ts +4 -7
  21. package/dist/interpreter/model.js +1 -11
  22. package/dist/interpreter/native.d.ts +7 -8
  23. package/dist/interpreter/native.js +4 -10
  24. package/dist/interpreter/objects.d.ts +47 -21
  25. package/dist/interpreter/objects.js +33 -12
  26. package/dist/interpreter/promises.d.ts +15 -53
  27. package/dist/interpreter/promises.js +226 -401
  28. package/dist/interpreter/runner.d.ts +188 -0
  29. package/dist/interpreter/runner.js +492 -0
  30. package/dist/stdlib/array.d.ts +3 -3
  31. package/dist/stdlib/array.js +106 -102
  32. package/dist/stdlib/bytes.d.ts +3 -3
  33. package/dist/stdlib/bytes.js +46 -41
  34. package/dist/stdlib/collections.d.ts +5 -5
  35. package/dist/stdlib/collections.js +160 -165
  36. package/dist/stdlib/date.d.ts +1 -1
  37. package/dist/stdlib/date.js +28 -20
  38. package/dist/stdlib/headers.d.ts +1 -1
  39. package/dist/stdlib/headers.js +14 -19
  40. package/dist/stdlib/iterator.d.ts +1 -1
  41. package/dist/stdlib/iterator.js +140 -122
  42. package/dist/stdlib/json.js +9 -12
  43. package/dist/stdlib/math.js +10 -10
  44. package/dist/stdlib/number.d.ts +2 -2
  45. package/dist/stdlib/object.d.ts +1 -1
  46. package/dist/stdlib/object.js +21 -22
  47. package/dist/stdlib/regexp.d.ts +1 -1
  48. package/dist/stdlib/regexp.js +2 -3
  49. package/dist/stdlib/string.d.ts +1 -1
  50. package/dist/stdlib/string.js +18 -20
  51. package/dist/stdlib/url.d.ts +5 -5
  52. package/dist/stdlib/url.js +32 -33
  53. package/dist/stdlib/value.d.ts +2 -2
  54. package/dist/stdlib/web.d.ts +2 -2
  55. package/dist/tool-schema.js +7 -3
  56. package/package.json +2 -2
@@ -1,406 +1,214 @@
1
- import { Cause, Deferred, Effect, Exit, Fiber, Scope } from "effect";
2
- import { MAX_PENDING_PROMISES } from "./limits.js";
3
- import { CallSite, Throw, rangeError, typeError } from "./model.js";
1
+ import { Throw, typeError } from "./model.js";
4
2
  import { Callable, define, get, hidden, Arr, Fn, Obj, PromiseObj, record } from "./objects.js";
5
3
  import { constructor, fn, methods, native, receiver, requiresNew } from "./native.js";
6
- import { createAggregateErrorValue, locate, materialize, normalizeError } from "./errors.js";
4
+ import { createAggregateErrorValue, materialize } from "./errors.js";
7
5
  import { describeValue, typeofValue } from "./references.js";
8
- import { applyCollectionCallback, isSupportedCallback } from "./callback.js";
6
+ import { isSupportedCallback } from "./callback.js";
7
+ import { Interruption, normal, Task } from "./runner.js";
9
8
  // A `resolve`/`reject` handed to an executor or thenable: calling it settles the capability.
10
- const capability = (ctx, name, settle) => fn(ctx.builtins, name, 1, (_, args) => {
11
- settle(args[0]);
12
- return undefined;
9
+ const resolvingFunctions = (ctx, resolving) => ({
10
+ resolve: fn(ctx.builtins, "resolve", 1, (_, args) => {
11
+ resolving.resolve(args[0]);
12
+ return undefined;
13
+ }),
14
+ reject: fn(ctx.builtins, "reject", 1, (_, args) => {
15
+ resolving.reject(new Throw(args[0]));
16
+ return undefined;
17
+ }),
13
18
  });
14
- // Program fibers that synchronous starts and handbacks may nest on the host stack. Deeper ones start and resume
15
- // through the scheduler, so deep recursion through async calls cannot overflow the host stack.
16
- const MAX_NESTING = 100;
17
19
  /**
18
- * The right to run program code. JavaScript runs one job at a time: code between two awaits finishes before another
19
- * job starts. Effect preempts a busy fiber so timeouts and host work still run, so only the fiber holding the turn may
20
- * run program code. A synchronous call into another fiber (an async function's body up to its first await, a
21
- * generator step) lends that fiber the turn and gets it back when the callee suspends or ends. An await gives the turn
22
- * to the next waiting job and queues to take it back. Work that only settles a promise or runs host code leaves
23
- * without it, so tool calls stay concurrent and resolvers settle in the call, as in JavaScript.
20
+ * NewPromiseCapability(%Promise%): a pending promise with the host functions that settle it once. A built-in's own
21
+ * failure that rejects it is located at `site`, the call that created it.
24
22
  */
25
- export class Turn {
26
- holder;
27
- // Callers waiting for a callee to hand the turn back, innermost last.
28
- handbacks = [];
29
- // Jobs waiting to take the turn, in the order they became ready.
30
- first;
31
- last;
32
- nesting = 0;
33
- // Take the turn when it is free, after the jobs already waiting.
34
- take = Effect.withFiber((fiber) => {
35
- if (this.holder === undefined) {
36
- this.holder = fiber;
37
- return Effect.void;
38
- }
39
- return Effect.callback((resume) => {
40
- const waiter = { fiber, resume, removed: false };
41
- if (this.last === undefined)
42
- this.first = waiter;
43
- else
44
- this.last.next = waiter;
45
- this.last = waiter;
46
- // Interrupted while waiting, or after the turn was granted but before it ran.
47
- return Effect.sync(() => {
48
- if (this.holder === fiber)
49
- this.release(fiber);
50
- else
51
- waiter.removed = true;
52
- });
53
- });
54
- });
55
- // Run `effect` holding the turn, as the program's main job does.
56
- hold(effect) {
57
- return Effect.withFiber((fiber) => Effect.andThen(this.take, effect).pipe(Effect.ensuring(Effect.sync(() => this.release(fiber)))));
23
+ export const capability = (ctx, site) => {
24
+ const promise = ctx.runner.newPromise();
25
+ return { promise, ...ctx.runner.resolving(promise, site) };
26
+ };
27
+ /** Settles `resolving` with a completion: a fulfillment value is resolved, so a thenable is adopted. */
28
+ const settleWith = (resolving, completion) => completion.ok ? resolving.resolve(completion.value) : resolving.reject(completion.error);
29
+ /**
30
+ * A promise reaction that calls program code: the handler runs as a job, and its result or failure settles the
31
+ * derived promise. A missing handler passes the outcome through.
32
+ */
33
+ const handlerReaction = (ctx, onFulfilled, onRejected, derived) => (settled) => {
34
+ const handler = settled.ok ? onFulfilled : onRejected;
35
+ if (handler === undefined || (!settled.ok && settled.error instanceof Interruption)) {
36
+ if (derived !== undefined)
37
+ settleWith(derived, settled);
38
+ return;
58
39
  }
59
- // Give up the turn, back to the innermost caller waiting for it or to the next waiting job.
60
- release(fiber) {
61
- if (this.holder !== fiber)
62
- return;
63
- const back = this.handbacks.pop();
64
- if (back !== undefined) {
65
- this.holder = back.fiber;
66
- this.handBack(back);
67
- return;
40
+ const argument = settled.ok ? settled.value : materialize(ctx, settled.error);
41
+ const body = function* () {
42
+ let result;
43
+ try {
44
+ result = yield* ctx.call(handler, undefined, [argument]);
68
45
  }
69
- let next = this.first;
70
- while (next !== undefined && next.removed)
71
- next = next.next;
72
- this.first = next?.next;
73
- if (this.first === undefined)
74
- this.last = undefined;
75
- this.holder = next?.fiber;
76
- // Resume in the scheduler, as a yield would: release can run inside another fiber's step.
77
- if (next !== undefined)
78
- next.fiber.currentDispatcher.scheduleTask(() => next.resume(Effect.void), 0);
79
- }
80
- // Wait without the turn, then queue for it like any job that became ready. An interrupted fiber stops without it.
81
- suspend(wait) {
82
- return Effect.uninterruptibleMask((restore) => Effect.withFiber((fiber) => {
83
- this.release(fiber);
84
- return Effect.flatMap(Effect.exit(restore(wait)), (exit) => Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause) ? exit : Effect.andThen(restore(this.take), exit));
85
- }));
86
- }
87
- // Wait without the turn and finish without it, for work that only settles a promise or runs host code.
88
- leave(wait) {
89
- return Effect.withFiber((fiber) => {
90
- this.release(fiber);
91
- return wait;
92
- });
93
- }
94
- // Run `start`, which wakes a fiber parked with `park`, and continue once it hands the turn back.
95
- handOff(start) {
96
- return Effect.withFiber((fiber) => {
97
- const back = { fiber, returned: false };
98
- this.handbacks.push(back);
99
- return Effect.andThen(this.nest(start), awaitHandback(back));
100
- });
101
- }
102
- // Wait without the turn for a caller to hand it over with `handOff`.
103
- park(wait) {
104
- return Effect.uninterruptibleMask((restore) => Effect.withFiber((fiber) => {
105
- this.release(fiber);
106
- // The wake runs inside the caller's step; when that is deep, yield so the body continues on its own stack.
107
- return Effect.tap(restore(wait), () => {
108
- this.holder = fiber;
109
- return this.nesting > MAX_NESTING ? Effect.yieldNow : Effect.void;
110
- });
111
- }));
112
- }
113
- // Fork a fiber that runs program code. It starts with the caller's turn, and the caller continues once the fiber
114
- // suspends or ends; the fiber gives up the turn whenever it ends.
115
- fork(effect, scope) {
116
- return Effect.withFiber((caller) => {
117
- const back = { fiber: caller, returned: false };
118
- this.handbacks.push(back);
119
- let started = false;
120
- const body = Effect.withFiber((fiber) => {
121
- started = true;
122
- this.holder = fiber;
123
- return effect;
124
- });
125
- const forked = this.nesting < MAX_NESTING
126
- ? this.nest(Effect.forkIn(body, scope, { startImmediately: true }))
127
- : Effect.forkIn(body, scope);
128
- return Effect.flatMap(forked, (fiber) => {
129
- fiber.addObserver(() => {
130
- if (started)
131
- return this.release(fiber);
132
- // Forked into a closing scope: it never took the turn, so the caller keeps it.
133
- const index = this.handbacks.lastIndexOf(back);
134
- if (index >= 0)
135
- this.handbacks.splice(index, 1);
136
- this.handBack(back);
137
- });
138
- // A callee that suspends without blocking hands the turn back before `forkIn` returns.
139
- return back.returned ? Effect.succeed(fiber) : Effect.as(awaitHandback(back), fiber);
140
- });
141
- });
142
- }
143
- // Resume a parked caller in the scheduler: resumed inline, it would run to its next await and queue before the callee
144
- // that just suspended has queued its own continuation.
145
- handBack(back) {
146
- back.returned = true;
147
- const resume = back.resume;
148
- if (resume !== undefined)
149
- back.fiber.currentDispatcher.scheduleTask(() => resume(Effect.void), 0);
150
- }
151
- // Run `effect`, which can run another program fiber inside the current step, counting the nesting.
152
- nest(effect) {
153
- return Effect.suspend(() => {
154
- this.nesting++;
155
- return Effect.ensuring(effect, Effect.sync(() => {
156
- this.nesting--;
157
- }));
158
- });
159
- }
160
- }
161
- // The check runs when the caller suspends: it can be preempted after deciding to wait.
162
- const awaitHandback = (back) => Effect.callback((resume) => {
163
- if (back.returned)
164
- resume(Effect.void);
165
- else
166
- back.resume = resume;
167
- });
168
- // Observation only controls rejection reporting; program completion interrupts all promise work.
169
- export class Pending {
170
- scope;
171
- proto;
172
- turn = new Turn();
173
- active = new Set();
174
- ids = new WeakMap();
175
- observed = new WeakSet();
176
- failures = new Map();
177
- nextID = 0;
178
- constructor(scope, proto) {
179
- this.scope = scope;
180
- this.proto = proto;
181
- }
182
- // Resolution bodies need the promise's own identity to reject `resolve(promise)` self-resolution.
183
- createWithSelf(body) {
184
- const self = {};
185
- return Effect.map(this.create(body(self)), (promise) => {
186
- self.promise = promise;
187
- return promise;
188
- });
189
- }
190
- // A promise whose work runs program code, on the turn. Host work that runs no program code uses `createHost`.
191
- create(effect) {
192
- return this.register(effect, (body) => this.turn.fork(body, this.scope));
193
- }
194
- // Starts now, without the turn, so host work stays concurrent and attaches to host promises at once.
195
- createHost(effect) {
196
- return this.register(effect, (body) => Effect.forkIn(body, this.scope, { startImmediately: true }));
197
- }
198
- register(effect, fork) {
199
- return Effect.flatMap(CallSite, (site) => {
200
- if (this.active.size >= MAX_PENDING_PROMISES) {
201
- throw rangeError(`Too many pending promises (limit ${MAX_PENDING_PROMISES}); await promises before creating more.`);
202
- }
203
- // Allocate before forking so reruns get distinct IDs and diagnostics retain creation order.
204
- const id = this.nextID++;
205
- const body = Effect.catchDefect(effect, (defect) => Effect.die(locate(defect, site.node)));
206
- return Effect.map(fork(body), (fiber) => {
207
- const promise = new PromiseObj(this.proto, fiber);
208
- this.active.add(promise);
209
- this.ids.set(promise, id);
210
- fiber.addObserver((exit) => {
211
- this.active.delete(promise);
212
- if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause) || this.observed.has(promise)) {
213
- this.ids.delete(promise);
214
- return;
215
- }
216
- const failure = normalizeError(Cause.squash(exit.cause));
217
- this.failures.set(id, {
218
- ...failure,
219
- message: `Unhandled rejection from an un-awaited promise: ${failure.message}`,
220
- });
221
- });
222
- return promise;
223
- });
224
- });
225
- }
226
- // Observation must be recorded when responsibility transfers, before the consumer fiber runs.
227
- markObserved(promise) {
228
- this.observed.add(promise);
229
- const id = this.ids.get(promise);
230
- this.ids.delete(promise);
231
- if (id !== undefined)
232
- this.failures.delete(id);
233
- }
234
- await(promise) {
235
- return Fiber.await(promise.fiber);
236
- }
237
- fork(effect) {
238
- return Effect.asVoid(this.turn.fork(effect, this.scope));
239
- }
240
- diagnostics() {
241
- return [...this.failures].sort(([left], [right]) => left - right).map(([, failure]) => failure);
242
- }
243
- // Re-check because a straggler can create promises before its interruption lands.
244
- interrupt() {
245
- const self = this;
246
- return Effect.gen(function* () {
247
- while (self.active.size > 0) {
248
- yield* Fiber.interruptAll([...self.active].map((promise) => promise.fiber));
249
- }
250
- return self.diagnostics();
251
- });
252
- }
253
- }
254
- export const resolvePromiseValue = (ctx, value, own) => {
255
- if (own?.promise !== undefined && value === own.promise) {
256
- return Effect.die(typeError("Chaining cycle detected: a promise cannot resolve with itself."));
257
- }
258
- if (value instanceof PromiseObj)
259
- return ctx.await(value);
260
- if (!(value instanceof Obj))
261
- return Effect.succeed(value);
262
- const then = get(value, "then");
263
- if (typeofValue(then) !== "function")
264
- return Effect.succeed(value);
265
- return Effect.gen(function* () {
266
- // Promise resolution invokes a thenable's method in a later job.
267
- yield* ctx.pending.turn.suspend(Effect.yieldNow);
268
- const deferred = Deferred.makeUnsafe();
269
- const resolve = capability(ctx, "resolve", (result) => Deferred.doneUnsafe(deferred, Exit.succeed(result)));
270
- const reject = capability(ctx, "reject", (reason) => Deferred.doneUnsafe(deferred, Exit.fail(new Throw(reason))));
271
- const executed = yield* Effect.exit(ctx.call(then, value, [resolve, reject]));
272
- if (!Exit.isSuccess(executed)) {
273
- if (Cause.hasInterruptsOnly(executed.cause))
274
- return yield* Effect.failCause(executed.cause);
275
- Deferred.doneUnsafe(deferred, Exit.fail(Cause.squash(executed.cause)));
46
+ catch (error) {
47
+ derived?.reject(error);
48
+ return;
276
49
  }
277
- return yield* resolvePromiseValue(ctx, yield* ctx.pending.turn.leave(Deferred.await(deferred)), own);
278
- });
279
- };
280
- export const resolvePromise = (ctx, value) => {
281
- if (value instanceof PromiseObj)
282
- return Effect.succeed(value);
283
- return ctx.pending.createWithSelf((self) => resolvePromiseValue(ctx, value, self));
50
+ derived?.resolve(result);
51
+ };
52
+ return { task: new Task([{ body: body(), boundary: undefined }]), input: normal(undefined) };
284
53
  };
285
54
  const promiseStatics = ["all", "allSettled", "race", "any", "resolve", "reject", "withResolvers", "try"];
286
- const invokePromiseMethod = (ctx, name, args) => {
287
- if (name === "resolve") {
288
- return resolvePromise(ctx, args[0]);
289
- }
55
+ function* invokePromiseMethod(ctx, name, args, site) {
56
+ const runner = ctx.runner;
57
+ if (name === "resolve")
58
+ return runner.promiseResolve(args[0]);
290
59
  if (name === "reject") {
291
- return ctx.pending.create(Effect.fail(new Throw(args[0])));
60
+ const made = capability(ctx, site);
61
+ made.reject(new Throw(args[0]));
62
+ return made.promise;
292
63
  }
293
64
  if (name === "withResolvers") {
294
- return Effect.map(promiseCapability(ctx), (made) => record(ctx.builtins.Object, { promise: made.promise, resolve: made.resolve, reject: made.reject }));
65
+ const made = capability(ctx, site);
66
+ const functions = resolvingFunctions(ctx, made);
67
+ return record(ctx.builtins.Object, { promise: made.promise, resolve: functions.resolve, reject: functions.reject });
295
68
  }
296
69
  if (name === "try") {
297
70
  if (typeofValue(args[0]) !== "function") {
298
71
  throw typeError(`Promise.try expects a function, received ${describeValue(args[0])}.`);
299
72
  }
300
- return Effect.flatMap(Effect.exit(ctx.call(args[0], undefined, args.slice(1))), (called) => {
301
- if (Exit.isSuccess(called))
302
- return resolvePromise(ctx, called.value);
303
- if (Cause.hasInterruptsOnly(called.cause))
304
- return Effect.failCause(called.cause);
305
- return ctx.pending.create(Effect.fail(Cause.squash(called.cause)));
306
- });
73
+ const made = capability(ctx, site);
74
+ try {
75
+ made.resolve(yield* ctx.call(args[0], undefined, args.slice(1)));
76
+ }
77
+ catch (error) {
78
+ made.reject(error);
79
+ }
80
+ return made.promise;
307
81
  }
308
- return ctx.pending.create(Effect.gen(function* () {
309
- const cursor = yield* ctx.iterate(args[0]);
82
+ return yield* combinator(ctx, name, args[0], site);
83
+ }
84
+ // Promise.all, allSettled, race, and any: each element is resolved to a promise and observed through a reaction, so
85
+ // the result settles in the job where the deciding element's reaction runs, or at once for an empty input. A failure
86
+ // while iterating rejects the result.
87
+ function* combinator(ctx, name, iterable, site) {
88
+ const runner = ctx.runner;
89
+ const made = capability(ctx, site);
90
+ try {
91
+ const cursor = yield* ctx.iterate(iterable);
310
92
  if (cursor === undefined) {
311
- throw typeError(`Promise.${name} expects a synchronous iterable, received ${describeValue(args[0])}.`);
93
+ throw typeError(`Promise.${name} expects a synchronous iterable, received ${describeValue(iterable)}.`);
312
94
  }
313
- const items = [];
95
+ const values = [];
96
+ const reasons = [];
97
+ // Once the result settles early, the remaining members' reactions can do nothing: detach them so a member that
98
+ // stays pending for the rest of the program does not keep them.
99
+ const attached = [];
100
+ const decided = (settle) => {
101
+ settle();
102
+ for (const [item, reaction] of attached)
103
+ runner.detach(item, reaction);
104
+ };
105
+ let remaining = 1;
106
+ let index = 0;
107
+ const finish = () => {
108
+ if (--remaining > 0)
109
+ return;
110
+ if (name === "any") {
111
+ made.reject(new Throw(createAggregateErrorValue(ctx, reasons, "All promises were rejected")));
112
+ return;
113
+ }
114
+ made.resolve(new Arr(ctx.builtins.Array, values));
115
+ };
314
116
  while (true) {
315
- const step = yield* cursor.next;
117
+ const step = yield* cursor.next();
316
118
  if (step.done)
317
119
  break;
318
- const item = yield* resolvePromise(ctx, step.value);
319
- ctx.pending.markObserved(item);
320
- items.push(item);
321
- }
322
- if (name === "all") {
323
- return new Arr(ctx.builtins.Array, yield* settleAfterTurn(ctx, Effect.all(items.map((item) => Effect.flatten(ctx.pending.await(item))), { concurrency: "unbounded" })));
324
- }
325
- if (name === "allSettled") {
326
- return yield* ctx.pending.turn.suspend(Effect.gen(function* () {
327
- const outcomes = [];
328
- for (const item of items) {
329
- const exit = yield* ctx.pending.await(item);
330
- if (Exit.isSuccess(exit)) {
331
- outcomes.push(record(ctx.builtins.Object, { status: "fulfilled", value: exit.value }));
332
- continue;
333
- }
334
- if (Cause.hasInterruptsOnly(exit.cause))
335
- return yield* Effect.failCause(exit.cause);
336
- outcomes.push(record(ctx.builtins.Object, {
337
- status: "rejected",
338
- reason: materialize(ctx, Cause.squash(exit.cause)),
339
- }));
120
+ const item = runner.promiseResolve(step.value);
121
+ const at = index++;
122
+ values.push(undefined);
123
+ reasons.push(undefined);
124
+ remaining++;
125
+ let called = false;
126
+ const reaction = (settled) => {
127
+ if (called)
128
+ return;
129
+ called = true;
130
+ if (name === "race" || (!settled.ok && settled.error instanceof Interruption)) {
131
+ return decided(() => settleWith(made, settled));
132
+ }
133
+ if (name === "all") {
134
+ if (!settled.ok)
135
+ return decided(() => made.reject(settled.error));
136
+ values[at] = settled.value;
137
+ return finish();
138
+ }
139
+ if (name === "any") {
140
+ if (settled.ok)
141
+ return decided(() => made.resolve(settled.value));
142
+ reasons[at] = materialize(ctx, settled.error);
143
+ return finish();
340
144
  }
341
- yield* Effect.yieldNow;
342
- return new Arr(ctx.builtins.Array, outcomes);
343
- }));
145
+ values[at] = settled.ok
146
+ ? record(ctx.builtins.Object, { status: "fulfilled", value: settled.value })
147
+ : record(ctx.builtins.Object, { status: "rejected", reason: materialize(ctx, settled.error) });
148
+ finish();
149
+ };
150
+ attached.push([item, reaction]);
151
+ runner.then(item, reaction);
344
152
  }
345
- if (name === "race") {
346
- if (items.length === 0) {
347
- throw typeError("Promise.race([]) would never settle; provide at least one promise or value.");
348
- }
349
- return yield* settleAfterTurn(ctx, Effect.flatten(Effect.raceAll(items.map((item) => ctx.pending.await(item)))));
153
+ if (name === "race" && index === 0) {
154
+ throw typeError("Promise.race([]) would never settle; provide at least one promise or value.");
350
155
  }
351
- const flipped = items.map((item) => Effect.flatMap(ctx.pending.await(item), (exit) => {
352
- if (Exit.isSuccess(exit))
353
- return Effect.fail(new PromiseAnyFulfilled(exit.value));
354
- if (Cause.hasInterruptsOnly(exit.cause))
355
- return Effect.failCause(exit.cause);
356
- return Effect.succeed(materialize(ctx, Cause.squash(exit.cause)));
357
- }));
358
- return yield* settleAfterTurn(ctx, Effect.all(flipped, { concurrency: "unbounded" }).pipe(Effect.flatMap((reasons) => Effect.fail(new Throw(createAggregateErrorValue(ctx, reasons, "All promises were rejected")))), Effect.catch((error) => error instanceof PromiseAnyFulfilled ? Effect.succeed(error.value) : Effect.fail(error))));
359
- }));
360
- };
361
- const instanceMethod = (ctx, name, thisValue, args) => {
156
+ finish();
157
+ }
158
+ catch (error) {
159
+ made.reject(error);
160
+ }
161
+ return made.promise;
162
+ }
163
+ const instanceMethod = (ctx, name, thisValue, args, site) => {
362
164
  const method = `Promise.prototype.${name}`;
363
165
  const promise = receiver(PromiseObj, thisValue, method);
364
- ctx.pending.markObserved(promise);
365
- if (name === "finally") {
366
- return chainFinally(ctx, promise, reactionHandler(args[0], method), method);
367
- }
166
+ if (name === "finally")
167
+ return chainFinally(ctx, promise, reactionHandler(args[0], method), site);
368
168
  const onFulfilled = name === "then" ? reactionHandler(args[0], method) : undefined;
369
169
  const onRejected = reactionHandler(name === "then" ? args[1] : args[0], method);
370
- return chainReaction(ctx, promise, onFulfilled, onRejected, method);
170
+ const made = capability(ctx, site);
171
+ ctx.runner.then(promise, handlerReaction(ctx, onFulfilled, onRejected, made));
172
+ return made.promise;
371
173
  };
372
- /** NewPromiseCapability: a pending promise with the resolve/reject callables that settle it exactly once. */
373
- const promiseCapability = (ctx) => Effect.gen(function* () {
374
- const deferred = Deferred.makeUnsafe();
375
- const promise = yield* ctx.pending.createWithSelf((self) => Effect.flatMap(ctx.pending.turn.leave(Deferred.await(deferred)), (value) => resolvePromiseValue(ctx, value, self)));
376
- const resolve = capability(ctx, "resolve", (value) => Deferred.doneUnsafe(deferred, Exit.succeed(value)));
377
- const reject = capability(ctx, "reject", (value) => Deferred.doneUnsafe(deferred, Exit.fail(new Throw(value))));
378
- return { promise, resolve, reject, deferred };
379
- });
380
- const constructPromise = (ctx, executor) => {
381
- if (!(executor instanceof Fn)) {
382
- throw typeError("new Promise(...) expects an executor function (e.g. new Promise((resolve, reject) => { ... })).");
383
- }
384
- return Effect.gen(function* () {
385
- const made = yield* promiseCapability(ctx);
386
- const executed = yield* Effect.exit(ctx.call(executor, undefined, [made.resolve, made.reject]));
387
- if (!Exit.isSuccess(executed)) {
388
- if (Cause.hasInterruptsOnly(executed.cause))
389
- return yield* Effect.failCause(executed.cause);
390
- Deferred.doneUnsafe(made.deferred, Exit.fail(Cause.squash(executed.cause)));
391
- }
174
+ // Promise.prototype.finally: the cleanup runs as a reaction, then the original outcome passes through once the
175
+ // cleanup's own result settles; a failing cleanup wins.
176
+ const chainFinally = (ctx, source, cleanup, site) => {
177
+ const runner = ctx.runner;
178
+ const made = capability(ctx, site);
179
+ if (cleanup === undefined) {
180
+ runner.then(source, (settled) => settleWith(made, settled));
392
181
  return made.promise;
182
+ }
183
+ runner.then(source, (settled) => {
184
+ if (!settled.ok && settled.error instanceof Interruption)
185
+ return made.reject(settled.error);
186
+ const body = function* () {
187
+ let result;
188
+ try {
189
+ result = yield* ctx.call(cleanup, undefined, []);
190
+ }
191
+ catch (error) {
192
+ made.reject(error);
193
+ return;
194
+ }
195
+ let after;
196
+ try {
197
+ after = runner.promiseResolve(result);
198
+ }
199
+ catch (error) {
200
+ made.reject(error);
201
+ return;
202
+ }
203
+ // The spec chains `then(valueThunk)` onto the cleanup's promise: one more job before the outcome passes.
204
+ const derived = capability(ctx, site);
205
+ runner.then(after, (cleaned) => (cleaned.ok ? derived.resolve(undefined) : derived.reject(cleaned.error)));
206
+ runner.then(derived.promise, (cleaned) => settleWith(made, cleaned.ok ? settled : cleaned));
207
+ };
208
+ return { task: new Task([{ body: body(), boundary: undefined }]), input: normal(undefined) };
393
209
  });
210
+ return made.promise;
394
211
  };
395
- // Settle one reaction turn after the deciding member, after its existing reactions. That reaction is a job: it queues
396
- // for the turn behind the jobs ready before it and settles holding it.
397
- const settleAfterTurn = (ctx, body) => Effect.flatten(ctx.pending.turn.suspend(Effect.flatMap(Effect.exit(body), (exit) => Effect.as(Effect.yieldNow, exit))));
398
- class PromiseAnyFulfilled {
399
- value;
400
- constructor(value) {
401
- this.value = value;
402
- }
403
- }
404
212
  const reactionHandler = (value, method) => {
405
213
  if (isSupportedCallback(value))
406
214
  return value;
@@ -409,37 +217,51 @@ const reactionHandler = (value, method) => {
409
217
  }
410
218
  return undefined;
411
219
  };
412
- // Teardown bypasses handlers; settled reactions yield once so handlers never run inline.
413
- const reactionExit = (ctx, source) => ctx.pending.turn.suspend(Effect.gen(function* () {
414
- const exit = yield* ctx.pending.await(source);
415
- if (!Exit.isSuccess(exit) && Cause.hasInterruptsOnly(exit.cause))
416
- return yield* Effect.failCause(exit.cause);
417
- yield* Effect.yieldNow;
418
- return exit;
419
- }));
420
- const chainReaction = (ctx, source, onFulfilled, onRejected, method) => {
421
- return ctx.pending.createWithSelf((self) => Effect.gen(function* () {
422
- const exit = yield* reactionExit(ctx, source);
423
- const handler = Exit.isSuccess(exit) ? onFulfilled : onRejected;
424
- if (handler === undefined)
425
- return yield* exit;
426
- const input = Exit.isSuccess(exit) ? exit.value : materialize(ctx, Cause.squash(exit.cause));
427
- const result = yield* applyCollectionCallback(ctx, handler, method)([input]);
428
- return yield* resolvePromiseValue(ctx, result, self);
429
- }));
430
- };
431
- const chainFinally = (ctx, source, cleanup, method) => ctx.pending.create(Effect.gen(function* () {
432
- const exit = yield* reactionExit(ctx, source);
433
- if (cleanup !== undefined) {
434
- const result = yield* applyCollectionCallback(ctx, cleanup, method)([]);
435
- const intermediate = yield* ctx.pending.create(Effect.gen(function* () {
436
- yield* ctx.await(yield* resolvePromise(ctx, result));
437
- return yield* exit;
438
- }));
439
- return yield* ctx.await(intermediate);
220
+ function* constructPromise(ctx, executor, site) {
221
+ if (!(executor instanceof Fn)) {
222
+ throw typeError("new Promise(...) expects an executor function (e.g. new Promise((resolve, reject) => { ... })).");
223
+ }
224
+ const made = capability(ctx, site);
225
+ const functions = resolvingFunctions(ctx, made);
226
+ try {
227
+ yield* ctx.call(executor, undefined, [functions.resolve, functions.reject]);
228
+ }
229
+ catch (error) {
230
+ made.reject(error);
440
231
  }
441
- return yield* exit;
442
- }));
232
+ return made.promise;
233
+ }
234
+ const promiseLikePrototypes = new WeakMap();
235
+ /**
236
+ * Lets a synchronous object result also be awaited or chained like a Promise. It inherits non-enumerable
237
+ * then/catch/finally that settle with a plain copy, so data views never show them and awaiting does not recurse.
238
+ */
239
+ export const promiseLike = (ctx, value) => {
240
+ if (!(value instanceof Obj) || value.proto !== ctx.builtins.Object)
241
+ return value;
242
+ value.proto = promiseLikePrototype(ctx);
243
+ return value;
244
+ };
245
+ const promiseLikePrototype = (ctx) => {
246
+ const cached = promiseLikePrototypes.get(ctx);
247
+ if (cached !== undefined)
248
+ return cached;
249
+ const proto = new Obj(ctx.builtins.Object);
250
+ const settled = (thisValue, name) => {
251
+ const source = receiver(Obj, thisValue, name);
252
+ const copy = new Obj(ctx.builtins.Object);
253
+ for (const [key, slot] of source.props)
254
+ copy.props.set(key, { ...slot });
255
+ return ctx.runner.promiseResolve(copy);
256
+ };
257
+ methods(ctx.builtins, proto, ["then", "catch", "finally"].map((name) => [
258
+ name,
259
+ name === "then" ? 2 : 1,
260
+ (thisValue, args, site) => instanceMethod(ctx, name, settled(thisValue, name), args, site),
261
+ ]));
262
+ promiseLikePrototypes.set(ctx, proto);
263
+ return proto;
264
+ };
443
265
  export const promiseGlobal = (ctx) => {
444
266
  const builtins = ctx.builtins;
445
267
  const proto = builtins.Promise;
@@ -447,21 +269,24 @@ export const promiseGlobal = (ctx) => {
447
269
  name: "Promise",
448
270
  length: 1,
449
271
  call: requiresNew("Promise"),
450
- construct: (args) => constructPromise(ctx, args[0]),
272
+ construct: (args, _, site) => constructPromise(ctx, args[0], site),
451
273
  });
452
274
  // Combinators are not callbacks: `[p].map(Promise.resolve)` must ask for an arrow function.
453
275
  for (const name of promiseStatics) {
454
276
  define(promise, name, native(builtins, {
455
277
  name,
456
278
  length: 1,
457
- call: (_, args) => invokePromiseMethod(ctx, name, args),
279
+ call: (_, args, site) => invokePromiseMethod(ctx, name, args, site),
458
280
  callback: false,
459
281
  }), hidden);
460
282
  }
461
283
  methods(builtins, proto, [
462
- ["then", 2, (thisValue, args) => instanceMethod(ctx, "then", thisValue, args)],
463
- ["catch", 1, (thisValue, args) => instanceMethod(ctx, "catch", thisValue, args)],
464
- ["finally", 1, (thisValue, args) => instanceMethod(ctx, "finally", thisValue, args)],
284
+ ["then", 2, (thisValue, args, site) => instanceMethod(ctx, "then", thisValue, args, site)],
285
+ ["catch", 1, (thisValue, args, site) => instanceMethod(ctx, "catch", thisValue, args, site)],
286
+ ["finally", 1, (thisValue, args, site) => instanceMethod(ctx, "finally", thisValue, args, site)],
465
287
  ]);
288
+ const then = get(proto, "then");
289
+ if (then instanceof Callable)
290
+ ctx.runner.intrinsicThen = then;
466
291
  return promise;
467
292
  };