async-browser-context 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +102 -0
- package/README.md +45 -30
- package/dist/babel/async-generator-helpers.d.ts +6 -6
- package/dist/babel/async-generator-helpers.d.ts.map +1 -1
- package/dist/babel/async-generator-helpers.js +33 -22
- package/dist/babel/async-generator-helpers.js.map +1 -1
- package/dist/babel/async-generator-resources.d.ts +14 -0
- package/dist/babel/async-generator-resources.d.ts.map +1 -0
- package/dist/babel/async-generator-resources.js +38 -0
- package/dist/babel/async-generator-resources.js.map +1 -0
- package/dist/babel/bind-generators.d.ts +1 -1
- package/dist/babel/bind-generators.d.ts.map +1 -1
- package/dist/babel/bind-generators.js +88 -44
- package/dist/babel/bind-generators.js.map +1 -1
- package/dist/babel/name-coroutines.d.ts +14 -8
- package/dist/babel/name-coroutines.d.ts.map +1 -1
- package/dist/babel/name-coroutines.js +160 -39
- package/dist/babel/name-coroutines.js.map +1 -1
- package/dist/babel/preset.d.ts +24 -13
- package/dist/babel/preset.d.ts.map +1 -1
- package/dist/babel/preset.js +37 -9
- package/dist/babel/preset.js.map +1 -1
- package/dist/babel/runtime-calls.d.ts +22 -0
- package/dist/babel/runtime-calls.d.ts.map +1 -0
- package/dist/babel/runtime-calls.js +69 -0
- package/dist/babel/runtime-calls.js.map +1 -0
- package/dist/babel/skip-runtime.d.ts +18 -11
- package/dist/babel/skip-runtime.d.ts.map +1 -1
- package/dist/babel/skip-runtime.js +52 -16
- package/dist/babel/skip-runtime.js.map +1 -1
- package/dist/babel/static-members.d.ts +4 -0
- package/dist/babel/static-members.d.ts.map +1 -0
- package/dist/babel/static-members.js +112 -0
- package/dist/babel/static-members.js.map +1 -0
- package/dist/core/async-generator.d.ts +51 -13
- package/dist/core/async-generator.d.ts.map +1 -1
- package/dist/core/async-generator.js +255 -58
- package/dist/core/async-generator.js.map +1 -1
- package/dist/core/async-local-storage.d.ts +3 -0
- package/dist/core/async-local-storage.d.ts.map +1 -1
- package/dist/core/async-local-storage.js +3 -0
- package/dist/core/async-local-storage.js.map +1 -1
- package/dist/core/callback-hook.d.ts +3 -3
- package/dist/core/coroutine.d.ts +6 -2
- package/dist/core/coroutine.d.ts.map +1 -1
- package/dist/core/coroutine.js +106 -44
- package/dist/core/coroutine.js.map +1 -1
- package/dist/core/function-name.d.ts +9 -0
- package/dist/core/function-name.d.ts.map +1 -0
- package/dist/core/function-name.js +12 -0
- package/dist/core/function-name.js.map +1 -0
- package/dist/core/hooks.d.ts +2 -1
- package/dist/core/hooks.d.ts.map +1 -1
- package/dist/core/hooks.js +21 -6
- package/dist/core/hooks.js.map +1 -1
- package/dist/core/snapshot.d.ts +2 -1
- package/dist/core/snapshot.d.ts.map +1 -1
- package/dist/core/snapshot.js +7 -3
- package/dist/core/snapshot.js.map +1 -1
- package/dist/core/store.d.ts +28 -0
- package/dist/core/store.d.ts.map +1 -1
- package/dist/core/store.js +90 -20
- package/dist/core/store.js.map +1 -1
- package/dist/core/variable.d.ts +2 -1
- package/dist/core/variable.d.ts.map +1 -1
- package/dist/core/variable.js +5 -2
- package/dist/core/variable.js.map +1 -1
- package/dist/node/index.d.ts +10 -4
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +51 -16
- package/dist/node/index.js.map +1 -1
- package/dist/node/runtime.d.ts +7 -6
- package/dist/node/runtime.d.ts.map +1 -1
- package/dist/node/runtime.js +29 -16
- package/dist/node/runtime.js.map +1 -1
- package/dist/opentelemetry/context-manager.d.ts.map +1 -1
- package/dist/opentelemetry/context-manager.js +172 -13
- package/dist/opentelemetry/context-manager.js.map +1 -1
- package/dist/patches/callbacks.d.ts.map +1 -1
- package/dist/patches/callbacks.js +84 -29
- package/dist/patches/callbacks.js.map +1 -1
- package/dist/patches/events.d.ts.map +1 -1
- package/dist/patches/events.js +203 -91
- package/dist/patches/events.js.map +1 -1
- package/dist/patches/handler-interfaces.d.ts +3 -2
- package/dist/patches/handler-interfaces.d.ts.map +1 -1
- package/dist/patches/handler-interfaces.js +3 -2
- package/dist/patches/handler-interfaces.js.map +1 -1
- package/dist/patches/promise.d.ts +3 -0
- package/dist/patches/promise.d.ts.map +1 -1
- package/dist/patches/promise.js +13 -5
- package/dist/patches/promise.js.map +1 -1
- package/dist/patches/streams.d.ts.map +1 -1
- package/dist/patches/streams.js +36 -16
- package/dist/patches/streams.js.map +1 -1
- package/dist/patches/timers.d.ts.map +1 -1
- package/dist/patches/timers.js +17 -5
- package/dist/patches/timers.js.map +1 -1
- package/dist/patches/to-string.d.ts +4 -0
- package/dist/patches/to-string.d.ts.map +1 -1
- package/dist/patches/to-string.js +12 -6
- package/dist/patches/to-string.js.map +1 -1
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +3 -3
- package/dist/runtime.js.map +1 -1
- package/dist/vite/plugin.d.ts +7 -2
- package/dist/vite/plugin.d.ts.map +1 -1
- package/dist/vite/plugin.js +30 -6
- package/dist/vite/plugin.js.map +1 -1
- package/package.json +49 -25
- package/src/babel/async-generator-helpers.ts +34 -23
- package/src/babel/async-generator-resources.ts +40 -0
- package/src/babel/bind-generators.ts +91 -47
- package/src/babel/name-coroutines.ts +170 -41
- package/src/babel/preset.ts +47 -15
- package/src/babel/runtime-calls.ts +73 -0
- package/src/babel/skip-runtime.ts +58 -18
- package/src/babel/static-members.ts +117 -0
- package/src/core/async-generator.ts +273 -62
- package/src/core/async-local-storage.ts +3 -0
- package/src/core/callback-hook.ts +3 -3
- package/src/core/coroutine.ts +104 -43
- package/src/core/function-name.ts +11 -0
- package/src/core/hooks.ts +23 -6
- package/src/core/snapshot.ts +8 -3
- package/src/core/store.ts +107 -21
- package/src/core/variable.ts +6 -2
- package/src/node/index.ts +62 -19
- package/src/node/runtime.ts +33 -15
- package/src/opentelemetry/context-manager.ts +188 -13
- package/src/patches/callbacks.ts +87 -30
- package/src/patches/events.ts +249 -103
- package/src/patches/handler-interfaces.ts +3 -2
- package/src/patches/promise.ts +17 -13
- package/src/patches/streams.ts +36 -16
- package/src/patches/timers.ts +17 -5
- package/src/patches/to-string.ts +12 -6
- package/src/runtime.ts +3 -3
- package/src/vite/plugin.ts +38 -8
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
|
-
/**
|
|
20
|
-
|
|
21
|
-
|
|
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
|
-
|
|
43
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
-
|
|
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 #
|
|
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.#
|
|
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
|
|
95
|
+
const context = new AsyncResource(SNAPSHOT_TYPE);
|
|
67
96
|
const wrapped = function (this : T, ...args : A) : R {
|
|
68
|
-
return
|
|
97
|
+
return context.runInAsyncScope(fn, this, ...args);
|
|
69
98
|
};
|
|
70
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
package/src/node/runtime.ts
CHANGED
|
@@ -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 `
|
|
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 {
|
|
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
|
-
|
|
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>(
|
|
20
|
-
|
|
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
|
|
43
|
-
*
|
|
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
|
-
|
|
49
|
-
let
|
|
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
|
-
|
|
72
|
+
context = new AsyncResource(RESOURCE_TYPE);
|
|
57
73
|
}
|
|
58
74
|
};
|
|
59
|
-
return createAsyncGenerator(step, Promise, (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
|
|
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 =>
|
|
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
|
-
|
|
93
|
+
context = new AsyncResource(RESOURCE_TYPE);
|
|
76
94
|
}
|
|
77
95
|
});
|
|
78
96
|
const methods = {
|
|
@@ -10,6 +10,51 @@ export interface ContextStorage {
|
|
|
10
10
|
/** The type of the context manager class. */
|
|
11
11
|
export type AsyncContextManagerClass = new () => ContextManager;
|
|
12
12
|
|
|
13
|
+
type Listener = (...args : unknown[]) => unknown;
|
|
14
|
+
|
|
15
|
+
/** The guard of one emitter against nested adds: `true` while a patched add method operates. */
|
|
16
|
+
interface AddGuard {
|
|
17
|
+
adding : boolean;
|
|
18
|
+
}
|
|
19
|
+
type Method = (this : unknown, ...args : unknown[]) => unknown;
|
|
20
|
+
|
|
21
|
+
/** The methods of a Node.js EventEmitter that add a listener. */
|
|
22
|
+
const ADD_LISTENER_METHODS = ["addListener", "on", "once", "prependListener", "prependOnceListener"] as const;
|
|
23
|
+
|
|
24
|
+
/** The emitters and event targets that bind() patched. A second bind() keeps the first context, as the context managers of OpenTelemetry do. */
|
|
25
|
+
const boundTargets = new WeakSet<object>();
|
|
26
|
+
|
|
27
|
+
/** The bound listeners of one emitter or event target, for each event name. */
|
|
28
|
+
type ListenersByEvent = Record<PropertyKey, WeakMap<object, Listener> | undefined>;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The bound listeners of each emitter or event target, so that a remove method finds the bound listener.
|
|
32
|
+
* The event names are property keys, as in the EventEmitter of Node.js. Thus `1` and `"1"` are the same
|
|
33
|
+
* event name, as for the event target, which changes the type to a string.
|
|
34
|
+
*/
|
|
35
|
+
const boundListeners = new WeakMap<object, ListenersByEvent>();
|
|
36
|
+
|
|
37
|
+
function listenersOf(target : object, event : unknown) : WeakMap<object, Listener> {
|
|
38
|
+
let byEvent = boundListeners.get(target);
|
|
39
|
+
if (byEvent === undefined) {
|
|
40
|
+
// The object has no prototype, thus the event name "constructor" gives no inherited value
|
|
41
|
+
byEvent = Object.create(null) as ListenersByEvent;
|
|
42
|
+
boundListeners.set(target, byEvent);
|
|
43
|
+
}
|
|
44
|
+
let listeners = byEvent[event as PropertyKey];
|
|
45
|
+
if (listeners === undefined) {
|
|
46
|
+
listeners = new WeakMap();
|
|
47
|
+
byEvent[event as PropertyKey] = listeners;
|
|
48
|
+
}
|
|
49
|
+
return listeners;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** This function gives the bound listener of `listener`, or `undefined` if the add methods did not bind it. */
|
|
53
|
+
function boundListenerOf(target : object, event : unknown, listener : unknown) : Listener | undefined {
|
|
54
|
+
// For a key that is not an object, WeakMap.get() gives undefined
|
|
55
|
+
return boundListeners.get(target)?.[event as PropertyKey]?.get(listener as object);
|
|
56
|
+
}
|
|
57
|
+
|
|
13
58
|
/**
|
|
14
59
|
* This function makes the context manager class for one `AsyncLocalStorage`
|
|
15
60
|
* class: the class of the browser runtime, or the native class of Node.js.
|
|
@@ -24,21 +69,42 @@ export function defineContextManager(createStorage : () => ContextStorage) : Asy
|
|
|
24
69
|
return this.#storage.getStore() ?? ROOT_CONTEXT;
|
|
25
70
|
}
|
|
26
71
|
|
|
27
|
-
/**
|
|
72
|
+
/**
|
|
73
|
+
* This method starts `fn` with `context` as the active context, also after each `await` in `fn`.
|
|
74
|
+
* With `thisArg` `null` or `undefined`, `fn` gets `undefined` as its `this` value, as in OpenTelemetry.
|
|
75
|
+
*/
|
|
28
76
|
with<A extends unknown[], F extends (...args : A) => ReturnType<F>>(context : Context, fn : F, thisArg? : ThisParameterType<F>, ...args : A) : ReturnType<F> {
|
|
29
|
-
return this.#storage.run(context, () =>
|
|
77
|
+
return this.#storage.run(context, () => Reflect.apply(fn, thisArg ?? undefined, args) as ReturnType<F>);
|
|
30
78
|
}
|
|
31
79
|
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
80
|
+
/**
|
|
81
|
+
* This method binds `target` to `context`, as the context managers of OpenTelemetry do:
|
|
82
|
+
*
|
|
83
|
+
* - A function gives a wrapper that starts it with `context` as the active context.
|
|
84
|
+
* - An event target (`addEventListener`) or a Node.js event emitter (`on`) gets a patch of
|
|
85
|
+
* its methods. Each listener that the program adds later operates with `context`, and the
|
|
86
|
+
* remove methods find the bound listener. A second `bind()` of the same object keeps the
|
|
87
|
+
* first context.
|
|
88
|
+
* - Other values stay as they are.
|
|
89
|
+
*
|
|
90
|
+
* Without a context, the method uses the active context.
|
|
91
|
+
*/
|
|
92
|
+
bind<T>(context : Context | undefined, target : T) : T {
|
|
93
|
+
const bound = context ?? this.active();
|
|
94
|
+
if (typeof target === "function") {
|
|
95
|
+
return this.#bindFunction(bound, target as unknown as Listener) as T;
|
|
96
|
+
}
|
|
97
|
+
if (typeof target === "object" && target !== null && !boundTargets.has(target)) {
|
|
98
|
+
const methods = target as unknown as Record<string, unknown>;
|
|
99
|
+
if (typeof methods["addEventListener"] === "function") {
|
|
100
|
+
boundTargets.add(target);
|
|
101
|
+
this.#bindEventTarget(bound, target);
|
|
102
|
+
} else if (typeof methods["on"] === "function" || typeof methods["addListener"] === "function") {
|
|
103
|
+
boundTargets.add(target);
|
|
104
|
+
this.#bindEmitter(bound, target);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return target;
|
|
42
108
|
}
|
|
43
109
|
|
|
44
110
|
/** The manager is active when it exists. The method is for the `ContextManager` interface. */
|
|
@@ -46,10 +112,119 @@ export function defineContextManager(createStorage : () => ContextStorage) : Asy
|
|
|
46
112
|
return this;
|
|
47
113
|
}
|
|
48
114
|
|
|
49
|
-
/**
|
|
115
|
+
/**
|
|
116
|
+
* After this method, `active()` gives the root context in the current code. With the
|
|
117
|
+
* browser runtime and with Node.js 22, it also gives the root context in all other code
|
|
118
|
+
* until the next `with()`. With Node.js 24 and its AsyncContextFrame, the native class
|
|
119
|
+
* changes only the current context, also for the callbacks that this context registered.
|
|
120
|
+
*/
|
|
50
121
|
disable() : this {
|
|
51
122
|
this.#storage.disable();
|
|
52
123
|
return this;
|
|
53
124
|
}
|
|
125
|
+
|
|
126
|
+
/** With `guard`, the listener of an emitter clears the guard against nested adds while it operates (`#bindEmitter`). */
|
|
127
|
+
#bindFunction(context : Context, fn : Listener, guard? : AddGuard) : Listener {
|
|
128
|
+
const run = (call : () => unknown) : unknown => this.with(context, call);
|
|
129
|
+
const wrapper = function (this : unknown, ...args : unknown[]) : unknown {
|
|
130
|
+
if (guard === undefined) {
|
|
131
|
+
return run(() => Reflect.apply(fn, this, args));
|
|
132
|
+
}
|
|
133
|
+
// A listener of "newListener" can add listeners during an add: they also get the context
|
|
134
|
+
const outer = guard.adding;
|
|
135
|
+
guard.adding = false;
|
|
136
|
+
try {
|
|
137
|
+
return run(() => Reflect.apply(fn, this, args));
|
|
138
|
+
} finally {
|
|
139
|
+
guard.adding = outer;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
Object.defineProperty(wrapper, "length", { value : fn.length, configurable : true });
|
|
143
|
+
return wrapper;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** This method patches the methods of a Node.js event emitter, as `AsyncLocalStorageContextManager` of OpenTelemetry does. */
|
|
147
|
+
#bindEmitter(context : Context, emitter : object) : void {
|
|
148
|
+
const methods = emitter as Record<string, unknown>;
|
|
149
|
+
// `once` of Node.js adds its own wrapper with `this.on`. That inner add must not wrap again,
|
|
150
|
+
// else `removeListener` does not find the listener. OpenTelemetry has the same guard.
|
|
151
|
+
const guard : AddGuard = { adding : false };
|
|
152
|
+
for (const name of ADD_LISTENER_METHODS) {
|
|
153
|
+
const original = methods[name];
|
|
154
|
+
if (typeof original !== "function") {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const manager = this;
|
|
158
|
+
methods[name] = function (this : unknown, event : unknown, listener : unknown) : unknown {
|
|
159
|
+
if (guard.adding || typeof listener !== "function") {
|
|
160
|
+
return Reflect.apply(original as Method, this, arguments);
|
|
161
|
+
}
|
|
162
|
+
const listeners = listenersOf(emitter, event);
|
|
163
|
+
let wrapper = listeners.get(listener);
|
|
164
|
+
if (wrapper === undefined) {
|
|
165
|
+
wrapper = manager.#bindFunction(context, listener as Listener, guard);
|
|
166
|
+
listeners.set(listener, wrapper);
|
|
167
|
+
}
|
|
168
|
+
guard.adding = true;
|
|
169
|
+
try {
|
|
170
|
+
return Reflect.apply(original as Method, this, [event, wrapper]);
|
|
171
|
+
} finally {
|
|
172
|
+
guard.adding = false;
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
for (const name of ["removeListener", "off"] as const) {
|
|
177
|
+
const original = methods[name];
|
|
178
|
+
if (typeof original !== "function") {
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
methods[name] = function (this : unknown, event : unknown, listener : unknown) : unknown {
|
|
182
|
+
return Reflect.apply(original as Method, this, [event, boundListenerOf(emitter, event, listener) ?? listener]);
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const removeAll = methods["removeAllListeners"];
|
|
186
|
+
if (typeof removeAll === "function") {
|
|
187
|
+
methods["removeAllListeners"] = function (this : unknown, event? : unknown) : unknown {
|
|
188
|
+
if (arguments.length === 0) {
|
|
189
|
+
boundListeners.delete(emitter);
|
|
190
|
+
} else {
|
|
191
|
+
delete boundListeners.get(emitter)?.[event as PropertyKey];
|
|
192
|
+
}
|
|
193
|
+
return Reflect.apply(removeAll as Method, this, arguments);
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** This method patches the methods of an event target, as `ZoneContextManager` of OpenTelemetry does. */
|
|
199
|
+
#bindEventTarget(context : Context, target : object) : void {
|
|
200
|
+
const methods = target as Record<string, unknown>;
|
|
201
|
+
const add = methods["addEventListener"] as Method;
|
|
202
|
+
const remove = methods["removeEventListener"];
|
|
203
|
+
const manager = this;
|
|
204
|
+
methods["addEventListener"] = function (this : unknown, type : unknown, listener : unknown) : unknown {
|
|
205
|
+
if (typeof listener !== "function") {
|
|
206
|
+
return Reflect.apply(add, this, arguments);
|
|
207
|
+
}
|
|
208
|
+
const listeners = listenersOf(target, type);
|
|
209
|
+
let wrapper = listeners.get(listener);
|
|
210
|
+
if (wrapper === undefined) {
|
|
211
|
+
wrapper = manager.#bindFunction(context, listener as Listener);
|
|
212
|
+
listeners.set(listener, wrapper);
|
|
213
|
+
}
|
|
214
|
+
const args = Array.prototype.slice.call(arguments) as unknown[];
|
|
215
|
+
args[1] = wrapper;
|
|
216
|
+
return Reflect.apply(add, this, args);
|
|
217
|
+
};
|
|
218
|
+
if (typeof remove === "function") {
|
|
219
|
+
methods["removeEventListener"] = function (this : unknown, type : unknown, listener : unknown) : unknown {
|
|
220
|
+
const wrapper = boundListenerOf(target, type, listener);
|
|
221
|
+
const args = Array.prototype.slice.call(arguments) as unknown[];
|
|
222
|
+
if (wrapper !== undefined) {
|
|
223
|
+
args[1] = wrapper;
|
|
224
|
+
}
|
|
225
|
+
return Reflect.apply(remove as Method, this, args);
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
}
|
|
54
229
|
};
|
|
55
230
|
}
|
package/src/patches/callbacks.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { bindToFrame, store } from "../core/store.js";
|
|
1
|
+
import { bindToFrame, store, type Frame } from "../core/store.js";
|
|
2
2
|
import { claim, globalPrototype, ownDataValue, replaceFunction, wrapFunctionArguments } from "./patch.js";
|
|
3
3
|
|
|
4
4
|
type Method = (this : unknown, ...args : unknown[]) => unknown;
|
|
@@ -24,40 +24,91 @@ const PROTOTYPE_METHODS : readonly (readonly [string, readonly string[]])[] = [
|
|
|
24
24
|
/** The static methods that get callbacks and use them later. */
|
|
25
25
|
const STATIC_METHODS : readonly (readonly [string, readonly string[]])[] = [
|
|
26
26
|
["Notification", ["requestPermission"]],
|
|
27
|
-
["Array", ["fromAsync"]],
|
|
28
27
|
];
|
|
29
28
|
|
|
30
|
-
/** `source` is the name of the method, for the callback hooks. */
|
|
29
|
+
/** `source` is the name of the method, for the callback hooks. The replacement is a method, as the native function. */
|
|
31
30
|
function wrapArguments(source : string) : (original : Method) => Method {
|
|
32
|
-
return (original) =>
|
|
33
|
-
|
|
34
|
-
|
|
31
|
+
return (original) => ({
|
|
32
|
+
method(this : unknown, ...args : unknown[]) : unknown {
|
|
33
|
+
return Reflect.apply(original, this, wrapFunctionArguments(args, source));
|
|
34
|
+
},
|
|
35
|
+
}).method;
|
|
35
36
|
}
|
|
36
37
|
|
|
37
|
-
/**
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
38
|
+
/**
|
|
39
|
+
* `Array.fromAsync(items, mapFn, thisArg)` uses only `mapFn` later. `items` and `thisArg` can
|
|
40
|
+
* also be functions, and they must not change.
|
|
41
|
+
*/
|
|
42
|
+
function wrapFromAsync(original : Method) : Method {
|
|
43
|
+
return {
|
|
44
|
+
fromAsync(this : unknown) : unknown {
|
|
45
|
+
const mapFn : unknown = arguments[1];
|
|
46
|
+
if (typeof mapFn !== "function") {
|
|
47
|
+
return Reflect.apply(original, this, arguments);
|
|
48
|
+
}
|
|
49
|
+
const args = Array.prototype.slice.call(arguments) as unknown[];
|
|
50
|
+
args[1] = bindToFrame(store.current, mapFn as Method, "Array.fromAsync");
|
|
51
|
+
return Reflect.apply(original, this, args);
|
|
52
|
+
},
|
|
53
|
+
}.fromAsync;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* This function gives a view of the dictionary `options` in which each key of `keys` gives a
|
|
58
|
+
* wrapper of its callback. The other members come from `options` with their getters and their
|
|
59
|
+
* prototype chain. The target of the Proxy is an empty object, so a frozen object also
|
|
60
|
+
* operates. The browser reads the members of a dictionary with [[Get]] only.
|
|
61
|
+
*/
|
|
62
|
+
function withCallback(options : object, keys : readonly string[], frame : Frame, source : string) : object {
|
|
63
|
+
const wrappers = new Map<PropertyKey, Method>();
|
|
64
|
+
return new Proxy({}, {
|
|
65
|
+
get(_target, property) : unknown {
|
|
66
|
+
const value : unknown = Reflect.get(options, property, options);
|
|
67
|
+
if (typeof property !== "string" || !keys.includes(property) || typeof value !== "function") {
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
let wrapper = wrappers.get(property);
|
|
71
|
+
if (wrapper === undefined) {
|
|
72
|
+
wrapper = bindToFrame(frame, value as Method, source);
|
|
73
|
+
wrappers.set(property, wrapper);
|
|
74
|
+
}
|
|
75
|
+
return wrapper;
|
|
76
|
+
},
|
|
77
|
+
// For an engine that examines a member with the `in` operator first, as the streams of WebKit do
|
|
78
|
+
has(_target, property) : boolean {
|
|
79
|
+
return Reflect.has(options, property);
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** `startViewTransition()` gets a callback, or an object with an `update` callback. `source` names the class. */
|
|
85
|
+
function wrapViewTransition(source : string) : (original : Method) => Method {
|
|
86
|
+
return (original) => ({
|
|
87
|
+
startViewTransition(this : unknown) : unknown {
|
|
88
|
+
const first : unknown = arguments[0];
|
|
89
|
+
if (typeof first === "object" && first !== null) {
|
|
90
|
+
const args = Array.prototype.slice.call(arguments) as unknown[];
|
|
91
|
+
args[0] = withCallback(first, ["update"], store.current, source);
|
|
92
|
+
return Reflect.apply(original, this, args);
|
|
93
|
+
}
|
|
94
|
+
return Reflect.apply(original, this, wrapFunctionArguments(Array.prototype.slice.call(arguments) as unknown[], source));
|
|
95
|
+
},
|
|
96
|
+
}).startViewTransition;
|
|
49
97
|
}
|
|
50
98
|
|
|
51
|
-
/** `NavigateEvent.intercept()` gets an object with a `handler` callback. */
|
|
99
|
+
/** `NavigateEvent.intercept()` gets an object with a `handler` and a `precommitHandler` callback. */
|
|
52
100
|
function wrapIntercept(original : Method) : Method {
|
|
53
|
-
return
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
101
|
+
return {
|
|
102
|
+
intercept(this : unknown) : unknown {
|
|
103
|
+
const first : unknown = arguments[0];
|
|
104
|
+
if (typeof first === "object" && first !== null) {
|
|
105
|
+
const args = Array.prototype.slice.call(arguments) as unknown[];
|
|
106
|
+
args[0] = withCallback(first, ["handler", "precommitHandler"], store.current, "NavigateEvent.intercept");
|
|
107
|
+
return Reflect.apply(original, this, args);
|
|
108
|
+
}
|
|
109
|
+
return Reflect.apply(original, this, arguments);
|
|
110
|
+
},
|
|
111
|
+
}.intercept;
|
|
61
112
|
}
|
|
62
113
|
|
|
63
114
|
/** This function patches the callback APIs that are not events, timers or observers. */
|
|
@@ -83,9 +134,15 @@ export function installCallbackPatches() : void {
|
|
|
83
134
|
replaceFunction<Method>(constructor, method, wrapArguments(`${constructorName}.${method}`));
|
|
84
135
|
}
|
|
85
136
|
}
|
|
86
|
-
const
|
|
87
|
-
if (
|
|
88
|
-
replaceFunction<Method>(
|
|
137
|
+
const array = ownDataValue(globalThis, "Array");
|
|
138
|
+
if (typeof array === "function") {
|
|
139
|
+
replaceFunction<Method>(array, "fromAsync", wrapFromAsync);
|
|
140
|
+
}
|
|
141
|
+
for (const owner of ["Document", "Element"]) {
|
|
142
|
+
const prototype = globalPrototype(owner);
|
|
143
|
+
if (prototype !== undefined) {
|
|
144
|
+
replaceFunction<Method>(prototype, "startViewTransition", wrapViewTransition(`${owner}.startViewTransition`));
|
|
145
|
+
}
|
|
89
146
|
}
|
|
90
147
|
const navigateEventPrototype = globalPrototype("NavigateEvent");
|
|
91
148
|
if (navigateEventPrototype !== undefined) {
|