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.
Files changed (140) hide show
  1. package/CHANGELOG.md +102 -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 +51 -13
  36. package/dist/core/async-generator.d.ts.map +1 -1
  37. package/dist/core/async-generator.js +255 -58
  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 +106 -44
  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 +3 -2
  86. package/dist/patches/handler-interfaces.d.ts.map +1 -1
  87. package/dist/patches/handler-interfaces.js +3 -2
  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 +49 -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 +273 -62
  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 +104 -43
  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 +3 -2
  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/CHANGELOG.md CHANGED
@@ -1,5 +1,107 @@
1
1
  # Change history
2
2
 
3
+ ## 0.3.0
4
+
5
+ This version changes some behaviors, so it is a minor version. The first section gives the changes that can affect existing code.
6
+
7
+ ### Changes that can affect existing code
8
+
9
+ - `Snapshot.wrap()` gives the wrapper the name `wrapped` and the name of the function, for example `wrapped save`, as the TC39 draft specifies. In the browser, `AsyncLocalStorage.bind()` gives the same name. Before, the wrapper had the name of the function.
10
+ - `Variable` and `Snapshot` have the `Symbol.toStringTag` of the TC39 draft. `Object.prototype.toString` gives `[object AsyncContext.Variable]` and `[object AsyncContext.Snapshot]`. Before, it gave `[object Object]`.
11
+ - On Node.js, `Variable.run()` starts the function with the `this` value `undefined`, as the browser class and the TC39 draft do. Before, the native `run()` gave `null`.
12
+ - A callback that a hook method schedules does not start the callback hooks, also when it operates later. Examples are a timer, a `then` callback and an event listener that a hook registers. Such a callback is also quiet for the callbacks, async functions and async generators that it starts or registers. Thus a hook cannot start itself without end, also through a chain of callbacks. Before, only a callback that started synchronously in a hook did not start the hooks.
13
+ - `addEventListener()` and `removeEventListener()` read the options as the DOM does. `null` and `undefined` give the default options, and another primitive value is the capture flag. `capture` and `once` use `ToBoolean`. Before, the patch read only `true` and `capture: true`. With another value, for example `{ capture: 1 }`, a second registration or a removal with `true` did not find the listener.
14
+ - The patched functions have the form of native methods. They have no `prototype` property, they are not constructors, and they give the native function the same number of arguments. Thus `setTimeout()` without arguments and `addEventListener(type)` without a listener throw the native `TypeError`. Before, they did not throw.
15
+ - OpenTelemetry: `bind(context, emitter)` and `bind(context, eventTarget)` patch the methods that add and remove listeners, as the context managers of OpenTelemetry do. Each listener that the program adds later operates with the context, and the remove methods find it, also for a `once` listener. Before, `bind()` gave such an object without a change. `bind(undefined, fn)` uses the active context. Before, it used the root context. A second `bind()` of the same object keeps the first context, as in OpenTelemetry.
16
+ - The Babel preset imports all four async generator helpers from the runtime: `asyncGenerator`, `OverloadYield`, `awaitAsyncGenerator` and `asyncGeneratorDelegate`. A module that the `runtime` option names must export them. Use the preset and the runtime of the same version. Before, Babel put `awaitAsyncGenerator` and `asyncGeneratorDelegate` into each module.
17
+ - The Babel preset has nine plugins. A new plugin moves static class fields and static blocks with async arrow functions into static private methods. Thus `this` and `super` stay correct. Before, `this` was `undefined` in such a function, and `super` gave a `SyntaxError`.
18
+ - The Babel preset changes `using` and `await using` declarations with `@babel/plugin-transform-explicit-resource-management`, a new dependency, before the async transform. A plugin of the preset applies it to async generators first. This plugin operates with Babel 7.23.9 and later. Before, `await using` gave a `SyntaxError` in the generator of the transform.
19
+ - The Vite plugin reads a module without a static `import` or `export`, for example a worker, as an ES module. Only `.cjs` and `.cts` files and files with CommonJS marks get the source type `unambiguous`. Babel reads them as scripts, unless they have a static `import` or `export`. Before, Babel read such a module as a script and added a `require()` of the runtime, which a browser does not have.
20
+ - The Vite plugin also transforms the JavaScript of Vue, Svelte, Astro and MDX components. It does not transform their styles. The `include` and `exclude` options also apply to these modules.
21
+ - `package.json` has `main`, `types` and `typesVersions`. Thus TypeScript with the `moduleResolution` `node10` finds the types of each entry. This setting is the default for `module: commonjs`. Before, TypeScript found no types, so a project can get new type errors.
22
+
23
+ ### Changes
24
+
25
+ - On Node.js, all `Variable` objects share one native `AsyncLocalStorage`. Node.js 22 keeps each storage that operated in a global list of `async_hooks`, and each new async resource examines that list. Thus a `Variable` for each request made each async operation slower. `AsyncLocalStorage` is the native class, as before.
26
+ - On Node.js, `Snapshot`, `Snapshot.wrap()` and the generator drivers of the transform (`bindGenerator` and `asyncGenerator`) record the context with an `AsyncResource`. Before, they used `AsyncLocalStorage.snapshot()`. The hooks of `async_hooks` see these resources with the types `AsyncContext.Snapshot` and `async-browser-context:generator`.
27
+ - `addCallbackHook()` writes a warning on the console one time when a copy of version 0.1 installed some patches first. The callbacks of those patches do not start the hooks.
28
+ - The steps of an async generator after an `await` give the name of the async generator to the callback hooks (`callback.name`), as async functions do.
29
+
30
+ ### Corrections
31
+
32
+ - OpenTelemetry: a remove method finds a bound listener also when it gets the event name in another form, for example `1` in place of `"1"`. The emitter and the event target do the same. `with()` with the `this` value `null` starts the function with `undefined`, as OpenTelemetry does.
33
+ - The patches of `Promise.prototype.then` and `Function.prototype.toString` start the function that they replace, as the other patches do. Thus a patch of `then` or `toString` that another tool installed before the library stays in effect. Before, these patches started the native functions.
34
+ - The preset does not change the native async generator of the runtime, also when a bundler applies the preset to `node_modules`. The plugin of Babel for async generators changes async generators and `for await` loops in its own traversal. The preset makes that traversal skip the functions with the directive of the runtime too. Before, the runtime then imported itself, and its async generator objects did not inherit `Symbol.asyncDispose`.
35
+ - The runtime loads also when another preset in the same Babel configuration, for example `next/babel`, changes its native async generator. Its async generator objects then inherit from `Object.prototype`.
36
+ - OpenTelemetry: a listener that a `newListener` listener adds during an add of a bound emitter gets the context too.
37
+ - Async generators: `return()` at a `yield` settles in the same microtask turn as with a native async generator, one turn earlier than before. A `throw()` through `yield*` to a delegate without a `throw` method awaits `return()` of the delegate, as `AsyncIteratorClose` does. An error of that `return()` goes into the body. Before, it was an unhandled rejection, and the body got a `TypeError`.
38
+ - Events:
39
+ - After a top-level `enterWith()`, an event that the browser dispatches gives the registration context to each listener (rule C13). Before, each listener got the default store of the `enterWith()`. The event patch handles the default store as the root context.
40
+ - A listener with a `signal` does not stay in memory. The map of the listeners is weak, and the abort listener of a registration keeps only weak references. Before, a signal that lived long kept the target, the listener and its context in memory, also on Node.js.
41
+ - A removed registration and a `once` listener that operated remove their abort listener. A failed native `addEventListener()` keeps no registration.
42
+ - A registration with an aborted signal, or a `once` listener that operated, gets a new registration at the next add.
43
+ - The `on...` getters give the handler also from another property that reflects it, for example `window.onload` for the handler of `body.onload`.
44
+ - `MediaQueryList.addListener()` and `removeListener()` accept listener objects with a `handleEvent` method, as the native methods do. For an object that is not a `MediaQueryList`, they throw the native `TypeError`.
45
+ - The event patch drops the entry of a type when its last registration goes. Before, many event types on one target that lived long filled the memory.
46
+ - Streams, and the options of `startViewTransition()` and `NavigateEvent.intercept()`: the patch gives the browser a Proxy in place of a copy of the object. Thus frozen objects, getters, private fields and inherited members operate. The Proxy also answers the `in` operator, which the streams of WebKit use.
47
+ - `Element.startViewTransition()` and the `precommitHandler` of `NavigateEvent.intercept()` keep the context.
48
+ - `Array.fromAsync()` wraps only its map function. Before, it also wrapped `items` and `thisArg` when they were functions.
49
+ - Callback hooks: an error of a getter of a hook method, or an error of `reportError()`, does not stop the callback.
50
+ - The wrappers start each callback with `Reflect.apply`. Thus a callback with its own `call` or `apply` property operates.
51
+ - A frame of the same variable replaces its parent. Thus many uses of `enterWith()` in one context do not make a long chain, and do not keep old stores in memory.
52
+ - `yield*` in a transformed async generator keeps the protocol of a native `yield*`:
53
+ - After `return()`, a `yield*` in a `finally` block operates to its end, also after `return()` through an earlier `yield*`. Before, a delegate that was complete at its first step ended the generator with the value of the delegate.
54
+ - A rejection of a step of the delegate goes into the body at the `yield*`, also when the delegate has no `throw` method. Before, the body got a `TypeError` in that case.
55
+ - A result of the delegate that is not an object throws a `TypeError` into the body at the `yield*`. Before, the request of the consumer failed for `undefined` and `null`, and the body did not get the error.
56
+ - In WebKit, the driver does not await the values of the delegate. Before, it awaited each value, because the `yield*` of WebKit makes a new result object. The driver reads `done` and `value` of each result one time, as a native `yield*` does.
57
+ - Node.js: the probe of the native options also examines `exit()`, and it disables itself after the probe. With `--no-async-context-frame` on Node.js 24, `exit()` thus gives `undefined`, as in the browser.
58
+ - Babel preset:
59
+ - A generator parameter that the body declares again with `var`, or with a function declaration in a block of a sloppy script, keeps its value.
60
+ - The generator of a Babel helper in a compiled dependency gets a binding (rule C5). The generators that `coroutine` and `asyncGenerator` operate do not get a second binding.
61
+ - A generator declaration in a block of a script stays in the block.
62
+ - The plugin of the async generator helpers sets its helpers in `Program` enter. Thus `@babel/plugin-transform-runtime` and the presets earlier in the list do not break the markers of the driver.
63
+ - The traversals of the preset skip the functions with the directive of the runtime. The preset finds the runtime functions also in CommonJS output. A file counts as changed only when the preset changes it.
64
+ - TypeScript wrappers, for example `as` and `satisfies`, and accessor fields keep the name of an async function for the hooks. A function that Babel gives no named wrapper, for example in a class field, keeps its name and its length. This is also true on Node.js and for async generators. An anonymous async function has the empty name, as a native one. Before, it had the name `asyncFunction`.
65
+ - A class field with the name `_ref` keeps its result. Before, its wrapper started itself without end (`RangeError`). A field with the name `eval` or `arguments` is no `SyntaxError`, and it keeps its name.
66
+ - A bigint key, for example `1n`, gives its name, for example `"1"`. A static field with a computed literal key keeps its name, also with `names: false`.
67
+ - A key that is not a binding name, for example `"a b"`, `42`, `default` or `#p`, gives its name to an async arrow function. Before, the function had a binding name that Babel made of the key, for example `a_b`.
68
+ - Vite plugin: no input source map, because the map of Vite describes the code that the plugin gets. The option `compact: false` keeps the format of large modules. One presets array for all modules lets the configuration cache of Babel operate.
69
+
70
+ ### Performance
71
+
72
+ - Node.js: an `AsyncResource` records the context in 30 to 40 ns, and `AsyncLocalStorage.snapshot()` takes approximately 3 µs. The drivers record the context after each step. Thus a step of `bindGenerator` takes 0.11 µs in place of 2.3 µs, and a step of `asyncGenerator` 0.45 µs in place of 2.6 µs (Node.js 24).
73
+ - `pnpm bench:size` measures a minified bundle with all exports of the runtime. The runtime is 17.5 kB minified, 6.0 kB with gzip and 5.4 kB with brotli. The earlier values (19.0, 5.9 and 5.1 kB) came from a library build that kept the white space, and that did not contain `asyncGenerator` and `OverloadYield`.
74
+ - `pnpm bench:browsers` repeats each workload until at least 100 ms have passed, and divides the time by the repetitions. Before, one pair of `performance.now()` calls measured 50,000 steps, with a resolution of 0.1 ms to 1 ms.
75
+
76
+ ### Tests
77
+
78
+ - New tests for the cases that the review found without a test. An `await` in a `finally` block keeps the context after a `return` and after a `throw` (rule C3). A string callback of `setTimeout` goes to the native function as it is (rule C6). Two copies of the library read and keep the variables of each other (rule C10). A capture listener and a listener without capture stay apart (rule C13).
79
+ - Memory tests for event listeners: after `removeEventListener()`, after a `once` listener operated, and with a signal that lives long. The memory tests fail without `--expose-gc`.
80
+ - Browser tests for each correction of the events, the streams and the callback APIs.
81
+ - CI also starts the Node.js tests on Node.js 22.18.0 and 24.11.0, the minimum versions, and starts the tests of the STE linter (`pnpm test:ste-lint`).
82
+ - New tests of the core runtime, from mutation testing. They examine the requests of an async generator in each state and `yield*` with unusual delegates. They also examine the callback hooks of the generator steps and the property attributes of the prototypes. The project without a transform starts the tests of the generator protocol on native async generators.
83
+
84
+ ### Documentation
85
+
86
+ - The documents tell the nine plugins of the preset and the six exports of the runtime.
87
+ - New limits: a transformed generator function is a plain function for libraries that examine it, and a top-level `enterWith()` stays as a default store. A minifier can remove the directive of the runtime.
88
+ - The webpack examples add `@babel/preset-typescript` and `@babel/preset-react` for TypeScript and JSX files.
89
+ - The pages tell where the tests examine each rule and each boundary.
90
+
91
+ ## 0.2.4
92
+
93
+ ### Corrections
94
+
95
+ - `yield*` in a transformed async generator gave a promise in place of each object of the delegate. Version 0.2.3 had this error. The driver does not change the result of a `yield*` step at this time.
96
+ - Transformed code can await a thenable that is not a native promise, or give it as the result of a function. Its `then` method operates in the context of the body at this time. Before, only the read of `then` had the context, and the call had the root context. A query builder that starts its request in `then`, for example of supabase-js, gets the context, as on Node.js.
97
+ - An `enterWith()` in the synchronous part of a transformed async function stays for the caller, as on Node.js.
98
+ - An async generator of transformed code is closer to a native async generator:
99
+ - `return(value)` at a `yield` awaits the value before the `finally` blocks. A rejection goes into the body at the `yield`.
100
+ - `next()` of a complete generator settles before a later microtask.
101
+ - Its methods give a rejected promise for an object that is not an async generator.
102
+ - The object inherits from `%AsyncIteratorPrototype%`, so `Symbol.asyncDispose` and the async iterator helpers are available, and its methods are not enumerable.
103
+ - An error of the `then` getter of an awaited object goes into the body at the `await`.
104
+
3
105
  ## 0.2.3
4
106
 
5
107
  ### Corrections
package/README.md CHANGED
@@ -34,7 +34,7 @@ Browsers do not have `AsyncLocalStorage`. A native `await` does not use code tha
34
34
  1. **A runtime.** It keeps the current context. It patches `Promise.prototype.then`, the timers, the event listeners, the observers and other callback APIs. Thus, each callback gets the context of the code that registered it.
35
35
  2. **A Babel preset and a Vite plugin.** They change each async function into a generator that the runtime operates. Before each step of the function, the runtime sets the context of the function. After the step, the runtime sets the previous context again.
36
36
 
37
- On Node.js, the package uses the native `AsyncLocalStorage` of `node:async_hooks`. No transform and no patch is necessary on Node.js.
37
+ On Node.js, the package uses the native `AsyncLocalStorage` of `node:async_hooks`, and it installs no patch. On Node.js, the transform is necessary only for rule C5 of generators.
38
38
 
39
39
  ## Compared with other tools
40
40
 
@@ -53,11 +53,11 @@ Thus, code that uses `AsyncLocalStorage` on the server can use the same API in t
53
53
  npm install async-browser-context
54
54
  ```
55
55
 
56
- The package needs Node.js 22.18 or later, or 24.11 or later, for the build tools. The runtime operates in the current versions of Chrome, Edge, Firefox and Safari.
56
+ The build tools of the package need Node.js 22.18 or a later version of Node.js 22, or Node.js 24.11 or later. The runtime operates in the current versions of Chrome, Edge, Firefox and Safari.
57
57
 
58
58
  ## Set up the transform
59
59
 
60
- > **CAUTION:** Transform all the code that awaits in a context, also the code in `node_modules`. In code that the transform does not change, the browser runtime cannot set the context after `await`. That code gets the root context: `getStore()` gives `undefined`. It does not get the context of a different operation at any time.
60
+ > **CAUTION:** Transform all the code that awaits in a context, also the code in `node_modules`. In code that the transform does not change, the browser runtime cannot set the context after `await`. That code gets the root context: `getStore()` gives `undefined`, or the `defaultValue` of the storage. It does not get the context of a different operation at any time.
61
61
 
62
62
  ### Vite
63
63
 
@@ -74,14 +74,14 @@ The package needs Node.js 22.18 or later, or 24.11 or later, for the build tools
74
74
 
75
75
  2. Build or start the application as usual.
76
76
 
77
- The plugin transforms the modules of the application and of its dependencies, also in the dev server. It operates after the other plugins, so it gets JavaScript after TypeScript and JSX are compiled. The plugin does not transform the modules of server-side rendering, because Node.js has the native `AsyncLocalStorage`.
77
+ The plugin transforms the modules of the application and of its dependencies, also in the dev server. It also transforms the JavaScript of Vue, Svelte, Astro and MDX components, but not their styles. It operates after the other plugins, so it gets JavaScript after TypeScript and JSX are compiled. The plugin does not transform the modules of server-side rendering, because Node.js has the native `AsyncLocalStorage`.
78
78
 
79
79
  | Option | Default | Function |
80
80
  | --- | --- | --- |
81
- | `include` | All JavaScript and TypeScript modules | A regular expression or a function that selects the modules to transform. |
81
+ | `include` | All JavaScript and TypeScript modules, and the JavaScript of Vue, Svelte, Astro and MDX components | A regular expression or a function that selects the modules to transform. |
82
82
  | `exclude` | None | A regular expression or a function that selects the modules not to transform. |
83
- | `runtime` | `async-browser-context/runtime` | The module that the transformed code imports. |
84
- | `names` | `true` | Set `false` to remove the names of the async functions for the callback hooks. The code is then smaller by 0.1 to 1.6 percent. |
83
+ | `runtime` | `async-browser-context/runtime` | The module that the transformed code imports. It must export the six names of `async-browser-context/runtime`. |
84
+ | `names` | `true` | Set `false` to remove the names of the async functions for the callback hooks. The code is then smaller by 0.1 to 1.8 percent. |
85
85
  | `ssr` | `false` | Set `true` to also transform the modules of server-side rendering, for example for Vitest in Node.js. |
86
86
 
87
87
  ### Babel
@@ -96,7 +96,11 @@ The plugin transforms the modules of the application and of its dependencies, al
96
96
 
97
97
  2. Make sure that Babel transforms the dependencies too. With webpack, do not exclude `node_modules` from `babel-loader`.
98
98
 
99
- The preset operates with Babel 7.22 and later, and with Babel 8. CI examines Babel 7.22, the newest Babel 7 and the newest Babel 8 with the packed package (`pnpm test:babel`).
99
+ For TypeScript and JSX files, also add `@babel/preset-typescript` and `@babel/preset-react`. Babel cannot read these files without them. Put them before the preset of the library in the `presets` list.
100
+
101
+ The preset operates with Babel 7.22 and later, and with Babel 8. The transform of `using` and `await using` declarations needs Babel 7.23.9 or later. CI examines Babel 7.22, the newest Babel 7 and the newest Babel 8 with the packed package (`pnpm test:babel`).
102
+
103
+ The preset does not change the runtime of the library. A directive, `"async-browser-context runtime"`, marks its native async functions. Terser and other minifiers can remove directives. Thus do not give the preset a copy of the runtime that a minifier changed, for example a dependency that bundles and minifies this library. Bundlers minify after the transform of each module, so the usual setups are correct.
100
104
 
101
105
  ### Other build tools
102
106
 
@@ -114,7 +118,7 @@ With the target ES2016, the patch of `then` keeps the context through `await`. A
114
118
 
115
119
  ### Node.js
116
120
 
117
- Do not set up a transform. The `node` export condition selects the Node.js entry, which uses the native `AsyncLocalStorage`.
121
+ The `node` export condition selects the Node.js entry, which uses the native `AsyncLocalStorage`. A transform is not necessary, except for rule C5. A generator keeps the context of its creation only in code that the preset transforms. Without the preset, a generator body gets the context of each `next()` call, as a native generator does.
118
122
 
119
123
  ## Use the API
120
124
 
@@ -132,6 +136,8 @@ storage.getStore(); // "none"
132
136
 
133
137
  The class has `getStore()`, `run()`, `exit()`, `enterWith()`, `disable()`, the static `bind()` and `snapshot()`, and the `name` and `defaultValue` options of Node.js 24.
134
138
 
139
+ `enterWith()` operates as on Node.js. In the synchronous part of an async function, it also changes the store of the caller. Outside all `run()` calls, for example at the top level of a module, the store stays as a default store. The later code of the module and the callbacks that it registers get it. Use `run()` if possible.
140
+
135
141
  **`AsyncContext.Variable` and `AsyncContext.Snapshot`**, the API of the TC39 proposal:
136
142
 
137
143
  ```ts
@@ -164,7 +170,7 @@ addCallbackHook({
164
170
  });
165
171
  ```
166
172
 
167
- `source` names the API, for example `"setTimeout"`, `"addEventListener:click"` or `"await"`. For a step after an `await`, `callback.name` is the name of the async function. The guide [Find the operation of a long task](https://mark1russell7.github.io/AsyncBrowserContext/docs/guides/long-tasks) tells more.
173
+ `source` names the API, for example `"setTimeout"`, `"addEventListener:click"` or `"await"`. For a step after an `await`, `callback.name` is the name of the async function or of the async generator. A callback that a hook schedules does not start the hooks, so a hook cannot start itself without end. The guide [Find the operation of a long task](https://mark1russell7.github.io/AsyncBrowserContext/docs/guides/long-tasks) tells more.
168
174
 
169
175
  ## Entry points
170
176
 
@@ -194,7 +200,7 @@ On Node.js, `AsyncContextManager` uses the native `AsyncLocalStorage`. Do not us
194
200
 
195
201
  ## Context rules
196
202
 
197
- The tests examine each rule on the browser runtime, on the Node.js runtime and in Chromium, Firefox and WebKit.
203
+ The tests of the rules are in `test/rules/`, one file for each rule. Each rule project in Node.js starts them, and Chromium, Firefox and WebKit start them too. The rule projects are the browser runtime with the preset, with SWC and with esbuild, and the Node.js runtime with and without the preset. The table after the rules gives the exceptions.
198
204
 
199
205
  | Rule | The library keeps this rule |
200
206
  | --- | --- |
@@ -212,34 +218,42 @@ The tests examine each rule on the browser runtime, on the Node.js runtime and i
212
218
  | C12 | The library does not keep promises or values in memory after the program has no reference to them. |
213
219
  | C13 | An event listener gets the context of the code that dispatches the event. If that code has the root context, the listener gets the registration context. This is the context of the `addEventListener()` call or of the assignment to the `on...` property. An event that the browser dispatches, for example a click of the user, also gives the registration context. |
214
220
 
221
+ | Rule | Where the tests examine the rule |
222
+ | --- | --- |
223
+ | C5 | Only the projects with the preset examine the rule. The projects without the preset examine the other behavior: a generator body gets the context of each `next()` call. |
224
+ | C9 | `test/rules/c09-c11-isolation.test.ts`, only on the browser runtime. The Node.js runtime has no store of its own. |
225
+ | C10 | `test/rules/c09-c11-isolation.test.ts`, only on the browser runtime in Node.js. A browser cannot load a second copy of the same modules without a second bundle. |
226
+ | C12 | `test/memory/memory.test.ts`, in the project `memory`: the browser runtime in Node.js with `--expose-gc`. |
227
+ | C13 | `test/browser/c13-events.test.ts`, only in Chromium, Firefox and WebKit. |
228
+
215
229
  ## Patched APIs
216
230
 
217
- > **CAUTION:** Import `async-browser-context` before all other modules in the entry file of the application. The library patches global functions when it loads. Code that keeps a reference to `setTimeout` or to another patched function before the library loads does not get the context.
231
+ > **CAUTION:** Import `async-browser-context` before all other modules in the entry file of the application. The library patches global functions when it loads. Code that keeps a reference to `setTimeout` or to another patched function before the library loads does not get the context. A listener that code adds before the library loads, and adds again after, operates two times. The browser then has the listener and a wrapper of it.
218
232
 
219
233
  | Group | APIs |
220
234
  | --- | --- |
221
235
  | Promises | `Promise.prototype.then`, thus also `catch`, `finally` and the combinators |
222
236
  | Timers | `setTimeout`, `setInterval`, `setImmediate`, `queueMicrotask`, `requestAnimationFrame`, `requestIdleCallback`, `scheduler.postTask`, `requestVideoFrameCallback`, `XRSession.requestAnimationFrame` |
223
- | Events | `addEventListener`, `removeEventListener`, all `on...` properties, `MediaQueryList.addListener` |
237
+ | Events | `addEventListener`, `removeEventListener`, all `on...` properties, `MediaQueryList.addListener` and `removeListener` |
224
238
  | Observers | `MutationObserver`, `ResizeObserver`, `IntersectionObserver`, `PerformanceObserver`, `ReportingObserver`, `PressureObserver`, `FinalizationRegistry` |
225
239
  | Streams | The methods of the underlying objects of `ReadableStream`, `WritableStream` and `TransformStream` |
226
- | Callback APIs | `navigator.locks.request`, `HTMLCanvasElement.toBlob`, `Array.fromAsync`, geolocation, `DataTransferItem.getAsString`, the APIs of file system entries, `decodeAudioData`, `MediaSession.setActionHandler`, `Notification.requestPermission`, the callbacks of `RTCPeerConnection`, `startViewTransition`, `NavigateEvent.intercept` |
240
+ | Callback APIs | `navigator.locks.request`, `HTMLCanvasElement.toBlob`, the map function of `Array.fromAsync`, geolocation, `DataTransferItem.getAsString`, the APIs of file system entries, `decodeAudioData`, `MediaSession.setActionHandler`, `Notification.requestPermission`, the callbacks of `RTCPeerConnection`, `startViewTransition` of `Document` and `Element`, `NavigateEvent.intercept` |
227
241
 
228
- The patches keep the names, the lengths and the source text of the native functions. `Function.prototype.toString` gives the source text of the original function.
242
+ The patches keep the names, the lengths and the source text of the native functions. `Function.prototype.toString` gives the source text of the original function. The patched functions are methods, as the native functions: they have no `prototype` property and they are not constructors. They read the options of `addEventListener()` as the DOM does. For streams and option objects, the patches give the browser a Proxy of your object, so frozen objects, getters and private fields operate.
229
243
 
230
244
  ## Boundaries
231
245
 
232
246
  In transformed code, each step gets the context of its own operation. Code without the transform cannot get the context of a different operation (rule C7). At most, that code gets no context after its own native `await`. Where your code meets that code, one function of the library keeps the context:
233
247
 
234
- | The other code | What to do |
235
- | --- | --- |
236
- | Gives a promise, and your code awaits it | Nothing. After the `await`, your code gets its context again. |
237
- | Is async code that a compiler changed before the publish (`__awaiter` of TypeScript, `_asyncToGenerator` of Babel) | Nothing. The helpers continue in `then` callbacks, and the patch of `then` keeps the context. |
238
- | Starts your callback synchronously, or from a timer, an observer or a promise that it registers before its first `await` | Nothing. The patched APIs keep the context. Event listeners follow rule C13. |
239
- | Starts your callback after its own native `await` | `AsyncLocalStorage.bind(callback)` or `AsyncContext.Snapshot.wrap(callback)` |
240
- | Keeps your callback in a list and starts it later from other code | `AsyncLocalStorage.bind(callback)` when you give the callback |
241
- | Reads the context itself after its own native `await` | Give the values as arguments, or transform the code. |
242
- | Operates in a worker or an iframe | Send the values in the message, and use `run()` on the other side. |
248
+ | The other code | What to do | Tests |
249
+ | --- | --- | --- |
250
+ | Gives a promise, and your code awaits it | Nothing. After the `await`, your code gets its context again. | `c07-boundaries`, `c07-untransformed` |
251
+ | Is async code that a compiler changed before the publish (`__awaiter` of TypeScript, `_asyncToGenerator` of Babel) | Nothing. The helpers continue in `then` callbacks, and the patch of `then` keeps the context. | `c07-compiled-dependencies` |
252
+ | Starts your callback synchronously, or from a timer, an observer or a promise that it registers before its first `await` | Nothing. The patched APIs keep the context. Event listeners follow rule C13. | `c07-boundaries`, `c04-then`, `c06-timers`, `browser/patched-apis`, `browser/c13-events` |
253
+ | Starts your callback after its own native `await` | `AsyncLocalStorage.bind(callback)` or `AsyncContext.Snapshot.wrap(callback)` | `c07-boundaries` |
254
+ | Keeps your callback in a list and starts it later from other code | `AsyncLocalStorage.bind(callback)` when you give the callback | `c07-boundaries` |
255
+ | Reads the context itself after its own native `await` | Give the values as arguments, or transform the code. | `c07-untransformed`: the read gets no value |
256
+ | Operates in a worker or an iframe | Send the values in the message, and use `run()` on the other side. | No test |
243
257
 
244
258
  ```ts
245
259
  untransformedLibrary.onDone(AsyncLocalStorage.bind((result) => {
@@ -247,13 +261,13 @@ untransformedLibrary.onDone(AsyncLocalStorage.bind((result) => {
247
261
  }));
248
262
  ```
249
263
 
250
- The Vite plugin transforms the dependencies in `node_modules` by default. Thus, these boundaries are usually only scripts from other servers, browser extensions and code from `eval()` or `new Function()`. The tests in `test/rules/c07-boundaries.test.ts` and `test/rules/c07-compiled-dependencies.test.ts` examine each row. The [boundaries page](https://mark1russell7.github.io/AsyncBrowserContext/docs/concepts/boundaries) of the website gives the details.
264
+ The Vite plugin transforms the dependencies in `node_modules` by default. Thus, these boundaries are usually only scripts from other servers, browser extensions and code from `eval()` or `new Function()`. The "Tests" column names the test files in `test/rules/` and `test/browser/`, without `.test.ts`. The [boundaries page](https://mark1russell7.github.io/AsyncBrowserContext/docs/concepts/boundaries) of the website gives the details.
251
265
 
252
266
  Do not use the library together with zone.js or with another library that patches `Promise.prototype.then`. The two libraries patch the same functions with different rules. For OpenTelemetry, use `AsyncContextManager` in place of the `ZoneContextManager`.
253
267
 
254
268
  ### Other differences of transformed code
255
269
 
256
- - **Generator functions.** A transformed generator function is an ordinary function that gives a generator. `fn.prototype` and `instanceof fn` do not operate as for a native generator function. The generator objects operate as native generator objects.
270
+ - **Generator functions.** A transformed generator function is an ordinary function that gives a bound generator. `fn.prototype` and `instanceof fn` do not operate as for a native generator function. `fn.constructor` is `Function`, not `GeneratorFunction`. Thus a library that examines a function to find a generator function, for example `co` or `is-generator-function`, sees a plain function. The generator objects operate as native generator objects.
257
271
  - **Stack traces.** In transformed code, a stack trace shows the generator and the `coroutine` function of the runtime.
258
272
  - **Profilers.** Between the browser and each callback of a patched API, stack traces and profilers show the wrapper `asyncBrowserContextWrapper`. The Long Animation Frames API of Chromium shows this name in place of your function. `addCallbackHook()` gives the function and the context of each callback.
259
273
 
@@ -272,18 +286,18 @@ These results are from `pnpm bench`: the mean time of each scenario, on Node.js
272
286
 
273
287
  One read with `get()` takes approximately 4 ns. The [documentation website](https://mark1russell7.github.io/AsyncBrowserContext/) shows the full results.
274
288
 
275
- When the page loads, the library installs its patches in approximately 8 ms: the median of Chromium, Firefox and WebKit on the same computer.
289
+ When the page loads, the library installs its patches in approximately 8 ms: the median of Chromium, Firefox and WebKit on the same computer. <!-- TODO(bench) -->
276
290
 
277
- In Chromium, Firefox and WebKit, an `await` in transformed code takes approximately the time of a native `await` (`pnpm bench:browsers`). In Firefox, the patch of `then` adds approximately 0.8 µs to each `await` of a promise. The performance page of the website tells more.
291
+ In most cases, an `await` in transformed code takes more time than a native `await`. In Firefox, the patch of `then` adds approximately 0.8 µs to each `await` of a promise, also in code without the transform. <!-- TODO(bench) --> The performance page of the website gives the time of each workload in Chromium, Firefox and WebKit (`pnpm bench:browsers`).
278
292
 
279
- The runtime is 5.9 kB with gzip, and zone.js 0.16.3 is 13.3 kB. The transform adds 3 to 8 percent to packages with much async code, and nothing to React DOM. In an example application with React DOM, TanStack Query, supabase-js and ky, it adds 2.9 percent (`pnpm bench:size`).
293
+ The runtime is 6.0 kB with gzip, and zone.js 0.16.3 is 11.8 kB. The transform adds 3 to 8.5 percent to packages with much async code, and nothing to React DOM. In an example application with React DOM, TanStack Query, supabase-js and ky, it adds 2.4 percent (`pnpm bench:size`).
280
294
 
281
295
  ## Tests
282
296
 
283
297
  | Command | Function |
284
298
  | --- | --- |
285
299
  | `pnpm test` | All test projects: unit tests, the rules on the browser runtime and on the Node.js runtime, memory tests, and the browser tests |
286
- | `pnpm test:node` | The tests in Node.js only |
300
+ | `pnpm test:node` | The test projects in Node.js, without the memory tests |
287
301
  | `pnpm test:browser` | The tests in Chromium, Firefox and WebKit |
288
302
  | `pnpm smoke` | Packs the package, installs it in a new Vite application, and examines the application in Chromium |
289
303
  | `pnpm test:babel` | Packs the package, transforms a program with the preset in Babel 7.22, the newest Babel 7 and Babel 8, and starts the output |
@@ -293,6 +307,7 @@ The runtime is 5.9 kB with gzip, and zone.js 0.16.3 is 13.3 kB. The transform ad
293
307
  | `pnpm bench:browsers` | The time of `await` and `then` in Chromium, Firefox and WebKit, without the library, with the Babel helper and with the library |
294
308
  | `pnpm bench:size` | The size of the runtime, and the size that the transform adds to a set of npm packages |
295
309
  | `pnpm lint:ste` | The STE linter of the documentation and the TSDoc comments |
310
+ | `pnpm test:ste-lint` | The tests of the STE linter (`tools/ste-lint`) |
296
311
 
297
312
  Set `BROWSERS=chromium,firefox,webkit` to select the browsers. Playwright WebKit does not start on all Windows computers, so the default on Windows is Chromium and Firefox. `docs/testing.md` tells more.
298
313
 
@@ -1,17 +1,17 @@
1
1
  import { type PluginObject, type PluginPass } from "@babel/core";
2
2
  /** The options of the plugin. */
3
3
  export interface AsyncGeneratorHelpersOptions {
4
- /** The module that exports `asyncGenerator` and `OverloadYield`. */
4
+ /** The module that exports the async generator functions of the runtime. */
5
5
  readonly runtime: string;
6
6
  }
7
7
  /**
8
8
  * The Babel plugin that gives the async generators to the driver of the runtime. It sets the
9
- * `helperGenerator` of the file, as `@babel/plugin-transform-runtime` does. Thus, the helpers
10
- * `wrapAsyncGenerator` and `OverloadYield` of `@babel/plugin-transform-async-generator-functions`
11
- * become imports of `asyncGenerator` and `OverloadYield` from the runtime. The helpers `awaitAsyncGenerator` and `asyncGeneratorDelegate` stay in the
12
- * file, and they make the `OverloadYield` values of the runtime.
9
+ * `helperGenerator` of the file, as `@babel/plugin-transform-runtime` does. Thus, the helpers of
10
+ * `@babel/plugin-transform-async-generator-functions` become imports from the runtime.
13
11
  *
14
- * The plugin keeps a `helperGenerator` of an earlier plugin for the other helpers.
12
+ * The plugin sets the generator in `Program` enter, after the `pre` methods of all plugins. A
13
+ * preset that comes before this preset in the list operates later, and its `pre` method can set
14
+ * a generator too. This plugin keeps that generator for the other helpers.
15
15
  */
16
16
  export declare function asyncGeneratorHelpersPlugin(_api: unknown, options: object): PluginObject<PluginPass>;
17
17
  //# sourceMappingURL=async-generator-helpers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"async-generator-helpers.d.ts","sourceRoot":"","sources":["../../src/babel/async-generator-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,KAAK,YAAY,EAAE,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAGxE,iCAAiC;AACjC,MAAM,WAAW,4BAA4B;IACzC,oEAAoE;IACpE,QAAQ,CAAC,OAAO,EAAG,MAAM,CAAC;CAC7B;AAUD;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CAAC,IAAI,EAAG,OAAO,EAAE,OAAO,EAAG,MAAM,GAAI,YAAY,CAAC,UAAU,CAAC,CAsBvG"}
1
+ {"version":3,"file":"async-generator-helpers.d.ts","sourceRoot":"","sources":["../../src/babel/async-generator-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,KAAK,YAAY,EAAE,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAGxE,iCAAiC;AACjC,MAAM,WAAW,4BAA4B;IACzC,4EAA4E;IAC5E,QAAQ,CAAC,OAAO,EAAG,MAAM,CAAC;CAC7B;AAkBD;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CAAC,IAAI,EAAG,OAAO,EAAE,OAAO,EAAG,MAAM,GAAI,YAAY,CAAC,UAAU,CAAC,CAyBvG"}
@@ -1,39 +1,50 @@
1
1
  import { types } from "@babel/core";
2
2
  import { addNamed } from "@babel/helper-module-imports";
3
- /** The Babel helpers that the runtime replaces, and the export of the runtime for each one. */
3
+ /**
4
+ * The Babel helpers of async generators, and the export of the runtime for each one. The
5
+ * runtime gives all four, so the markers of the body (`OverloadYield`) are always the class of
6
+ * the runtime. Without this, another plugin (for example `@babel/plugin-transform-runtime`) can
7
+ * give `awaitAsyncGenerator` with the class of `@babel/runtime`. Then the driver operates each
8
+ * `await` as a `yield`.
9
+ */
4
10
  const REPLACED_HELPERS = {
5
11
  wrapAsyncGenerator: "asyncGenerator",
6
12
  OverloadYield: "OverloadYield",
13
+ awaitAsyncGenerator: "awaitAsyncGenerator",
14
+ asyncGeneratorDelegate: "asyncGeneratorDelegate",
7
15
  };
8
16
  /**
9
17
  * The Babel plugin that gives the async generators to the driver of the runtime. It sets the
10
- * `helperGenerator` of the file, as `@babel/plugin-transform-runtime` does. Thus, the helpers
11
- * `wrapAsyncGenerator` and `OverloadYield` of `@babel/plugin-transform-async-generator-functions`
12
- * become imports of `asyncGenerator` and `OverloadYield` from the runtime. The helpers `awaitAsyncGenerator` and `asyncGeneratorDelegate` stay in the
13
- * file, and they make the `OverloadYield` values of the runtime.
18
+ * `helperGenerator` of the file, as `@babel/plugin-transform-runtime` does. Thus, the helpers of
19
+ * `@babel/plugin-transform-async-generator-functions` become imports from the runtime.
14
20
  *
15
- * The plugin keeps a `helperGenerator` of an earlier plugin for the other helpers.
21
+ * The plugin sets the generator in `Program` enter, after the `pre` methods of all plugins. A
22
+ * preset that comes before this preset in the list operates later, and its `pre` method can set
23
+ * a generator too. This plugin keeps that generator for the other helpers.
16
24
  */
17
25
  export function asyncGeneratorHelpersPlugin(_api, options) {
18
26
  const { runtime } = options;
19
27
  return {
20
28
  name: "async-browser-context/async-generator-helpers",
21
- pre(file) {
22
- const previous = file.get("helperGenerator");
23
- const imports = new Map();
24
- const generator = (name) => {
25
- const exported = REPLACED_HELPERS[name];
26
- if (exported === undefined) {
27
- return previous?.(name);
28
- }
29
- let local = imports.get(exported);
30
- if (local === undefined) {
31
- local = addNamed(file.path, exported, runtime, { nameHint: exported });
32
- imports.set(exported, local);
33
- }
34
- return types.cloneNode(local);
35
- };
36
- file.set("helperGenerator", generator);
29
+ visitor: {
30
+ Program(programPath, state) {
31
+ const file = state.file;
32
+ const previous = file.get("helperGenerator");
33
+ const imports = new Map();
34
+ const generator = (name) => {
35
+ const exported = REPLACED_HELPERS[name];
36
+ if (exported === undefined) {
37
+ return previous?.(name);
38
+ }
39
+ let local = imports.get(exported);
40
+ if (local === undefined) {
41
+ local = addNamed(programPath, exported, runtime, { nameHint: exported });
42
+ imports.set(exported, local);
43
+ }
44
+ return types.cloneNode(local);
45
+ };
46
+ file.set("helperGenerator", generator);
47
+ },
37
48
  },
38
49
  };
39
50
  }
@@ -1 +1 @@
1
- {"version":3,"file":"async-generator-helpers.js","sourceRoot":"","sources":["../../src/babel/async-generator-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAsC,MAAM,aAAa,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AAQxD,+FAA+F;AAC/F,MAAM,gBAAgB,GAAsC;IACxD,kBAAkB,EAAG,gBAAgB;IACrC,aAAa,EAAG,eAAe;CAClC,CAAC;AAIF;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CAAC,IAAc,EAAE,OAAgB;IACxE,MAAM,EAAE,OAAO,EAAE,GAAG,OAAuC,CAAC;IAC5D,OAAO;QACH,IAAI,EAAG,+CAA+C;QACtD,GAAG,CAAC,IAAyB;YACzB,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,iBAAiB,CAAgC,CAAC;YAC5E,MAAM,OAAO,GAAG,IAAI,GAAG,EAA4B,CAAC;YACpD,MAAM,SAAS,GAAqB,CAAC,IAAI,EAAE,EAAE;gBACzC,MAAM,QAAQ,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;gBACxC,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;oBACzB,OAAO,QAAQ,EAAE,CAAC,IAAI,CAAC,CAAC;gBAC5B,CAAC;gBACD,IAAI,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBAClC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;oBACtB,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAG,QAAQ,EAAE,CAAqB,CAAC;oBAC5F,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACjC,CAAC;gBACD,OAAO,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;YAClC,CAAC,CAAC;YACF,IAAI,CAAC,GAAG,CAAC,iBAAiB,EAAE,SAAS,CAAC,CAAC;QAC3C,CAAC;KACJ,CAAC;AACN,CAAC"}
1
+ {"version":3,"file":"async-generator-helpers.js","sourceRoot":"","sources":["../../src/babel/async-generator-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAsC,MAAM,aAAa,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AAQxD;;;;;;GAMG;AACH,MAAM,gBAAgB,GAAsC;IACxD,kBAAkB,EAAG,gBAAgB;IACrC,aAAa,EAAG,eAAe;IAC/B,mBAAmB,EAAG,qBAAqB;IAC3C,sBAAsB,EAAG,wBAAwB;CACpD,CAAC;AAIF;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CAAC,IAAc,EAAE,OAAgB;IACxE,MAAM,EAAE,OAAO,EAAE,GAAG,OAAuC,CAAC;IAC5D,OAAO;QACH,IAAI,EAAG,+CAA+C;QACtD,OAAO,EAAG;YACN,OAAO,CAAC,WAAW,EAAE,KAAK;gBACtB,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;gBACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,iBAAiB,CAAgC,CAAC;gBAC5E,MAAM,OAAO,GAAG,IAAI,GAAG,EAA4B,CAAC;gBACpD,MAAM,SAAS,GAAqB,CAAC,IAAI,EAAE,EAAE;oBACzC,MAAM,QAAQ,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;oBACxC,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;wBACzB,OAAO,QAAQ,EAAE,CAAC,IAAI,CAAC,CAAC;oBAC5B,CAAC;oBACD,IAAI,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;oBAClC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;wBACtB,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAG,QAAQ,EAAE,CAAqB,CAAC;wBAC9F,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;oBACjC,CAAC;oBACD,OAAO,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;gBAClC,CAAC,CAAC;gBACF,IAAI,CAAC,GAAG,CAAC,iBAAiB,EAAE,SAAS,CAAC,CAAC;YAC3C,CAAC;SACJ;KACJ,CAAC;AACN,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { PluginFactory } from "./skip-runtime.js";
2
+ /**
3
+ * The plugin of Babel for `using` declarations changes the blocks of an async function when it
4
+ * visits the function in the main traversal. But the plugin of Babel for async generators
5
+ * changes each async generator before, in its own traversal from `Program`. The block of an
6
+ * async generator then got `await _usingCtx.d()` in a generator, which is a `SyntaxError`.
7
+ *
8
+ * This function gives a plugin that changes the `using` declarations of each async generator
9
+ * in `Program` enter, with the visitor of `resources`. The preset puts it after the plugin of
10
+ * `using` declarations and before the plugin of async generators. The functions with the
11
+ * directive of the runtime stay as they are.
12
+ */
13
+ export declare function asyncGeneratorResources(resources: PluginFactory): PluginFactory;
14
+ //# sourceMappingURL=async-generator-resources.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-generator-resources.d.ts","sourceRoot":"","sources":["../../src/babel/async-generator-resources.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEvD;;;;;;;;;;GAUG;AACH,wBAAgB,uBAAuB,CAAC,SAAS,EAAG,aAAa,GAAI,aAAa,CAwBjF"}
@@ -0,0 +1,38 @@
1
+ import { isRuntimeFunction } from "./runtime-calls.js";
2
+ /**
3
+ * The plugin of Babel for `using` declarations changes the blocks of an async function when it
4
+ * visits the function in the main traversal. But the plugin of Babel for async generators
5
+ * changes each async generator before, in its own traversal from `Program`. The block of an
6
+ * async generator then got `await _usingCtx.d()` in a generator, which is a `SyntaxError`.
7
+ *
8
+ * This function gives a plugin that changes the `using` declarations of each async generator
9
+ * in `Program` enter, with the visitor of `resources`. The preset puts it after the plugin of
10
+ * `using` declarations and before the plugin of async generators. The functions with the
11
+ * directive of the runtime stay as they are.
12
+ */
13
+ export function asyncGeneratorResources(resources) {
14
+ return function asyncGeneratorResourcesPlugin(api, options, dirname) {
15
+ // The empty visitor of a plugin without a visitor changes nothing
16
+ const visitor = resources(api, options, dirname).visitor ?? {};
17
+ return {
18
+ name: "async-browser-context/async-generator-resources",
19
+ visitor: {
20
+ Program(programPath, state) {
21
+ programPath.traverse({
22
+ Function(functionPath) {
23
+ if (isRuntimeFunction(functionPath.node)) {
24
+ functionPath.skip();
25
+ return;
26
+ }
27
+ if (functionPath.node.async && functionPath.node.generator) {
28
+ // A second visit of a changed block finds no using declaration, so nested async generators are no problem
29
+ functionPath.traverse(visitor, state);
30
+ }
31
+ },
32
+ }, state);
33
+ },
34
+ },
35
+ };
36
+ };
37
+ }
38
+ //# sourceMappingURL=async-generator-resources.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-generator-resources.js","sourceRoot":"","sources":["../../src/babel/async-generator-resources.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAGvD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,uBAAuB,CAAC,SAAyB;IAC7D,OAAO,SAAS,6BAA6B,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO;QAC/D,kEAAkE;QAClE,MAAM,OAAO,GAAG,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,OAAO,IAAI,EAAE,CAAC;QAC/D,OAAO;YACH,IAAI,EAAG,iDAAiD;YACxD,OAAO,EAAG;gBACN,OAAO,CAAC,WAAW,EAAE,KAAK;oBACtB,WAAW,CAAC,QAAQ,CAAC;wBACjB,QAAQ,CAAC,YAAuC;4BAC5C,IAAI,iBAAiB,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC;gCACvC,YAAY,CAAC,IAAI,EAAE,CAAC;gCACpB,OAAO;4BACX,CAAC;4BACD,IAAI,YAAY,CAAC,IAAI,CAAC,KAAK,IAAI,YAAY,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;gCACzD,0GAA0G;gCAC1G,YAAY,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;4BAC1C,CAAC;wBACL,CAAC;qBACJ,EAAE,KAAK,CAAC,CAAC;gBACd,CAAC;aACJ;SACJ,CAAC;IACN,CAAC,CAAC;AACN,CAAC"}
@@ -7,7 +7,7 @@ export interface BindGeneratorsOptions {
7
7
  /** The key of the file metadata that tells if the preset changed the file. */
8
8
  export declare const METADATA_KEY = "asyncBrowserContext";
9
9
  /**
10
- * The Babel plugin that binds generators to the context of their creation
10
+ * The Babel plugin that binds sync generators to the context of their creation
11
11
  * (rule C5). It changes the code in `Program` enter, before the async
12
12
  * generator transform changes the async generators.
13
13
  */
@@ -1 +1 @@
1
- {"version":3,"file":"bind-generators.d.ts","sourceRoot":"","sources":["../../src/babel/bind-generators.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,KAAK,YAAY,EAAE,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAGvF,iCAAiC;AACjC,MAAM,WAAW,qBAAqB;IAClC,+CAA+C;IAC/C,QAAQ,CAAC,OAAO,EAAG,MAAM,CAAC;CAC7B;AAED,8EAA8E;AAC9E,eAAO,MAAM,YAAY,wBAAwB,CAAC;AAiFlD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAG,OAAO,EAAE,OAAO,EAAG,MAAM,GAAI,YAAY,CAAC,UAAU,CAAC,CAqChG"}
1
+ {"version":3,"file":"bind-generators.d.ts","sourceRoot":"","sources":["../../src/babel/bind-generators.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,KAAK,YAAY,EAAE,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAIvF,iCAAiC;AACjC,MAAM,WAAW,qBAAqB;IAClC,+CAA+C;IAC/C,QAAQ,CAAC,OAAO,EAAG,MAAM,CAAC;CAC7B;AAED,8EAA8E;AAC9E,eAAO,MAAM,YAAY,wBAAwB,CAAC;AA0HlD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAG,OAAO,EAAE,OAAO,EAAG,MAAM,GAAI,YAAY,CAAC,UAAU,CAAC,CAuChG"}