async-browser-context 0.2.4 → 0.3.1

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 (140) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +45 -30
  3. package/dist/babel/async-generator-helpers.d.ts +6 -6
  4. package/dist/babel/async-generator-helpers.d.ts.map +1 -1
  5. package/dist/babel/async-generator-helpers.js +33 -22
  6. package/dist/babel/async-generator-helpers.js.map +1 -1
  7. package/dist/babel/async-generator-resources.d.ts +14 -0
  8. package/dist/babel/async-generator-resources.d.ts.map +1 -0
  9. package/dist/babel/async-generator-resources.js +38 -0
  10. package/dist/babel/async-generator-resources.js.map +1 -0
  11. package/dist/babel/bind-generators.d.ts +1 -1
  12. package/dist/babel/bind-generators.d.ts.map +1 -1
  13. package/dist/babel/bind-generators.js +88 -44
  14. package/dist/babel/bind-generators.js.map +1 -1
  15. package/dist/babel/name-coroutines.d.ts +14 -8
  16. package/dist/babel/name-coroutines.d.ts.map +1 -1
  17. package/dist/babel/name-coroutines.js +160 -39
  18. package/dist/babel/name-coroutines.js.map +1 -1
  19. package/dist/babel/preset.d.ts +24 -13
  20. package/dist/babel/preset.d.ts.map +1 -1
  21. package/dist/babel/preset.js +37 -9
  22. package/dist/babel/preset.js.map +1 -1
  23. package/dist/babel/runtime-calls.d.ts +22 -0
  24. package/dist/babel/runtime-calls.d.ts.map +1 -0
  25. package/dist/babel/runtime-calls.js +69 -0
  26. package/dist/babel/runtime-calls.js.map +1 -0
  27. package/dist/babel/skip-runtime.d.ts +18 -11
  28. package/dist/babel/skip-runtime.d.ts.map +1 -1
  29. package/dist/babel/skip-runtime.js +52 -16
  30. package/dist/babel/skip-runtime.js.map +1 -1
  31. package/dist/babel/static-members.d.ts +4 -0
  32. package/dist/babel/static-members.d.ts.map +1 -0
  33. package/dist/babel/static-members.js +112 -0
  34. package/dist/babel/static-members.js.map +1 -0
  35. package/dist/core/async-generator.d.ts +26 -8
  36. package/dist/core/async-generator.d.ts.map +1 -1
  37. package/dist/core/async-generator.js +162 -44
  38. package/dist/core/async-generator.js.map +1 -1
  39. package/dist/core/async-local-storage.d.ts +3 -0
  40. package/dist/core/async-local-storage.d.ts.map +1 -1
  41. package/dist/core/async-local-storage.js +3 -0
  42. package/dist/core/async-local-storage.js.map +1 -1
  43. package/dist/core/callback-hook.d.ts +3 -3
  44. package/dist/core/coroutine.d.ts +6 -2
  45. package/dist/core/coroutine.d.ts.map +1 -1
  46. package/dist/core/coroutine.js +35 -21
  47. package/dist/core/coroutine.js.map +1 -1
  48. package/dist/core/function-name.d.ts +9 -0
  49. package/dist/core/function-name.d.ts.map +1 -0
  50. package/dist/core/function-name.js +12 -0
  51. package/dist/core/function-name.js.map +1 -0
  52. package/dist/core/hooks.d.ts +2 -1
  53. package/dist/core/hooks.d.ts.map +1 -1
  54. package/dist/core/hooks.js +21 -6
  55. package/dist/core/hooks.js.map +1 -1
  56. package/dist/core/snapshot.d.ts +2 -1
  57. package/dist/core/snapshot.d.ts.map +1 -1
  58. package/dist/core/snapshot.js +7 -3
  59. package/dist/core/snapshot.js.map +1 -1
  60. package/dist/core/store.d.ts +28 -0
  61. package/dist/core/store.d.ts.map +1 -1
  62. package/dist/core/store.js +90 -20
  63. package/dist/core/store.js.map +1 -1
  64. package/dist/core/variable.d.ts +2 -1
  65. package/dist/core/variable.d.ts.map +1 -1
  66. package/dist/core/variable.js +5 -2
  67. package/dist/core/variable.js.map +1 -1
  68. package/dist/node/index.d.ts +10 -4
  69. package/dist/node/index.d.ts.map +1 -1
  70. package/dist/node/index.js +51 -16
  71. package/dist/node/index.js.map +1 -1
  72. package/dist/node/runtime.d.ts +7 -6
  73. package/dist/node/runtime.d.ts.map +1 -1
  74. package/dist/node/runtime.js +29 -16
  75. package/dist/node/runtime.js.map +1 -1
  76. package/dist/opentelemetry/context-manager.d.ts.map +1 -1
  77. package/dist/opentelemetry/context-manager.js +172 -13
  78. package/dist/opentelemetry/context-manager.js.map +1 -1
  79. package/dist/patches/callbacks.d.ts.map +1 -1
  80. package/dist/patches/callbacks.js +84 -29
  81. package/dist/patches/callbacks.js.map +1 -1
  82. package/dist/patches/events.d.ts.map +1 -1
  83. package/dist/patches/events.js +203 -91
  84. package/dist/patches/events.js.map +1 -1
  85. package/dist/patches/handler-interfaces.d.ts +4 -3
  86. package/dist/patches/handler-interfaces.d.ts.map +1 -1
  87. package/dist/patches/handler-interfaces.js +7 -5
  88. package/dist/patches/handler-interfaces.js.map +1 -1
  89. package/dist/patches/promise.d.ts +3 -0
  90. package/dist/patches/promise.d.ts.map +1 -1
  91. package/dist/patches/promise.js +13 -5
  92. package/dist/patches/promise.js.map +1 -1
  93. package/dist/patches/streams.d.ts.map +1 -1
  94. package/dist/patches/streams.js +36 -16
  95. package/dist/patches/streams.js.map +1 -1
  96. package/dist/patches/timers.d.ts.map +1 -1
  97. package/dist/patches/timers.js +17 -5
  98. package/dist/patches/timers.js.map +1 -1
  99. package/dist/patches/to-string.d.ts +4 -0
  100. package/dist/patches/to-string.d.ts.map +1 -1
  101. package/dist/patches/to-string.js +12 -6
  102. package/dist/patches/to-string.js.map +1 -1
  103. package/dist/runtime.d.ts +3 -3
  104. package/dist/runtime.d.ts.map +1 -1
  105. package/dist/runtime.js +3 -3
  106. package/dist/runtime.js.map +1 -1
  107. package/dist/vite/plugin.d.ts +7 -2
  108. package/dist/vite/plugin.d.ts.map +1 -1
  109. package/dist/vite/plugin.js +30 -6
  110. package/dist/vite/plugin.js.map +1 -1
  111. package/package.json +52 -25
  112. package/src/babel/async-generator-helpers.ts +34 -23
  113. package/src/babel/async-generator-resources.ts +40 -0
  114. package/src/babel/bind-generators.ts +91 -47
  115. package/src/babel/name-coroutines.ts +170 -41
  116. package/src/babel/preset.ts +47 -15
  117. package/src/babel/runtime-calls.ts +73 -0
  118. package/src/babel/skip-runtime.ts +58 -18
  119. package/src/babel/static-members.ts +117 -0
  120. package/src/core/async-generator.ts +169 -46
  121. package/src/core/async-local-storage.ts +3 -0
  122. package/src/core/callback-hook.ts +3 -3
  123. package/src/core/coroutine.ts +35 -21
  124. package/src/core/function-name.ts +11 -0
  125. package/src/core/hooks.ts +23 -6
  126. package/src/core/snapshot.ts +8 -3
  127. package/src/core/store.ts +107 -21
  128. package/src/core/variable.ts +6 -2
  129. package/src/node/index.ts +62 -19
  130. package/src/node/runtime.ts +33 -15
  131. package/src/opentelemetry/context-manager.ts +188 -13
  132. package/src/patches/callbacks.ts +87 -30
  133. package/src/patches/events.ts +249 -103
  134. package/src/patches/handler-interfaces.ts +7 -5
  135. package/src/patches/promise.ts +17 -13
  136. package/src/patches/streams.ts +36 -16
  137. package/src/patches/timers.ts +17 -5
  138. package/src/patches/to-string.ts +12 -6
  139. package/src/runtime.ts +3 -3
  140. package/src/vite/plugin.ts +38 -8
package/src/core/store.ts CHANGED
@@ -19,8 +19,10 @@ export interface Frame {
19
19
  /** The native functions that the runtime uses. The store records them before a patch replaces them. */
20
20
  export interface Intrinsics {
21
21
  readonly Promise : PromiseConstructor;
22
+ /** The patch of version 0.3 does not use it. An older copy of the library that shares the store can use it. */
22
23
  readonly promiseThen : typeof Promise.prototype.then;
23
24
  readonly promiseResolve : <T>(value : T) => Promise<Awaited<T>>;
25
+ /** The patch of version 0.3 does not use it. An older copy of the library that shares the store can use it. */
24
26
  readonly functionToString : () => string;
25
27
  }
26
28
 
@@ -42,6 +44,18 @@ export interface ContextStore {
42
44
  hooks? : readonly HookEntry[] | undefined;
43
45
  /** `true` while a hook operates. Callbacks that start in a hook do not start the hook methods. */
44
46
  inHook? : boolean | undefined;
47
+ /**
48
+ * The patches that a copy of version 0.1 installed before a newer copy loaded. Version 0.1
49
+ * has no callback hooks, so the callbacks of these patches do not start the hooks. Only a
50
+ * store that a copy of version 0.1 made has this property.
51
+ */
52
+ oldCopyPatches? : ReadonlySet<string> | undefined;
53
+ /**
54
+ * The frame that stays current between tasks: the root frame, or the frame of a top-level
55
+ * `enterWith()` (a default store). The event patch handles it as the root frame (rule C13).
56
+ * The store of an older copy of the library does not have this property.
57
+ */
58
+ idle? : Frame | undefined;
45
59
  }
46
60
 
47
61
  /** The methods of a callback hook. The public type is `CallbackHook` in `hooks.ts`. */
@@ -75,22 +89,54 @@ function createStore() : ContextStore {
75
89
  // Own properties from the start: each callback reads `hooks`, and the read of an own property is faster
76
90
  hooks : undefined,
77
91
  inHook : false,
92
+ idle : root,
78
93
  };
79
94
  }
80
95
 
81
- function getOrCreateStore() : ContextStore {
82
- const holder = globalThis as unknown as Record<symbol, ContextStore | undefined>;
83
- const existing = holder[STORE_KEY];
96
+ /**
97
+ * This function gives the store of the global object `holder`. If `holder` has no store, the
98
+ * function makes one, and adds it as a property that code cannot change or remove.
99
+ *
100
+ * @internal
101
+ */
102
+ export function getOrCreateStore(holder : object) : ContextStore {
103
+ const existing = (holder as Record<symbol, ContextStore | undefined>)[STORE_KEY];
84
104
  if (existing !== undefined) {
105
+ // The stores of version 0.2 and later have the own property hooks from the start. Version 0.1 has no hooks.
106
+ if (!Object.prototype.hasOwnProperty.call(existing, "hooks") && existing.oldCopyPatches === undefined) {
107
+ existing.oldCopyPatches = new Set(existing.patches);
108
+ }
85
109
  return existing;
86
110
  }
87
111
  const created = createStore();
88
- Object.defineProperty(globalThis, STORE_KEY, { value : created, writable : false, enumerable : false, configurable : false });
112
+ Object.defineProperty(holder, STORE_KEY, { value : created, writable : false, enumerable : false, configurable : false });
89
113
  return created;
90
114
  }
91
115
 
92
116
  /** The store of this global object. */
93
- export const store : ContextStore = getOrCreateStore();
117
+ export const store : ContextStore = getOrCreateStore(globalThis);
118
+
119
+ /** `true` while a record of the idle frame waits in the microtask queue. */
120
+ let idleRecordQueued = false;
121
+
122
+ /**
123
+ * This function records `store.idle` in the next microtask. `enterWith()` starts it, because a
124
+ * top-level `enterWith()` changes the frame that stays current between tasks. A microtask
125
+ * operates when the stack is empty, after each wrapper set its previous frame again. The callback
126
+ * goes to the native `then`, so no wrapper sets a frame for it.
127
+ */
128
+ export function recordIdleFrame() : void {
129
+ // Stryker disable next-line ConditionalExpression,BlockStatement: a second record in the same turn records the same frame, so the flag only prevents more microtasks
130
+ if (idleRecordQueued) {
131
+ return;
132
+ }
133
+ // Stryker disable next-line BooleanLiteral: a second record in the same turn records the same frame, so the flag only prevents more microtasks
134
+ idleRecordQueued = true;
135
+ Reflect.apply(store.intrinsics.promiseThen, store.intrinsics.promiseResolve(undefined), [() : void => {
136
+ idleRecordQueued = false;
137
+ store.idle = store.current;
138
+ }]);
139
+ }
94
140
 
95
141
  /** This function makes `frame` the current frame. It gives the frame that was current before. */
96
142
  export function enter(frame : Frame) : Frame {
@@ -115,7 +161,8 @@ class ValueFrame implements Frame {
115
161
  /**
116
162
  * The result of the last search for another variable from this frame. A
117
163
  * frame does not change, so the result stays correct. The cached value
118
- * comes from a parent frame, so the cache keeps no other object in memory.
164
+ * comes from a parent frame. The cache also keeps the last variable of a
165
+ * search, so a frame can keep one more variable in memory.
119
166
  */
120
167
  #cachedVariable : object | undefined = undefined;
121
168
  #cachedValue : unknown = undefined;
@@ -145,6 +192,16 @@ class ValueFrame implements Frame {
145
192
  return value;
146
193
  }
147
194
 
195
+ /**
196
+ * This method makes a frame that sets `variable`. When `parent` sets the same variable,
197
+ * the new frame replaces it: the new frame has the parent of `parent`. A search gives the
198
+ * same values. Many uses of enterWith() in one context thus do not make a long chain.
199
+ */
200
+ static create(parent : Frame, variable : object, value : unknown) : ValueFrame {
201
+ const base = #variable in parent && parent.#variable === variable ? parent.parent : parent;
202
+ return new ValueFrame(base, variable, value);
203
+ }
204
+
148
205
  static #search(start : Frame | null, variable : object) : unknown {
149
206
  for (let frame = start; frame !== null; frame = frame.parent) {
150
207
  if (#variable in frame && frame.#variable === variable) {
@@ -157,7 +214,7 @@ class ValueFrame implements Frame {
157
214
 
158
215
  /** This function makes a new frame that has `parent` as its parent and sets `variable` to `value`. */
159
216
  export function createFrame(parent : Frame, variable : object, value : unknown) : Frame {
160
- return new ValueFrame(parent, variable, value);
217
+ return ValueFrame.create(parent, variable, value);
161
218
  }
162
219
 
163
220
  /** This function gives the value of `variable` in `frame`, or `NOT_FOUND` if no frame sets it. */
@@ -167,12 +224,16 @@ export function findValue(frame : Frame, variable : object) : unknown {
167
224
 
168
225
  /** This function gives the error of a hook to the host. A hook error does not stop the callback. */
169
226
  function reportHookError(error : unknown) : void {
170
- const report = (globalThis as { reportError? : unknown }).reportError;
171
- if (typeof report === "function") {
172
- (report as (error : unknown) => void)(error);
173
- return;
227
+ try {
228
+ const report = (globalThis as { reportError? : unknown }).reportError;
229
+ if (typeof report === "function") {
230
+ Reflect.apply(report, globalThis, [error]);
231
+ return;
232
+ }
233
+ console.error(error);
234
+ } catch {
235
+ // The report itself failed. The callback must operate, so the error stops here.
174
236
  }
175
- console.error(error);
176
237
  }
177
238
 
178
239
  /**
@@ -187,12 +248,12 @@ function callHooks(hooks : readonly HookEntry[], phase : "before" | "after", cal
187
248
  const count = hooks.length;
188
249
  for (let step = 0; step < count; step++) {
189
250
  const { hook } = hooks[phase === "before" ? step : count - 1 - step] as HookEntry;
190
- const method = hook[phase];
191
- if (typeof method !== "function") {
192
- continue;
193
- }
194
251
  try {
195
- method.call(hook, callback, source);
252
+ // A getter of the method can also throw
253
+ const method = hook[phase];
254
+ if (typeof method === "function") {
255
+ Reflect.apply(method, hook, [callback, source]);
256
+ }
196
257
  } catch (error) {
197
258
  reportHookError(error);
198
259
  }
@@ -218,16 +279,32 @@ export function applyWithHooks<T, A extends unknown[], R>(
218
279
  args : A,
219
280
  ) : R {
220
281
  if (store.inHook === true) {
221
- return fn.apply(thisValue, args);
282
+ return Reflect.apply(fn, thisValue, args);
222
283
  }
223
284
  callHooks(hooks, "before", callback, source);
224
285
  try {
225
- return fn.apply(thisValue, args);
286
+ return Reflect.apply(fn, thisValue, args);
226
287
  } finally {
227
288
  callHooks(hooks, "after", callback, source);
228
289
  }
229
290
  }
230
291
 
292
+ /**
293
+ * This function starts `fn` as a callback that a hook registered: the hooks do not operate for
294
+ * it. `store.inHook` stays `true` while it operates. Thus the callbacks and the async functions
295
+ * that it starts or registers do not start the hooks either. A hook cannot start itself without
296
+ * end, also through a chain of callbacks.
297
+ */
298
+ export function applyQuietly<T, A extends unknown[], R>(fn : (this : T, ...args : A) => R, thisValue : T, args : A) : R {
299
+ const previous = store.inHook;
300
+ store.inHook = true;
301
+ try {
302
+ return Reflect.apply(fn, thisValue, args);
303
+ } finally {
304
+ store.inHook = previous;
305
+ }
306
+ }
307
+
231
308
  /*
232
309
  * Each wrapper has the name `asyncBrowserContextWrapper`. Profilers, stack
233
310
  * traces and the Long Animation Frames API show the static name of a
@@ -242,13 +319,18 @@ export function applyWithHooks<T, A extends unknown[], R>(
242
319
  * `fn`, for the callback hooks.
243
320
  */
244
321
  export function bindToFrame<T, A extends unknown[], R>(frame : Frame, fn : (this : T, ...args : A) => R, source : string) : (this : T, ...args : A) => R {
322
+ // A callback that a hook registers does not start the hooks, so a hook cannot start itself without end
323
+ const quiet = store.inHook === true;
245
324
  return function asyncBrowserContextWrapper(this : T, ...args : A) : R {
246
325
  const previous = store.current;
247
326
  store.current = frame;
248
327
  try {
328
+ if (quiet) {
329
+ return applyQuietly(fn, this, args);
330
+ }
249
331
  const hooks = store.hooks;
250
332
  if (hooks === undefined) {
251
- return fn.apply(this, args);
333
+ return Reflect.apply(fn, this, args);
252
334
  }
253
335
  return applyWithHooks(hooks, fn, source, fn, this, args);
254
336
  } finally {
@@ -263,13 +345,17 @@ export function bindToFrame<T, A extends unknown[], R>(frame : Frame, fn : (this
263
345
  * `bindToFrame` on the hot path.
264
346
  */
265
347
  export function bindOneArgument<T, A, R>(frame : Frame, fn : (this : T, argument : A) => R, source : string) : (this : T, argument : A) => R {
348
+ const quiet = store.inHook === true;
266
349
  return function asyncBrowserContextWrapper(this : T, argument : A) : R {
267
350
  const previous = store.current;
268
351
  store.current = frame;
269
352
  try {
353
+ if (quiet) {
354
+ return applyQuietly(fn, this, [argument]);
355
+ }
270
356
  const hooks = store.hooks;
271
357
  if (hooks === undefined) {
272
- return fn.call(this, argument);
358
+ return Reflect.apply(fn, this, [argument]);
273
359
  }
274
360
  return applyWithHooks(hooks, fn, source, fn, this, [argument]);
275
361
  } finally {
@@ -1,4 +1,4 @@
1
- import { createFrame, findValue, NOT_FOUND, store } from "./store.js";
1
+ import { createFrame, findValue, NOT_FOUND, recordIdleFrame, store } from "./store.js";
2
2
 
3
3
  /** The options of a `Variable`. */
4
4
  export interface VariableOptions<T> {
@@ -50,7 +50,8 @@ export class Variable<T> {
50
50
 
51
51
  /**
52
52
  * This method starts `fn` with `args` in a new context in which `get()`
53
- * gives `value`. After `fn` ends, also with an error, the previous context is
53
+ * gives `value`. As in the TC39 draft, `fn` gets `undefined` as its `this`
54
+ * value. After `fn` ends, also with an error, the previous context is
54
55
  * current again. The method gives the result of `fn`.
55
56
  */
56
57
  run<R, A extends unknown[]>(value : T, fn : (...args : A) => R, ...args : A) : R {
@@ -64,6 +65,8 @@ export class Variable<T> {
64
65
  }
65
66
  }
66
67
 
68
+ Object.defineProperty(Variable.prototype, Symbol.toStringTag, { value : "AsyncContext.Variable", configurable : true });
69
+
67
70
  /**
68
71
  * This function makes a new current frame in which `variable` has `value`.
69
72
  * The frame stays current until the code that controls the current step sets
@@ -73,4 +76,5 @@ export class Variable<T> {
73
76
  */
74
77
  export function enterValue<T>(variable : Variable<T>, value : T) : void {
75
78
  store.current = createFrame(store.current, variable, value);
79
+ recordIdleFrame();
76
80
  }
package/src/node/index.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * @packageDocumentation
9
9
  */
10
- import { AsyncLocalStorage as NodeAsyncLocalStorage } from "node:async_hooks";
10
+ import { AsyncLocalStorage as NodeAsyncLocalStorage, AsyncResource } from "node:async_hooks";
11
11
  import { assertCallbackHook, type CallbackHook } from "../core/callback-hook.js";
12
12
  import type { VariableOptions } from "../core/variable.js";
13
13
  import { createCompatibleStorage } from "./compatible-storage.js";
@@ -16,16 +16,27 @@ export type { AsyncLocalStorageOptions } from "../core/async-local-storage.js";
16
16
  export type { CallbackHook } from "../core/callback-hook.js";
17
17
  export type { VariableOptions } from "../core/variable.js";
18
18
 
19
- /** The value of a `Variable` in one context. The box tells "a value is set" apart from `undefined`. */
20
- interface Box<T> {
21
- readonly value : T;
19
+ /**
20
+ * One value of one variable in a context, and the values of the parent context. The chain
21
+ * tells "a value is set" apart from `undefined`.
22
+ */
23
+ interface Entry {
24
+ readonly variable : object;
25
+ readonly value : unknown;
26
+ readonly parent : Entry | undefined;
22
27
  }
23
28
 
29
+ /**
30
+ * One native storage for all variables. Its store is the chain of the values of the current
31
+ * context. On Node.js 22, each native storage that operated stays in a global list of
32
+ * async_hooks, and each new async resource examines the list. One storage keeps that list short.
33
+ */
34
+ const values = new NodeAsyncLocalStorage<Entry>();
35
+
24
36
  /** The `AsyncContext.Variable` of the TC39 proposal, on the native `AsyncLocalStorage`. */
25
37
  export class Variable<T> {
26
38
  readonly #name : string;
27
39
  readonly #defaultValue : T | undefined;
28
- readonly #storage : NodeAsyncLocalStorage<Box<T>> = new NodeAsyncLocalStorage<Box<T>>();
29
40
 
30
41
  constructor(options : VariableOptions<T> = {}) {
31
42
  this.#name = options.name === undefined ? "" : String(options.name);
@@ -39,23 +50,41 @@ export class Variable<T> {
39
50
 
40
51
  /** This method gives the value of this variable in the current context, or the default value. */
41
52
  get() : T | undefined {
42
- const box = this.#storage.getStore();
43
- return box === undefined ? this.#defaultValue : box.value;
53
+ for (let entry = values.getStore(); entry !== undefined; entry = entry.parent) {
54
+ if (entry.variable === this) {
55
+ return entry.value as T;
56
+ }
57
+ }
58
+ return this.#defaultValue;
44
59
  }
45
60
 
46
- /** This method starts `fn` with `args` in a new context in which `get()` gives `value`. */
61
+ /**
62
+ * This method starts `fn` with `args` in a new context in which `get()` gives `value`. As
63
+ * in the TC39 draft, `fn` gets `undefined` as its `this` value.
64
+ */
47
65
  run<R, A extends unknown[]>(value : T, fn : (...args : A) => R, ...args : A) : R {
48
- return this.#storage.run({ value }, fn, ...args);
66
+ const current = values.getStore();
67
+ // A value of the same variable in the current context gets replaced, so the chain stays short
68
+ const parent = current !== undefined && current.variable === this ? current.parent : current;
69
+ return values.run({ variable : this, value, parent }, () => fn(...args));
49
70
  }
50
71
  }
51
72
 
52
- /** The `AsyncContext.Snapshot` of the TC39 proposal, on the native `AsyncLocalStorage.snapshot()`. */
73
+ Object.defineProperty(Variable.prototype, Symbol.toStringTag, { value : "AsyncContext.Variable", configurable : true });
74
+
75
+ /** The type of the async resources of the snapshots, for async_hooks. */
76
+ const SNAPSHOT_TYPE = "AsyncContext.Snapshot";
77
+
78
+ /**
79
+ * The `AsyncContext.Snapshot` of the TC39 proposal. An `AsyncResource` records the context, as
80
+ * `AsyncLocalStorage.snapshot()` does, at a much lower cost (src/node/runtime.ts).
81
+ */
53
82
  export class Snapshot {
54
- readonly #run : <R, A extends unknown[]>(fn : (...args : A) => R, ...args : A) => R = NodeAsyncLocalStorage.snapshot();
83
+ readonly #context = new AsyncResource(SNAPSHOT_TYPE);
55
84
 
56
- /** This method starts `fn` with `args` in the recorded context. */
85
+ /** This method starts `fn` with `args` in the recorded context. `fn` gets `undefined` as its `this` value. */
57
86
  run<R, A extends unknown[]>(fn : (...args : A) => R, ...args : A) : R {
58
- return this.#run(fn, ...args);
87
+ return this.#context.runInAsyncScope(fn, undefined, ...args);
59
88
  }
60
89
 
61
90
  /** This method records the current context. It gives a wrapper of `fn` that operates in that context. */
@@ -63,25 +92,39 @@ export class Snapshot {
63
92
  if (typeof fn !== "function") {
64
93
  throw new TypeError("Snapshot.wrap: the argument is not a function");
65
94
  }
66
- const run = NodeAsyncLocalStorage.snapshot();
95
+ const context = new AsyncResource(SNAPSHOT_TYPE);
67
96
  const wrapped = function (this : T, ...args : A) : R {
68
- return run(() => fn.apply(this, args));
97
+ return context.runInAsyncScope(fn, this, ...args);
69
98
  };
70
- Object.defineProperty(wrapped, "name", { value : fn.name, configurable : true });
99
+ // As CopyNameAndLength with the prefix "wrapped" in the TC39 draft
100
+ const name : unknown = fn.name;
101
+ Object.defineProperty(wrapped, "name", { value : `wrapped ${typeof name === "string" ? name : ""}`, configurable : true });
71
102
  Object.defineProperty(wrapped, "length", { value : fn.length, configurable : true });
72
103
  return wrapped;
73
104
  }
74
105
  }
75
106
 
76
- /** This function gives `true` if the native class supports the `defaultValue` option (Node.js 24 and later). */
107
+ Object.defineProperty(Snapshot.prototype, Symbol.toStringTag, { value : "AsyncContext.Snapshot", configurable : true });
108
+
109
+ /**
110
+ * This function gives `true` if the native class supports the `defaultValue` option (Node.js 24
111
+ * and later), and `exit()` then gives `undefined` as in the browser class. Without
112
+ * AsyncContextFrame (`--no-async-context-frame`), `exit()` gives the default value, so the
113
+ * compatible class is used. The probe disables itself, so it does not stay in the list of
114
+ * async_hooks.
115
+ */
77
116
  function supportsOptions() : boolean {
78
117
  const probe = new NodeAsyncLocalStorage<number>({ defaultValue : 1 } as never);
79
- return probe.getStore() === 1;
118
+ try {
119
+ return probe.getStore() === 1 && probe.run(2, () => probe.exit(() => probe.getStore())) === undefined;
120
+ } finally {
121
+ probe.disable();
122
+ }
80
123
  }
81
124
 
82
125
  /**
83
126
  * The native `AsyncLocalStorage` of Node.js. On a Node.js version without the
84
- * `defaultValue` and `name` options, a subclass adds them.
127
+ * `defaultValue` and `name` options, a compatible class adds them (compatible-storage.ts).
85
128
  */
86
129
  export const AsyncLocalStorage : typeof NodeAsyncLocalStorage = supportsOptions()
87
130
  ? NodeAsyncLocalStorage
@@ -2,22 +2,35 @@
2
2
  * The runtime of transformed code on Node.js. On Node.js, the native
3
3
  * `AsyncLocalStorage` keeps the context through promises, so `coroutine` is
4
4
  * a plain driver of the generator. `bindGenerator` keeps the context of the
5
- * generator creation (rule C5), with `AsyncLocalStorage.snapshot()`.
5
+ * generator creation (rule C5), with an `AsyncResource`.
6
+ *
7
+ * An `AsyncResource` records the context as `AsyncLocalStorage.snapshot()` does,
8
+ * but at a much lower cost. `snapshot()` is `AsyncResource.bind()`, which also
9
+ * defines properties on a new function (approximately 3 µs against 30 ns on
10
+ * Node.js 24). The drivers record the context again after each step.
6
11
  *
7
12
  * @packageDocumentation
8
13
  */
9
- import { AsyncLocalStorage } from "node:async_hooks";
14
+ import { AsyncResource } from "node:async_hooks";
10
15
  import { createAsyncGenerator, type ResumeKey } from "../core/async-generator.js";
16
+ import { copyNameAndLength } from "../core/function-name.js";
17
+
18
+ export { asyncGeneratorDelegate, awaitAsyncGenerator, OverloadYield } from "../core/async-generator.js";
11
19
 
12
- export { OverloadYield } from "../core/async-generator.js";
20
+ /** The type of the async resources of the generators, for async_hooks. */
21
+ const RESOURCE_TYPE = "async-browser-context:generator";
13
22
 
14
23
  /**
15
24
  * This function gives an async function that operates `generatorFunction`. The function is
16
25
  * a native async function: each `await` of the source becomes one native `await`, with
17
- * the same microtask turns. An error of the parameters rejects the promise.
26
+ * the same microtask turns. An error of the parameters rejects the promise. The function has the
27
+ * name and the length of the source, as in the browser runtime.
18
28
  */
19
- export function coroutine<T, A extends unknown[], R>(generatorFunction : (this : T, ...args : A) => Generator<unknown, R, unknown>) : (this : T, ...args : A) => Promise<R> {
20
- return async function asyncFunction(this : T, ...args : A) : Promise<R> {
29
+ export function coroutine<T, A extends unknown[], R>(
30
+ generatorFunction : (this : T, ...args : A) => Generator<unknown, R, unknown>,
31
+ name? : string,
32
+ ) : (this : T, ...args : A) => Promise<R> {
33
+ const asyncFunction = async function asyncFunction(this : T, ...args : A) : Promise<R> {
21
34
  // The directive tells the Babel preset not to change this function (src/babel/skip-runtime.ts)
22
35
  "async-browser-context runtime";
23
36
  const generator = generatorFunction.apply(this, args);
@@ -34,30 +47,35 @@ export function coroutine<T, A extends unknown[], R>(generatorFunction : (this :
34
47
  }
35
48
  return result.value;
36
49
  };
50
+ copyNameAndLength(asyncFunction, name, generatorFunction.length);
51
+ return asyncFunction;
37
52
  }
38
53
 
39
54
  /**
40
55
  * This function gives a function that makes an async generator object, which operates
41
56
  * `generatorFunction`. The preset gives it in place of the helper `wrapAsyncGenerator` of
42
- * Babel. The driver starts in a snapshot of the context of the creation (rule C5). The
43
- * native `AsyncLocalStorage` keeps that context through the `await` of the driver.
57
+ * Babel. The driver starts in the context of the creation (rule C5). The native
58
+ * `AsyncLocalStorage` keeps that context through the `await` of the driver.
44
59
  */
45
60
  export function asyncGenerator<T, A extends unknown[]>(
46
61
  generatorFunction : (this : T, ...args : A) => Generator<unknown, unknown, unknown>,
62
+ name? : string,
47
63
  ) : (this : T, ...args : A) => AsyncGenerator<unknown, unknown, unknown> {
48
- return function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
49
- let snapshot = AsyncLocalStorage.snapshot();
64
+ const makeAsyncGenerator = function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
65
+ let context = new AsyncResource(RESOURCE_TYPE);
50
66
  const generator = generatorFunction.apply(this, args);
51
67
  const step = (key : ResumeKey, argument : unknown) : IteratorResult<unknown, unknown> => {
52
68
  try {
53
69
  return generator[key](argument);
54
70
  } finally {
55
71
  // The body can change its context with enterWith before it stops
56
- snapshot = AsyncLocalStorage.snapshot();
72
+ context = new AsyncResource(RESOURCE_TYPE);
57
73
  }
58
74
  };
59
- return createAsyncGenerator(step, Promise, (start) => snapshot(start));
75
+ return createAsyncGenerator(step, Promise, (start) => context.runInAsyncScope(start));
60
76
  };
77
+ copyNameAndLength(makeAsyncGenerator, name, generatorFunction.length);
78
+ return makeAsyncGenerator;
61
79
  }
62
80
 
63
81
  type AnyIterator = Iterator<unknown, unknown, unknown> | AsyncIterator<unknown, unknown, unknown>;
@@ -65,14 +83,14 @@ type ResumeMethod = "next" | "throw" | "return";
65
83
 
66
84
  /** This function binds a generator object to the current context (rule C5). */
67
85
  export function bindGenerator<I extends AnyIterator>(generator : I) : I {
68
- let run = AsyncLocalStorage.snapshot();
86
+ let context = new AsyncResource(RESOURCE_TYPE);
69
87
  const target = generator as unknown as Record<ResumeMethod, (argument? : unknown) => unknown>;
70
- const resume = (method : ResumeMethod, argument : unknown) : unknown => run(() => {
88
+ const resume = (method : ResumeMethod, argument : unknown) : unknown => context.runInAsyncScope(() => {
71
89
  try {
72
90
  return target[method](argument);
73
91
  } finally {
74
92
  // The body can change its context with enterWith before it stops
75
- run = AsyncLocalStorage.snapshot();
93
+ context = new AsyncResource(RESOURCE_TYPE);
76
94
  }
77
95
  });
78
96
  const methods = {