async-browser-context 0.2.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +45 -30
  3. package/dist/babel/async-generator-helpers.d.ts +6 -6
  4. package/dist/babel/async-generator-helpers.d.ts.map +1 -1
  5. package/dist/babel/async-generator-helpers.js +33 -22
  6. package/dist/babel/async-generator-helpers.js.map +1 -1
  7. package/dist/babel/async-generator-resources.d.ts +14 -0
  8. package/dist/babel/async-generator-resources.d.ts.map +1 -0
  9. package/dist/babel/async-generator-resources.js +38 -0
  10. package/dist/babel/async-generator-resources.js.map +1 -0
  11. package/dist/babel/bind-generators.d.ts +1 -1
  12. package/dist/babel/bind-generators.d.ts.map +1 -1
  13. package/dist/babel/bind-generators.js +88 -44
  14. package/dist/babel/bind-generators.js.map +1 -1
  15. package/dist/babel/name-coroutines.d.ts +14 -8
  16. package/dist/babel/name-coroutines.d.ts.map +1 -1
  17. package/dist/babel/name-coroutines.js +160 -39
  18. package/dist/babel/name-coroutines.js.map +1 -1
  19. package/dist/babel/preset.d.ts +24 -13
  20. package/dist/babel/preset.d.ts.map +1 -1
  21. package/dist/babel/preset.js +37 -9
  22. package/dist/babel/preset.js.map +1 -1
  23. package/dist/babel/runtime-calls.d.ts +22 -0
  24. package/dist/babel/runtime-calls.d.ts.map +1 -0
  25. package/dist/babel/runtime-calls.js +69 -0
  26. package/dist/babel/runtime-calls.js.map +1 -0
  27. package/dist/babel/skip-runtime.d.ts +18 -11
  28. package/dist/babel/skip-runtime.d.ts.map +1 -1
  29. package/dist/babel/skip-runtime.js +52 -16
  30. package/dist/babel/skip-runtime.js.map +1 -1
  31. package/dist/babel/static-members.d.ts +4 -0
  32. package/dist/babel/static-members.d.ts.map +1 -0
  33. package/dist/babel/static-members.js +112 -0
  34. package/dist/babel/static-members.js.map +1 -0
  35. package/dist/core/async-generator.d.ts +26 -8
  36. package/dist/core/async-generator.d.ts.map +1 -1
  37. package/dist/core/async-generator.js +162 -44
  38. package/dist/core/async-generator.js.map +1 -1
  39. package/dist/core/async-local-storage.d.ts +3 -0
  40. package/dist/core/async-local-storage.d.ts.map +1 -1
  41. package/dist/core/async-local-storage.js +3 -0
  42. package/dist/core/async-local-storage.js.map +1 -1
  43. package/dist/core/callback-hook.d.ts +3 -3
  44. package/dist/core/coroutine.d.ts +6 -2
  45. package/dist/core/coroutine.d.ts.map +1 -1
  46. package/dist/core/coroutine.js +35 -21
  47. package/dist/core/coroutine.js.map +1 -1
  48. package/dist/core/function-name.d.ts +9 -0
  49. package/dist/core/function-name.d.ts.map +1 -0
  50. package/dist/core/function-name.js +12 -0
  51. package/dist/core/function-name.js.map +1 -0
  52. package/dist/core/hooks.d.ts +2 -1
  53. package/dist/core/hooks.d.ts.map +1 -1
  54. package/dist/core/hooks.js +21 -6
  55. package/dist/core/hooks.js.map +1 -1
  56. package/dist/core/snapshot.d.ts +2 -1
  57. package/dist/core/snapshot.d.ts.map +1 -1
  58. package/dist/core/snapshot.js +7 -3
  59. package/dist/core/snapshot.js.map +1 -1
  60. package/dist/core/store.d.ts +28 -0
  61. package/dist/core/store.d.ts.map +1 -1
  62. package/dist/core/store.js +90 -20
  63. package/dist/core/store.js.map +1 -1
  64. package/dist/core/variable.d.ts +2 -1
  65. package/dist/core/variable.d.ts.map +1 -1
  66. package/dist/core/variable.js +5 -2
  67. package/dist/core/variable.js.map +1 -1
  68. package/dist/node/index.d.ts +10 -4
  69. package/dist/node/index.d.ts.map +1 -1
  70. package/dist/node/index.js +51 -16
  71. package/dist/node/index.js.map +1 -1
  72. package/dist/node/runtime.d.ts +7 -6
  73. package/dist/node/runtime.d.ts.map +1 -1
  74. package/dist/node/runtime.js +29 -16
  75. package/dist/node/runtime.js.map +1 -1
  76. package/dist/opentelemetry/context-manager.d.ts.map +1 -1
  77. package/dist/opentelemetry/context-manager.js +172 -13
  78. package/dist/opentelemetry/context-manager.js.map +1 -1
  79. package/dist/patches/callbacks.d.ts.map +1 -1
  80. package/dist/patches/callbacks.js +84 -29
  81. package/dist/patches/callbacks.js.map +1 -1
  82. package/dist/patches/events.d.ts.map +1 -1
  83. package/dist/patches/events.js +203 -91
  84. package/dist/patches/events.js.map +1 -1
  85. package/dist/patches/handler-interfaces.d.ts +4 -3
  86. package/dist/patches/handler-interfaces.d.ts.map +1 -1
  87. package/dist/patches/handler-interfaces.js +7 -5
  88. package/dist/patches/handler-interfaces.js.map +1 -1
  89. package/dist/patches/promise.d.ts +3 -0
  90. package/dist/patches/promise.d.ts.map +1 -1
  91. package/dist/patches/promise.js +13 -5
  92. package/dist/patches/promise.js.map +1 -1
  93. package/dist/patches/streams.d.ts.map +1 -1
  94. package/dist/patches/streams.js +36 -16
  95. package/dist/patches/streams.js.map +1 -1
  96. package/dist/patches/timers.d.ts.map +1 -1
  97. package/dist/patches/timers.js +17 -5
  98. package/dist/patches/timers.js.map +1 -1
  99. package/dist/patches/to-string.d.ts +4 -0
  100. package/dist/patches/to-string.d.ts.map +1 -1
  101. package/dist/patches/to-string.js +12 -6
  102. package/dist/patches/to-string.js.map +1 -1
  103. package/dist/runtime.d.ts +3 -3
  104. package/dist/runtime.d.ts.map +1 -1
  105. package/dist/runtime.js +3 -3
  106. package/dist/runtime.js.map +1 -1
  107. package/dist/vite/plugin.d.ts +7 -2
  108. package/dist/vite/plugin.d.ts.map +1 -1
  109. package/dist/vite/plugin.js +30 -6
  110. package/dist/vite/plugin.js.map +1 -1
  111. package/package.json +52 -25
  112. package/src/babel/async-generator-helpers.ts +34 -23
  113. package/src/babel/async-generator-resources.ts +40 -0
  114. package/src/babel/bind-generators.ts +91 -47
  115. package/src/babel/name-coroutines.ts +170 -41
  116. package/src/babel/preset.ts +47 -15
  117. package/src/babel/runtime-calls.ts +73 -0
  118. package/src/babel/skip-runtime.ts +58 -18
  119. package/src/babel/static-members.ts +117 -0
  120. package/src/core/async-generator.ts +169 -46
  121. package/src/core/async-local-storage.ts +3 -0
  122. package/src/core/callback-hook.ts +3 -3
  123. package/src/core/coroutine.ts +35 -21
  124. package/src/core/function-name.ts +11 -0
  125. package/src/core/hooks.ts +23 -6
  126. package/src/core/snapshot.ts +8 -3
  127. package/src/core/store.ts +107 -21
  128. package/src/core/variable.ts +6 -2
  129. package/src/node/index.ts +62 -19
  130. package/src/node/runtime.ts +33 -15
  131. package/src/opentelemetry/context-manager.ts +188 -13
  132. package/src/patches/callbacks.ts +87 -30
  133. package/src/patches/events.ts +249 -103
  134. package/src/patches/handler-interfaces.ts +7 -5
  135. package/src/patches/promise.ts +17 -13
  136. package/src/patches/streams.ts +36 -16
  137. package/src/patches/timers.ts +17 -5
  138. package/src/patches/to-string.ts +12 -6
  139. package/src/runtime.ts +3 -3
  140. package/src/vite/plugin.ts +38 -8
@@ -3,47 +3,58 @@ import { addNamed } from "@babel/helper-module-imports";
3
3
 
4
4
  /** The options of the plugin. */
5
5
  export interface AsyncGeneratorHelpersOptions {
6
- /** The module that exports `asyncGenerator` and `OverloadYield`. */
6
+ /** The module that exports the async generator functions of the runtime. */
7
7
  readonly runtime : string;
8
8
  }
9
9
 
10
- /** The Babel helpers that the runtime replaces, and the export of the runtime for each one. */
10
+ /**
11
+ * The Babel helpers of async generators, and the export of the runtime for each one. The
12
+ * runtime gives all four, so the markers of the body (`OverloadYield`) are always the class of
13
+ * the runtime. Without this, another plugin (for example `@babel/plugin-transform-runtime`) can
14
+ * give `awaitAsyncGenerator` with the class of `@babel/runtime`. Then the driver operates each
15
+ * `await` as a `yield`.
16
+ */
11
17
  const REPLACED_HELPERS : Readonly<Record<string, string>> = {
12
18
  wrapAsyncGenerator : "asyncGenerator",
13
19
  OverloadYield : "OverloadYield",
20
+ awaitAsyncGenerator : "awaitAsyncGenerator",
21
+ asyncGeneratorDelegate : "asyncGeneratorDelegate",
14
22
  };
15
23
 
16
24
  type HelperGenerator = (name : string) => types.Expression | undefined;
17
25
 
18
26
  /**
19
27
  * The Babel plugin that gives the async generators to the driver of the runtime. It sets the
20
- * `helperGenerator` of the file, as `@babel/plugin-transform-runtime` does. Thus, the helpers
21
- * `wrapAsyncGenerator` and `OverloadYield` of `@babel/plugin-transform-async-generator-functions`
22
- * become imports of `asyncGenerator` and `OverloadYield` from the runtime. The helpers `awaitAsyncGenerator` and `asyncGeneratorDelegate` stay in the
23
- * file, and they make the `OverloadYield` values of the runtime.
28
+ * `helperGenerator` of the file, as `@babel/plugin-transform-runtime` does. Thus, the helpers of
29
+ * `@babel/plugin-transform-async-generator-functions` become imports from the runtime.
24
30
  *
25
- * The plugin keeps a `helperGenerator` of an earlier plugin for the other helpers.
31
+ * The plugin sets the generator in `Program` enter, after the `pre` methods of all plugins. A
32
+ * preset that comes before this preset in the list operates later, and its `pre` method can set
33
+ * a generator too. This plugin keeps that generator for the other helpers.
26
34
  */
27
35
  export function asyncGeneratorHelpersPlugin(_api : unknown, options : object) : PluginObject<PluginPass> {
28
36
  const { runtime } = options as AsyncGeneratorHelpersOptions;
29
37
  return {
30
38
  name : "async-browser-context/async-generator-helpers",
31
- pre(file : PluginPass["file"]) {
32
- const previous = file.get("helperGenerator") as HelperGenerator | undefined;
33
- const imports = new Map<string, types.Expression>();
34
- const generator : HelperGenerator = (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(file.path, exported, runtime, { nameHint : exported }) as types.Expression;
42
- imports.set(exported, local);
43
- }
44
- return types.cloneNode(local);
45
- };
46
- file.set("helperGenerator", generator);
39
+ visitor : {
40
+ Program(programPath, state) {
41
+ const file = state.file;
42
+ const previous = file.get("helperGenerator") as HelperGenerator | undefined;
43
+ const imports = new Map<string, types.Expression>();
44
+ const generator : HelperGenerator = (name) => {
45
+ const exported = REPLACED_HELPERS[name];
46
+ if (exported === undefined) {
47
+ return previous?.(name);
48
+ }
49
+ let local = imports.get(exported);
50
+ if (local === undefined) {
51
+ local = addNamed(programPath, exported, runtime, { nameHint : exported }) as types.Expression;
52
+ imports.set(exported, local);
53
+ }
54
+ return types.cloneNode(local);
55
+ };
56
+ file.set("helperGenerator", generator);
57
+ },
47
58
  },
48
59
  };
49
60
  }
@@ -0,0 +1,40 @@
1
+ import type { NodePath, PluginObject, PluginPass, types } from "@babel/core";
2
+ import { isRuntimeFunction } from "./runtime-calls.js";
3
+ import type { PluginFactory } from "./skip-runtime.js";
4
+
5
+ /**
6
+ * The plugin of Babel for `using` declarations changes the blocks of an async function when it
7
+ * visits the function in the main traversal. But the plugin of Babel for async generators
8
+ * changes each async generator before, in its own traversal from `Program`. The block of an
9
+ * async generator then got `await _usingCtx.d()` in a generator, which is a `SyntaxError`.
10
+ *
11
+ * This function gives a plugin that changes the `using` declarations of each async generator
12
+ * in `Program` enter, with the visitor of `resources`. The preset puts it after the plugin of
13
+ * `using` declarations and before the plugin of async generators. The functions with the
14
+ * directive of the runtime stay as they are.
15
+ */
16
+ export function asyncGeneratorResources(resources : PluginFactory) : PluginFactory {
17
+ return function asyncGeneratorResourcesPlugin(api, options, dirname) : PluginObject<PluginPass> {
18
+ // The empty visitor of a plugin without a visitor changes nothing
19
+ const visitor = resources(api, options, dirname).visitor ?? {};
20
+ return {
21
+ name : "async-browser-context/async-generator-resources",
22
+ visitor : {
23
+ Program(programPath, state) {
24
+ programPath.traverse({
25
+ Function(functionPath : NodePath<types.Function>) {
26
+ if (isRuntimeFunction(functionPath.node)) {
27
+ functionPath.skip();
28
+ return;
29
+ }
30
+ if (functionPath.node.async && functionPath.node.generator) {
31
+ // A second visit of a changed block finds no using declaration, so nested async generators are no problem
32
+ functionPath.traverse(visitor, state);
33
+ }
34
+ },
35
+ }, state);
36
+ },
37
+ },
38
+ };
39
+ };
40
+ }
@@ -1,5 +1,6 @@
1
1
  import { types, type NodePath, type PluginObject, type PluginPass } from "@babel/core";
2
2
  import { addNamed } from "@babel/helper-module-imports";
3
+ import { isRuntimeCallee, isRuntimeFunction } from "./runtime-calls.js";
3
4
 
4
5
  /** The options of the plugin. */
5
6
  export interface BindGeneratorsOptions {
@@ -10,44 +11,22 @@ export interface BindGeneratorsOptions {
10
11
  /** The key of the file metadata that tells if the preset changed the file. */
11
12
  export const METADATA_KEY = "asyncBrowserContext";
12
13
 
13
- /**
14
- * The local names of the async generator helper: `wrapAsyncGenerator` of
15
- * `@babel/plugin-transform-async-generator-functions`, or `asyncGenerator` of the runtime,
16
- * which the preset gives in its place. Babel gives them an underscore.
17
- */
18
- const ASYNC_GENERATOR_HELPER = /^_(wrapAsyncGenerator|asyncGenerator)\d*$/;
19
- /** The local names that `addNamed` gives to `bindGenerator`. */
20
- const BIND_GENERATOR_NAME = /^_bindGenerator\d*$/;
21
-
22
14
  type FunctionPath = NodePath<types.Function>;
23
15
 
24
- /** This function gives `true` if `path` is the generator that Babel gives to its async generator helper. */
25
- function isAsyncGeneratorHelperArgument(path : FunctionPath) : boolean {
26
- const parent = path.parent;
27
- if (!types.isCallExpression(parent)) {
28
- return false;
29
- }
30
- if (types.isIdentifier(parent.callee)) {
31
- return ASYNC_GENERATOR_HELPER.test(parent.callee.name);
32
- }
33
- // CommonJS output of the preset: _runtime.asyncGenerator or (0, _runtime.asyncGenerator)
34
- const member = types.isSequenceExpression(parent.callee) ? parent.callee.expressions.at(-1) : parent.callee;
35
- return types.isMemberExpression(member) && types.isIdentifier(member.property, { name : "asyncGenerator" });
36
- }
37
-
38
16
  /**
39
- * This function gives `true` if `callee` is the `bindGenerator` function of
40
- * the runtime: an import, or `_runtime.bindGenerator` in CommonJS output,
41
- * also in the form `(0, _runtime.bindGenerator)`.
17
+ * This function gives `true` if `path` is the generator that a driver of the runtime operates:
18
+ * the argument of `coroutine` or `asyncGenerator`. The driver keeps the context itself, so the
19
+ * plugin does not bind it. This is the case when the preset transforms its own output again.
20
+ * The generator of a Babel helper, for example `_wrapAsyncGenerator`, gets a binding.
42
21
  */
43
- function isBindGeneratorCallee(callee : types.Node, path : NodePath, runtime : string) : boolean {
44
- if (types.isIdentifier(callee)) {
45
- // Stryker disable next-line StringLiteral: referencesImport with an empty name accepts each import of the runtime, which gives the same result here
46
- return BIND_GENERATOR_NAME.test(callee.name) || path.referencesImport(runtime, "bindGenerator");
22
+ function isDriverArgument(path : FunctionPath, runtime : string) : boolean {
23
+ // A function always has a parent path: at least the program
24
+ const call = path.parentPath as NodePath;
25
+ if (!call.isCallExpression() || call.node.arguments[0] !== path.node) {
26
+ return false;
47
27
  }
48
- // Stryker disable next-line UnaryOperator: the sequence (0, _runtime.bindGenerator) has two expressions, so at(1) gives the same expression
49
- const member = types.isSequenceExpression(callee) ? callee.expressions.at(-1) : callee;
50
- return types.isMemberExpression(member) && types.isIdentifier(member.property, { name : "bindGenerator" });
28
+ const callee = call.get("callee");
29
+ return isRuntimeCallee(callee, runtime, "coroutine") || isRuntimeCallee(callee, runtime, "asyncGenerator");
51
30
  }
52
31
 
53
32
  /** This function gives `true` if this plugin already changed the generator: `bindGenerator((function* () {...})())`. */
@@ -56,14 +35,55 @@ function isAlreadyBound(path : FunctionPath, runtime : string) : boolean {
56
35
  const call = path.parentPath as NodePath;
57
36
  const outer = call.parentPath as NodePath;
58
37
  return call.isCallExpression() && call.node.callee === path.node
59
- && outer.isCallExpression() && isBindGeneratorCallee(outer.node.callee, outer.get("callee"), runtime);
38
+ && outer.isCallExpression() && isRuntimeCallee(outer.get("callee"), runtime, "bindGenerator");
60
39
  }
61
40
 
62
41
  /**
63
- * This function changes one generator function. The function stays the same kind of
64
- * function, with the same name and parameters, so declarations stay hoisted
65
- * and `length` does not change. The body moves into an inner generator, and
66
- * the function gives `bindGenerator(inner())`:
42
+ * This function gives the names of the parameters that the body declares again with `var` or
43
+ * with a function declaration. In the original function, such a variable starts with the value
44
+ * of the parameter. A function declaration in a block of sloppy code is not hoisted over it. The inner
45
+ * function gets these names as its parameters, so the values stay the same.
46
+ */
47
+ function redeclaredParameters(path : FunctionPath) : string[] {
48
+ const parameters = new Set<string>();
49
+ for (const parameter of path.node.params) {
50
+ for (const name of Object.keys(types.getBindingIdentifiers(parameter as types.Node))) {
51
+ parameters.add(name);
52
+ }
53
+ }
54
+ const redeclared = new Set<string>();
55
+ path.get("body").traverse({
56
+ Function(inner) {
57
+ // A function declaration in a block of sloppy code is hoisted (Annex B.3.3), but not
58
+ // over a parameter with the same name. In the inner generator, the name is no parameter.
59
+ if (inner.isFunctionDeclaration()) {
60
+ // A function declaration in a body always has a name
61
+ const { name } = inner.node.id as types.Identifier;
62
+ if (parameters.has(name)) {
63
+ redeclared.add(name);
64
+ }
65
+ }
66
+ inner.skip();
67
+ },
68
+ VariableDeclaration(declaration) {
69
+ if (declaration.node.kind !== "var") {
70
+ return;
71
+ }
72
+ for (const name of Object.keys(declaration.getBindingIdentifiers())) {
73
+ if (parameters.has(name)) {
74
+ redeclared.add(name);
75
+ }
76
+ }
77
+ },
78
+ });
79
+ return [...redeclared];
80
+ }
81
+
82
+ /**
83
+ * This function changes one generator function. The function keeps its name and its
84
+ * parameters, so a declaration stays hoisted and `length` does not change. It becomes a plain
85
+ * function: `fn.constructor` is `Function`, not `GeneratorFunction`. The body moves into an
86
+ * inner generator, and the function gives `bindGenerator(inner())`:
67
87
  *
68
88
  * ```js
69
89
  * function* numbers(limit) { ...body... }
@@ -78,9 +98,10 @@ function bindGeneratorFunction(path : FunctionPath, bindGenerator : types.Expres
78
98
  const node = path.node;
79
99
  // A generator function always has a block body: an arrow function cannot be a generator
80
100
  const body = node.body as types.BlockStatement;
81
- const inner = types.functionExpression(null, [], types.blockStatement(body.body), true, node.async);
101
+ const passed = redeclaredParameters(path);
102
+ const inner = types.functionExpression(null, passed.map((name) => types.identifier(name)), types.blockStatement(body.body), true, node.async);
82
103
  node.body = types.blockStatement(
83
- [types.returnStatement(types.callExpression(bindGenerator, [types.callExpression(inner, [])]))],
104
+ [types.returnStatement(types.callExpression(bindGenerator, [types.callExpression(inner, passed.map((name) => types.identifier(name)))]))],
84
105
  body.directives,
85
106
  );
86
107
  node.generator = false;
@@ -90,7 +111,28 @@ function bindGeneratorFunction(path : FunctionPath, bindGenerator : types.Expres
90
111
  }
91
112
 
92
113
  /**
93
- * The Babel plugin that binds generators to the context of their creation
114
+ * A generator declaration in a block of a script (sloppy mode) is not hoisted out of the block,
115
+ * but a plain function declaration is (Annex B.3.3). The changed declaration thus becomes a
116
+ * `let` at the start of its block, with the same name.
117
+ */
118
+ function keepBlockScope(path : FunctionPath) : void {
119
+ // A function and a block always have a parent path: at least the program
120
+ const block = path.parentPath as NodePath;
121
+ if (!block.isBlockStatement() || (block.parentPath as NodePath).isFunction() || path.isInStrictMode()) {
122
+ return;
123
+ }
124
+ // Only a function declaration is a statement of a block, and it always has a name
125
+ const { id, params, body } = path.node as types.FunctionDeclaration;
126
+ const name = (id as types.Identifier).name;
127
+ const declaration = types.variableDeclaration("let", [
128
+ types.variableDeclarator(types.identifier(name), types.functionExpression(types.identifier(name), params, body)),
129
+ ]);
130
+ path.remove();
131
+ block.unshiftContainer("body", declaration);
132
+ }
133
+
134
+ /**
135
+ * The Babel plugin that binds sync generators to the context of their creation
94
136
  * (rule C5). It changes the code in `Program` enter, before the async
95
137
  * generator transform changes the async generators.
96
138
  */
@@ -109,20 +151,22 @@ export function bindGeneratorsPlugin(_api : unknown, options : object) : PluginO
109
151
  programPath.traverse({
110
152
  Function(path) {
111
153
  const node = path.node;
154
+ if (isRuntimeFunction(node)) {
155
+ // The native async functions of the runtime stay native (skip-runtime.ts)
156
+ path.skip();
157
+ return;
158
+ }
112
159
  if (node.async) {
160
+ // The async transforms change this function
113
161
  changed = true;
114
162
  }
115
163
  // The driver of the runtime keeps the context of an async generator (asyncGenerator)
116
- if (!node.generator || node.async || isAsyncGeneratorHelperArgument(path) || isAlreadyBound(path, runtime)) {
164
+ if (!node.generator || node.async || isDriverArgument(path, runtime) || isAlreadyBound(path, runtime)) {
117
165
  return;
118
166
  }
119
167
  changed = true;
120
168
  bindGeneratorFunction(path, bindGenerator());
121
- },
122
- ForOfStatement(path) {
123
- if (path.node.await) {
124
- changed = true;
125
- }
169
+ keepBlockScope(path);
126
170
  },
127
171
  });
128
172
  if (changed) {
@@ -1,123 +1,252 @@
1
1
  import { types, type NodePath, type PluginObject, type PluginPass } from "@babel/core";
2
+ import { isRuntimeCallee, isRuntimeFunction } from "./runtime-calls.js";
2
3
 
3
4
  /** The options of the plugin. */
4
5
  export interface NameCoroutinesOptions {
5
- /** The module that exports `coroutine`. */
6
+ /** The module that exports `coroutine` and `asyncGenerator`. */
6
7
  readonly runtime : string;
7
8
  }
8
9
 
9
- /** The local names that Babel gives to the import of `coroutine`. */
10
- const COROUTINE_NAME = /^_coroutine\d*$/;
11
-
12
10
  /** The assignment operators that give a name to an anonymous function, as in the specification (NamedEvaluation). */
13
11
  const NAMING_OPERATORS = new Set(["=", "&&=", "||=", "??="]);
14
12
 
15
- /** This function gives the name of a property key, or `undefined` if the name is known only at run time. */
16
- function keyName(key : types.Node, computed : boolean) : string | undefined {
13
+ /**
14
+ * This function gives the name of a property key, or `undefined` if the name is known only at run time.
15
+ * The plugin of static members (static-members.ts) uses it too.
16
+ */
17
+ export function keyName(key : types.Node, computed : boolean) : string | undefined {
17
18
  if (types.isStringLiteral(key)) {
18
19
  return key.value;
19
20
  }
20
21
  if (types.isNumericLiteral(key)) {
21
22
  return String(key.value);
22
23
  }
24
+ if (types.isBigIntLiteral(key)) {
25
+ // Babel 8 gives a bigint, and Babel 7 gives the text of the number, for example "0x10"
26
+ return String(BigInt(key.value));
27
+ }
23
28
  if (computed) {
24
29
  return undefined;
25
30
  }
26
31
  if (types.isIdentifier(key)) {
27
32
  return key.name;
28
33
  }
34
+ // A decimal literal of Babel 7 gets no name
29
35
  return types.isPrivateName(key) ? `#${key.id.name}` : undefined;
30
36
  }
31
37
 
38
+ /** This function gives `true` for a TypeScript or Flow wrapper of an expression, which does not change the name of a function. */
39
+ function isTypeWrapper(path : NodePath) : boolean {
40
+ return path.isTSAsExpression() || path.isTSSatisfiesExpression() || path.isTSNonNullExpression()
41
+ || path.isTSTypeAssertion() || path.isTypeCastExpression() || path.isParenthesizedExpression();
42
+ }
43
+
44
+ /** This function gives the name of an identifier, or `undefined` for a pattern or a member expression. */
45
+ function identifierName(node : types.Node) : string | undefined {
46
+ return types.isIdentifier(node) ? node.name : undefined;
47
+ }
48
+
49
+ /**
50
+ * This function gives the name that `parent` gives to an anonymous function in it, or `undefined`.
51
+ * A function cannot be the target of a declarator or an assignment, so there it is the value. As a
52
+ * computed key, it gets no name from `keyName`.
53
+ */
54
+ function nameFromParent(parent : types.Node) : string | undefined {
55
+ if (types.isVariableDeclarator(parent)) {
56
+ return identifierName(parent.id);
57
+ }
58
+ if (types.isAssignmentExpression(parent)) {
59
+ return NAMING_OPERATORS.has(parent.operator) ? identifierName(parent.left) : undefined;
60
+ }
61
+ if (types.isAssignmentPattern(parent)) {
62
+ return identifierName(parent.left);
63
+ }
64
+ if (types.isObjectProperty(parent) || types.isClassProperty(parent) || types.isClassPrivateProperty(parent) || types.isClassAccessorProperty(parent)) {
65
+ // A private property has no computed field
66
+ return keyName(parent.key, (parent as { computed? : boolean }).computed === true);
67
+ }
68
+ return types.isExportDefaultDeclaration(parent) ? "default" : undefined;
69
+ }
70
+
32
71
  /**
33
72
  * This function gives the `name` that JavaScript gives to the function, or
34
73
  * `undefined` if the name is not known before run time.
35
74
  */
36
75
  export function functionName(path : NodePath<types.Function>) : string | undefined {
37
76
  const node = path.node;
38
- if ((types.isFunctionDeclaration(node) || types.isFunctionExpression(node)) && node.id) {
39
- return node.id.name;
77
+ // Only a function declaration or a function expression has an id. The parser gives null to the other functions.
78
+ const id = (node as types.FunctionExpression).id;
79
+ if (id != null) {
80
+ return id.name;
40
81
  }
41
- if (types.isObjectMethod(node) || types.isClassMethod(node) || types.isClassPrivateMethod(node)) {
82
+ if (types.isMethod(node)) {
42
83
  return keyName(node.key, node.computed === true);
43
84
  }
44
- const parent = path.parent;
45
- if (types.isVariableDeclarator(parent) && parent.init === node && types.isIdentifier(parent.id)) {
46
- return parent.id.name;
85
+ // `const h = (async () => {}) as Handler` names the function `h`. A function and a wrapper always have a parent path.
86
+ let parentPath = path.parentPath as NodePath;
87
+ while (isTypeWrapper(parentPath)) {
88
+ parentPath = parentPath.parentPath as NodePath;
89
+ }
90
+ return nameFromParent(parentPath.node);
91
+ }
92
+
93
+ /**
94
+ * Where the async transform has no name for the function, for example in a class field or as
95
+ * an argument, it gives an anonymous wrapper:
96
+ *
97
+ * ```js
98
+ * function () { var _ref = _coroutine(function* (value) {...}, "save"); return function (_x) { return _ref.apply(this, arguments); }; }()
99
+ * ```
100
+ *
101
+ * This function gives that wrapper the name of the source, so `fn.name` stays the same. The
102
+ * wrapper uses only `_ref`, `this` and `arguments`. The name of the function hides a `_ref` with
103
+ * the same name, for example for a field named `_ref`. Thus `_ref` then gets a new name first. A name that a function expression cannot have, for example `eval`,
104
+ * `arguments` or `"my-handler"`, goes to the `name` property with `Object.defineProperty`.
105
+ */
106
+ function nameReturnedWrapper(call : NodePath<types.CallExpression>, name : string) : void {
107
+ // A call is always in a statement, so it has a parent path and a grandparent path. In the other
108
+ // forms of the async transform, the next statement is not a return of a function expression,
109
+ // or there is no next statement, for example in a class field.
110
+ const declarator = call.parentPath as NodePath;
111
+ const declaration = declarator.parentPath as NodePath;
112
+ const next = declaration.getSibling((declaration.key as number) + 1);
113
+ if (next.isFunctionDeclaration()) {
114
+ nameDeclaredWrapper(next, declaration.getSibling((declaration.key as number) + 2), name);
115
+ return;
47
116
  }
48
- if (types.isAssignmentExpression(parent) && parent.right === node && NAMING_OPERATORS.has(parent.operator) && types.isIdentifier(parent.left)) {
49
- return parent.left.name;
117
+ if (!next.isReturnStatement() || !next.get("argument").isFunctionExpression()) {
118
+ return;
50
119
  }
51
- if (types.isAssignmentPattern(parent) && parent.right === node && types.isIdentifier(parent.left)) {
52
- return parent.left.name;
120
+ // A named function expression gets a wrapper with the same name, so a second name changes nothing
121
+ const returnedPath = next.get("argument") as NodePath<types.FunctionExpression>;
122
+ const returned = returnedPath.node;
123
+ // A class body and a module are strict code, where a function cannot have the name eval or arguments
124
+ if (types.isValidIdentifier(name) && !STRICT_BIND_ONLY.has(name)) {
125
+ // Only a declarator gives `var _ref = <call>` before a returned function expression
126
+ const reference = (declarator.node as types.VariableDeclarator).id;
127
+ if (types.isIdentifier(reference, { name })) {
128
+ // `_ref` is a new name of Babel, so only its declaration and the wrapper use it
129
+ const renamed = declaration.scope.generateUidIdentifier(name).name;
130
+ reference.name = renamed;
131
+ renameIdentifiers(returned, name, renamed);
132
+ }
133
+ returned.id = types.identifier(name);
134
+ return;
53
135
  }
54
- if ((types.isObjectProperty(parent) || types.isClassProperty(parent) || types.isClassPrivateProperty(parent)) && parent.value === node) {
55
- return keyName(parent.key, "computed" in parent && parent.computed === true);
136
+ if (next.scope.getBinding("Object") !== undefined) {
137
+ // The code has its own Object, so the global function is not available
138
+ return;
56
139
  }
57
- return types.isExportDefaultDeclaration(parent) ? "default" : undefined;
140
+ returnedPath.replaceWith(withName(returned, name));
58
141
  }
59
142
 
60
- /** This function gives `true` if `callee` is the `coroutine` function of the runtime, also in CommonJS output. */
61
- function isCoroutineCallee(callee : types.Node, path : NodePath, runtime : string) : boolean {
62
- if (types.isIdentifier(callee)) {
63
- return COROUTINE_NAME.test(callee.name) || path.referencesImport(runtime, "coroutine");
143
+ /**
144
+ * A key is not always a binding name, for example `"a b"`, `42` or `default`. For such a key,
145
+ * the async transform gives a wrapper declaration with a binding name that it makes from the key:
146
+ *
147
+ * ```js
148
+ * function () { var _a_b = _coroutine(function* () {...}, "a b"); function a_b() {...} return a_b; }()
149
+ * ```
150
+ *
151
+ * This function gives that wrapper the name of the source with `Object.defineProperty`, if the
152
+ * two names are not the same.
153
+ */
154
+ function nameDeclaredWrapper(wrapper : NodePath<types.FunctionDeclaration>, after : ReturnType<NodePath["getSibling"]>, name : string) : void {
155
+ const id = wrapper.node.id;
156
+ if (id === null || id === undefined || id.name === name || !after.isReturnStatement()) {
157
+ return;
158
+ }
159
+ const returned = after.node.argument;
160
+ if (!types.isIdentifier(returned, { name : id.name }) || after.scope.getBinding("Object") !== undefined) {
161
+ return;
64
162
  }
65
- const member = types.isSequenceExpression(callee) ? callee.expressions.at(-1) : callee;
66
- return types.isMemberExpression(member) && types.isIdentifier(member.property, { name : "coroutine" });
163
+ after.get("argument").replaceWith(withName(returned, name));
164
+ }
165
+
166
+ /** This function gives `Object.defineProperty(fn, "name", { value : name, configurable : true })`, which gives `fn`. */
167
+ function withName(fn : types.Expression, name : string) : types.CallExpression {
168
+ const descriptor = types.objectExpression([
169
+ types.objectProperty(types.identifier("value"), types.stringLiteral(name)),
170
+ types.objectProperty(types.identifier("configurable"), types.booleanLiteral(true)),
171
+ ]);
172
+ return types.callExpression(
173
+ types.memberExpression(types.identifier("Object"), types.identifier("defineProperty")),
174
+ [fn, types.stringLiteral("name"), descriptor],
175
+ );
67
176
  }
68
177
 
69
- /** The key of the names of one file in the plugin state. */
70
- const NAMES_KEY = "async-browser-context/coroutine-names";
178
+ /** The names that strict code cannot bind, also as the name of a function expression. */
179
+ const STRICT_BIND_ONLY = new Set(["eval", "arguments"]);
180
+
181
+ /** This function gives each identifier `from` in `node` the name `to`. */
182
+ function renameIdentifiers(node : types.Node, from : string, to : string) : void {
183
+ types.traverseFast(node, (child) => {
184
+ if (types.isIdentifier(child) && child.name === from) {
185
+ child.name = to;
186
+ }
187
+ });
188
+ }
71
189
 
72
190
  /**
73
191
  * The Babel plugin that gives the name of each async function to `coroutine`:
74
- * `_coroutine(function* () {...}, "load")`. The generator function of
75
- * `@babel/plugin-transform-async-to-generator` has no name, and the callback
76
- * hooks of the runtime show the name of the async function.
192
+ * `_coroutine(function* () {...}, "load")`, and of each async generator to
193
+ * `asyncGenerator`. The generator function of the Babel transforms has no name,
194
+ * and the callback hooks of the runtime show the name of the function.
77
195
  *
78
- * In `Program` enter, before the async transform, the plugin records the
196
+ * In `Program` enter, before the async transforms, the plugin records the
79
197
  * name of each async function. In `Program` exit, it adds the name to each
80
- * `coroutine` call. For a plain function, the async transform keeps the
81
- * function node as the argument of `coroutine`. For a method, the call is in
82
- * the body of the method.
198
+ * call of `coroutine` or `asyncGenerator`. For a plain function, the async
199
+ * transform keeps the function node as the argument of the call. For a method,
200
+ * the call is in the body of the method. A different call, for example a call
201
+ * that another plugin adds to a method, gets no name.
83
202
  */
84
203
  export function nameCoroutinesPlugin(_api : unknown, options : object) : PluginObject<PluginPass> {
85
204
  const { runtime } = options as NameCoroutinesOptions;
205
+ // The names of the async functions of each file, from Program enter to Program exit
206
+ const namesOfFile = new WeakMap<PluginPass, WeakMap<types.Node, string>>();
86
207
  return {
87
208
  name : "async-browser-context/name-coroutines",
88
209
  visitor : {
89
210
  Program : {
90
211
  enter(programPath, state) {
91
212
  const names = new WeakMap<types.Node, string>();
213
+ namesOfFile.set(state, names);
92
214
  programPath.traverse({
93
215
  Function(path) {
94
- if (!path.node.async || path.node.generator) {
216
+ if (isRuntimeFunction(path.node)) {
217
+ // The native async functions of the runtime stay native (skip-runtime.ts)
218
+ path.skip();
219
+ return;
220
+ }
221
+ if (!path.node.async) {
95
222
  return;
96
223
  }
97
224
  const name = functionName(path);
98
- if (name !== undefined && name !== "") {
225
+ // The empty name, for example of the key "", is no name
226
+ if (name) {
99
227
  names.set(path.node, name);
100
228
  }
101
229
  },
102
230
  });
103
- state.set(NAMES_KEY, names);
104
231
  },
105
232
  exit(programPath, state) {
106
- const names = state.get(NAMES_KEY) as WeakMap<types.Node, string>;
233
+ const names = namesOfFile.get(state) as WeakMap<types.Node, string>;
107
234
  programPath.traverse({
108
235
  CallExpression(path) {
109
- const { callee, arguments : args } = path.node;
236
+ const { arguments : args } = path.node;
110
237
  const [body] = args;
111
- if (args.length !== 1 || !types.isFunctionExpression(body) || !body.generator) {
238
+ if (args.length !== 1 || !types.isFunctionExpression(body, { generator : true })) {
112
239
  return;
113
240
  }
114
- if (!isCoroutineCallee(callee, path.get("callee"), runtime)) {
241
+ const callee = path.get("callee");
242
+ if (!isRuntimeCallee(callee, runtime, "coroutine") && !isRuntimeCallee(callee, runtime, "asyncGenerator")) {
115
243
  return;
116
244
  }
117
245
  const parent = path.getFunctionParent()?.node;
118
246
  const name = names.get(body) ?? (types.isMethod(parent) ? names.get(parent) : undefined);
119
247
  if (name !== undefined) {
120
248
  args.push(types.stringLiteral(name));
249
+ nameReturnedWrapper(path, name);
121
250
  }
122
251
  },
123
252
  });