@bitfab/sdk 0.64.23 → 0.64.25

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 (100) hide show
  1. package/dist/{chunk-ZNDFNAQD.js → chunk-DY52FEEM.js} +2 -2
  2. package/dist/{chunk-ZNDFNAQD.js.map → chunk-DY52FEEM.js.map} +1 -1
  3. package/dist/{chunk-WS7CB5H3.js → chunk-EFGQRVMT.js} +2 -2
  4. package/dist/chunk-GSHCHCB5.js +433 -0
  5. package/dist/chunk-GSHCHCB5.js.map +1 -0
  6. package/dist/chunk-IBWW3SP4.js +45 -0
  7. package/dist/chunk-IBWW3SP4.js.map +1 -0
  8. package/dist/{chunk-FWC3KDJ4.js → chunk-JNVDKPFL.js} +6 -6
  9. package/dist/chunk-JNVDKPFL.js.map +1 -0
  10. package/dist/{chunk-OXFZJP4E.js → chunk-MN3E2RUU.js} +6 -8
  11. package/dist/chunk-MN3E2RUU.js.map +1 -0
  12. package/dist/{chunk-A5DSCY6A.js → chunk-OMWPLB5R.js} +2 -2
  13. package/dist/{chunk-A5DSCY6A.js.map → chunk-OMWPLB5R.js.map} +1 -1
  14. package/dist/{chunk-WMMHAWXS.js → chunk-R7SJXFMB.js} +4 -4
  15. package/dist/{chunk-KHA4A746.js → chunk-ULKKTYOL.js} +2 -2
  16. package/dist/{http-PKBJRGNK.js → http-GDTWWWYY.js} +2 -2
  17. package/dist/{http-M6AWJWPW.js → http-QXJJB2F5.js} +2 -2
  18. package/dist/index.cjs +1 -1
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +48 -2
  21. package/dist/index.d.ts +48 -2
  22. package/dist/index.js +3 -3
  23. package/dist/node.cjs +1 -1
  24. package/dist/node.cjs.map +1 -1
  25. package/dist/node.d.cts +1 -1
  26. package/dist/node.d.ts +1 -1
  27. package/dist/node.js +3 -3
  28. package/dist/{replay-JAYRFN3X.js → replay-DC3PID7Q.js} +3 -3
  29. package/dist/{replay-OCHSU4JN.js → replay-VXQGVZXM.js} +3 -3
  30. package/dist/replayCli.js +3 -3
  31. package/dist/seedCli.js +3 -3
  32. package/dist/transform/babel.cjs +68 -34
  33. package/dist/transform/babel.cjs.map +1 -1
  34. package/dist/transform/babel.d.cts +2 -2
  35. package/dist/transform/babel.d.ts +2 -2
  36. package/dist/transform/babel.js +2 -374
  37. package/dist/transform/babel.js.map +1 -1
  38. package/dist/transform/bun.cjs +389 -464
  39. package/dist/transform/bun.cjs.map +1 -1
  40. package/dist/transform/bun.js +3 -3
  41. package/dist/transform/esbuild.cjs +389 -464
  42. package/dist/transform/esbuild.cjs.map +1 -1
  43. package/dist/transform/esbuild.js +3 -3
  44. package/dist/transform/loaderRuntime.cjs +448 -498
  45. package/dist/transform/loaderRuntime.cjs.map +1 -1
  46. package/dist/transform/loaderRuntime.js +90 -70
  47. package/dist/transform/loaderRuntime.js.map +1 -1
  48. package/dist/transform/nest.cjs +389 -464
  49. package/dist/transform/nest.cjs.map +1 -1
  50. package/dist/transform/nest.js +3 -3
  51. package/dist/transform/next.cjs +389 -464
  52. package/dist/transform/next.cjs.map +1 -1
  53. package/dist/transform/next.js +3 -3
  54. package/dist/transform/nodeLoader.js +451 -498
  55. package/dist/transform/nodeLoader.js.map +1 -1
  56. package/dist/transform/rolldown.cjs +389 -464
  57. package/dist/transform/rolldown.cjs.map +1 -1
  58. package/dist/transform/rolldown.js +3 -3
  59. package/dist/transform/rollup.cjs +389 -464
  60. package/dist/transform/rollup.cjs.map +1 -1
  61. package/dist/transform/rollup.js +3 -3
  62. package/dist/transform/rsbuild.cjs +389 -464
  63. package/dist/transform/rsbuild.cjs.map +1 -1
  64. package/dist/transform/rsbuild.js +3 -3
  65. package/dist/transform/rspack.cjs +389 -464
  66. package/dist/transform/rspack.cjs.map +1 -1
  67. package/dist/transform/rspack.js +3 -3
  68. package/dist/transform/swc.cjs +402 -471
  69. package/dist/transform/swc.cjs.map +1 -1
  70. package/dist/transform/swc.js +19 -13
  71. package/dist/transform/swc.js.map +1 -1
  72. package/dist/transform/unplugin.cjs +389 -464
  73. package/dist/transform/unplugin.cjs.map +1 -1
  74. package/dist/transform/unplugin.js +3 -3
  75. package/dist/transform/vite.cjs +389 -464
  76. package/dist/transform/vite.cjs.map +1 -1
  77. package/dist/transform/vite.js +3 -3
  78. package/dist/transform/webpack.cjs +389 -464
  79. package/dist/transform/webpack.cjs.map +1 -1
  80. package/dist/transform/webpack.js +3 -3
  81. package/package.json +10 -21
  82. package/dist/chunk-6R33XLNY.js +0 -28
  83. package/dist/chunk-6R33XLNY.js.map +0 -1
  84. package/dist/chunk-FWC3KDJ4.js.map +0 -1
  85. package/dist/chunk-OXFZJP4E.js.map +0 -1
  86. package/dist/chunk-PACLPKDH.js +0 -513
  87. package/dist/chunk-PACLPKDH.js.map +0 -1
  88. package/dist/transform/typescript.cjs +0 -566
  89. package/dist/transform/typescript.cjs.map +0 -1
  90. package/dist/transform/typescript.d.cts +0 -22
  91. package/dist/transform/typescript.d.ts +0 -22
  92. package/dist/transform/typescript.js +0 -10
  93. package/dist/transform/typescript.js.map +0 -1
  94. /package/dist/{chunk-WS7CB5H3.js.map → chunk-EFGQRVMT.js.map} +0 -0
  95. /package/dist/{chunk-WMMHAWXS.js.map → chunk-R7SJXFMB.js.map} +0 -0
  96. /package/dist/{chunk-KHA4A746.js.map → chunk-ULKKTYOL.js.map} +0 -0
  97. /package/dist/{http-M6AWJWPW.js.map → http-GDTWWWYY.js.map} +0 -0
  98. /package/dist/{http-PKBJRGNK.js.map → http-QXJJB2F5.js.map} +0 -0
  99. /package/dist/{replay-JAYRFN3X.js.map → replay-DC3PID7Q.js.map} +0 -0
  100. /package/dist/{replay-OCHSU4JN.js.map → replay-VXQGVZXM.js.map} +0 -0
@@ -6,7 +6,15 @@ import { fileURLToPath, pathToFileURL } from "url";
6
6
 
7
7
  // ../bitfab-typescript-transform/src/loaderRuntime.ts
8
8
  import { dirname } from "path";
9
- import ts2 from "typescript";
9
+ import {
10
+ transformFromAstSync,
11
+ transformSync as transformSync2
12
+ } from "@babel/core";
13
+ import decoratorsPlugin from "@babel/plugin-proposal-decorators";
14
+ import commonJsPlugin from "@babel/plugin-transform-modules-commonjs";
15
+ import reactJsxPlugin from "@babel/plugin-transform-react-jsx";
16
+ import typeScriptPlugin from "@babel/plugin-transform-typescript";
17
+ import { getTsconfig, parseTsconfig } from "get-tsconfig";
10
18
 
11
19
  // ../bitfab-typescript-transform/src/transformOptions.ts
12
20
  var AUTO_TRACE_FUNCTION_ID_VERSION = "ts-auto-v1";
@@ -14,6 +22,14 @@ var AUTO_TRACE_TRANSFORM_MARKER = "__bitfab_auto_trace_transformed_v1__";
14
22
  function autoTraceFunctionId(file, name) {
15
23
  return `${AUTO_TRACE_FUNCTION_ID_VERSION}:${file}#${name}`;
16
24
  }
25
+ function sourceFilename(filename) {
26
+ return filename.replace(/\\/g, "/").split(/[?#]/, 1)[0] ?? "";
27
+ }
28
+ function autoTraceFilename(filename, cwd) {
29
+ const normalized = sourceFilename(filename);
30
+ const normalizedCwd = cwd.replace(/\\/g, "/").replace(/\/$/, "");
31
+ return normalized.startsWith(`${normalizedCwd}/`) ? normalized.slice(normalizedCwd.length + 1) : normalized;
32
+ }
17
33
  function shouldTransformBitfabFile(filename, options) {
18
34
  if (!filename) {
19
35
  return false;
@@ -21,7 +37,7 @@ function shouldTransformBitfabFile(filename, options) {
21
37
  if (options.include && !options.include(filename)) {
22
38
  return false;
23
39
  }
24
- const normalized = filename.replace(/\\/g, "/").split(/[?#]/, 1)[0] ?? "";
40
+ const normalized = sourceFilename(filename);
25
41
  const normalizedCwd = options.cwd?.replace(/\\/g, "/").replace(/\/$/, "");
26
42
  const isAbsolute2 = normalized.startsWith("/") || /^[A-Za-z]:\//.test(normalized);
27
43
  if (normalizedCwd && isAbsolute2 && normalized !== normalizedCwd && !normalized.startsWith(`${normalizedCwd}/`)) {
@@ -30,566 +46,503 @@ function shouldTransformBitfabFile(filename, options) {
30
46
  return !normalized.includes("/node_modules/") && !normalized.endsWith(".d.ts") && /\.[cm]?[jt]sx?$/.test(normalized);
31
47
  }
32
48
 
33
- // ../bitfab-typescript-transform/src/typescriptTransformer.ts
34
- import ts from "typescript";
35
- function hasUseClientDirective(sourceFile) {
36
- return sourceFile.statements.some(
37
- (statement) => ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression) && statement.expression.text === "use client"
38
- );
39
- }
40
- function hasTransformMarker(sourceFile) {
41
- return sourceFile.statements.some(
42
- (statement) => ts.isVariableStatement(statement) && statement.declarationList.declarations.some(
43
- (declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === AUTO_TRACE_TRANSFORM_MARKER
44
- )
45
- );
46
- }
47
- function isBitfabMemberCall(node, memberName) {
48
- return ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === memberName;
49
+ // ../bitfab-typescript-transform/src/babelPlugin.ts
50
+ function propertyName(node, types) {
51
+ if (types.isIdentifier(node)) {
52
+ return node.name;
53
+ }
54
+ if (types.isStringLiteral(node)) {
55
+ return node.value;
56
+ }
57
+ return null;
49
58
  }
50
- function withNodeFunctionName(node) {
51
- if (!isBitfabMemberCall(node, "withNode") || node.arguments.length > 2) {
52
- return null;
59
+ function functionName(path, types) {
60
+ const node = path.node;
61
+ if (types.isFunctionDeclaration(node) || types.isFunctionExpression(node)) {
62
+ if (node.id) {
63
+ return node.id.name;
64
+ }
53
65
  }
54
- const fn = node.arguments[node.arguments.length - 1];
55
- if (ts.isIdentifier(fn)) {
56
- return fn.text;
66
+ if ((types.isClassMethod(node) || types.isObjectMethod(node)) && !node.computed && types.isIdentifier(node.key)) {
67
+ return node.key.name;
57
68
  }
58
- if (ts.isPropertyAccessExpression(fn)) {
59
- return fn.name.text;
69
+ const parent = path.parentPath?.node;
70
+ if (types.isVariableDeclarator(parent)) {
71
+ return propertyName(parent.id, types) ?? "anonymous";
60
72
  }
61
- if (ts.isFunctionExpression(fn) && fn.name) {
62
- return fn.name.text;
73
+ if (types.isObjectProperty(parent) && !parent.computed) {
74
+ return propertyName(parent.key, types) ?? "anonymous";
63
75
  }
64
- return null;
76
+ const { line, column } = sourcePosition(path);
77
+ return `anonymous-${line}-${column}`;
65
78
  }
66
- function traceDecorators(node) {
67
- if (!ts.canHaveDecorators(node)) {
68
- return [];
79
+ function isInstrumentableFunction(node, types) {
80
+ if (node.generator || types.isClassPrivateMethod(node)) {
81
+ return false;
69
82
  }
70
- return ts.getDecorators(node) ?? [];
83
+ return !(types.isClassMethod(node) || types.isObjectMethod(node)) || node.kind === "method";
71
84
  }
72
- function isTraceDecoratorRoot(node) {
73
- return traceDecorators(node).some(
74
- (decorator) => isBitfabMemberCall(decorator.expression, "trace")
75
- );
85
+ function sourcePosition(path) {
86
+ const exportDeclaration = path.parentPath?.isExportDeclaration() ? path.parentPath.node : void 0;
87
+ const start = (exportDeclaration ?? path.node).loc?.start;
88
+ return { line: start?.line ?? 0, column: start?.column ?? 0 };
76
89
  }
77
- function collectBitfabWrappedFunctions(sourceFile) {
78
- const inlineRoots = /* @__PURE__ */ new Set();
79
- const referencedRoots = /* @__PURE__ */ new Set();
80
- function visit(node) {
81
- if (isBitfabMemberCall(node, "withTrace") || isBitfabMemberCall(node, "withSpan")) {
82
- const fn = node.arguments[node.arguments.length - 1];
83
- if (fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) {
84
- inlineRoots.add(fn);
85
- } else if (fn && ts.isIdentifier(fn)) {
86
- referencedRoots.add(fn.text);
90
+ function qualifiedFunctionName(path, types) {
91
+ const ownName = functionName(path, types);
92
+ if (ownName.startsWith("anonymous-")) {
93
+ return ownName;
94
+ }
95
+ const scopes = [];
96
+ let ancestor = path.parentPath;
97
+ while (ancestor) {
98
+ if (ancestor.isFunction()) {
99
+ if (!isInstrumentableFunction(ancestor.node, types)) {
100
+ ancestor = ancestor.parentPath;
101
+ continue;
102
+ }
103
+ const name = functionName(
104
+ ancestor,
105
+ types
106
+ );
107
+ if (!name.startsWith("anonymous-")) {
108
+ scopes.unshift(name);
109
+ }
110
+ } else if ((ancestor.isClassDeclaration() || ancestor.isClassExpression()) && ancestor.node.id) {
111
+ scopes.unshift(ancestor.node.id.name);
112
+ } else if (ancestor.isObjectExpression()) {
113
+ const parent = ancestor.parentPath?.node;
114
+ if (types.isVariableDeclarator(parent)) {
115
+ const name = propertyName(parent.id, types);
116
+ if (name) {
117
+ scopes.unshift(name);
118
+ }
119
+ } else if (types.isObjectProperty(parent) && !parent.computed) {
120
+ const name = propertyName(parent.key, types);
121
+ if (name) {
122
+ scopes.unshift(name);
123
+ }
87
124
  }
88
125
  }
89
- ts.forEachChild(node, visit);
126
+ ancestor = ancestor.parentPath;
90
127
  }
91
- visit(sourceFile);
92
- return { inlineRoots, referencedRoots };
128
+ return [...scopes, ownName].join(".");
93
129
  }
94
- function declaredFunctionName(node) {
95
- if (node.name && ts.isIdentifier(node.name)) {
96
- return node.name.text;
130
+ function isTraceDecoratorRoot(path, types) {
131
+ const node = path.node;
132
+ if (!types.isClassMethod(node) && !types.isClassPrivateMethod(node)) {
133
+ return false;
97
134
  }
98
- if ((ts.isArrowFunction(node) || ts.isFunctionExpression(node)) && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
99
- return node.parent.name.text;
135
+ return node.decorators?.some((decorator) => {
136
+ const expression = decorator.expression;
137
+ if (!types.isCallExpression(expression)) {
138
+ return false;
139
+ }
140
+ const callee = expression.callee;
141
+ return types.isMemberExpression(callee) && !callee.computed && types.isIdentifier(callee.property, { name: "trace" });
142
+ }) ?? false;
143
+ }
144
+ function isBitfabWrapperArgument(path, types) {
145
+ const parent = path.parentPath?.node;
146
+ if (!types.isCallExpression(parent)) {
147
+ return false;
100
148
  }
101
- if ((ts.isArrowFunction(node) || ts.isFunctionExpression(node)) && ts.isPropertyAssignment(node.parent) && (ts.isIdentifier(node.parent.name) || ts.isStringLiteral(node.parent.name))) {
102
- return node.parent.name.text;
149
+ if (!parent.arguments.some((argument) => argument === path.node)) {
150
+ return false;
103
151
  }
104
- return null;
152
+ const callee = parent.callee;
153
+ return types.isMemberExpression(callee) && !callee.computed && types.isIdentifier(callee.property) && (callee.property.name === "withTrace" || callee.property.name === "withSpan");
105
154
  }
106
- function objectContainerName(node) {
107
- if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
108
- return node.parent.name.text;
155
+ function withNodeFunctionName(path, types) {
156
+ if (path.node.arguments.length > 2) {
157
+ return null;
158
+ }
159
+ const callee = path.node.callee;
160
+ if (!types.isMemberExpression(callee) || callee.computed || !types.isIdentifier(callee.property, { name: "withNode" })) {
161
+ return null;
162
+ }
163
+ const fn = path.node.arguments[path.node.arguments.length - 1];
164
+ if (types.isIdentifier(fn)) {
165
+ return fn.name;
109
166
  }
110
- if (ts.isPropertyAssignment(node.parent) && (ts.isIdentifier(node.parent.name) || ts.isStringLiteral(node.parent.name))) {
111
- return node.parent.name.text;
167
+ if (types.isMemberExpression(fn) && !fn.computed) {
168
+ return propertyName(fn.property, types);
169
+ }
170
+ if (types.isFunctionExpression(fn) && fn.id) {
171
+ return fn.id.name;
112
172
  }
113
173
  return null;
114
174
  }
115
- function functionName(node) {
116
- const ownName = declaredFunctionName(node);
117
- if (ownName) {
118
- const scopes = [];
119
- let ancestor = node.parent;
120
- while (ancestor) {
121
- if (isInstrumentableFunction(ancestor)) {
122
- const name = declaredFunctionName(ancestor);
123
- if (name) {
124
- scopes.unshift(name);
125
- }
126
- } else if ((ts.isClassDeclaration(ancestor) || ts.isClassExpression(ancestor)) && ancestor.name) {
127
- scopes.unshift(ancestor.name.text);
128
- } else if (ts.isObjectLiteralExpression(ancestor)) {
129
- const name = objectContainerName(ancestor);
130
- if (name) {
131
- scopes.unshift(name);
132
- }
133
- }
134
- ancestor = ancestor.parent;
135
- }
136
- return [...scopes, ownName].join(".");
175
+ function functionBindingName(path, types) {
176
+ if (types.isFunctionDeclaration(path.node) && path.node.id) {
177
+ return path.node.id.name;
137
178
  }
138
- const sourceFile = node.getSourceFile();
139
- const position = sourceFile.getLineAndCharacterOfPosition(node.getStart());
140
- return `anonymous-${position.line + 1}-${position.character}`;
179
+ const parent = path.parentPath?.node;
180
+ if (types.isVariableDeclarator(parent) && types.isIdentifier(parent.id)) {
181
+ return parent.id.name;
182
+ }
183
+ return null;
141
184
  }
142
- function isBitfabWrappedFunction(node, inlineRoots, referencedRoots) {
143
- if (inlineRoots.has(node)) {
185
+ function isBitfabWrappedFunction(path, types) {
186
+ if (isBitfabWrapperArgument(path, types)) {
144
187
  return true;
145
188
  }
146
- const name = declaredFunctionName(node);
147
- return name !== null && referencedRoots.has(name);
148
- }
149
- function isInstrumentableFunction(node) {
150
- if (!ts.isFunctionDeclaration(node) && !ts.isFunctionExpression(node) && !ts.isArrowFunction(node) && !ts.isMethodDeclaration(node)) {
189
+ const bindingName = functionBindingName(path, types);
190
+ if (!bindingName) {
151
191
  return false;
152
192
  }
153
- return node.body !== void 0 && node.asteriskToken === void 0 && (!node.name || !ts.isPrivateIdentifier(node.name));
193
+ const binding = path.scope.getBinding(bindingName);
194
+ return binding?.referencePaths.some(
195
+ (referencePath) => isBitfabWrapperArgument(referencePath, types)
196
+ ) ?? false;
154
197
  }
155
- function normalizedFilename(filename, cwd) {
156
- const normalized = filename.replace(/\\/g, "/").split(/[?#]/, 1)[0] ?? "";
157
- const normalizedCwd = cwd.replace(/\\/g, "/").replace(/\/$/, "");
158
- return normalized.startsWith(`${normalizedCwd}/`) ? normalized.slice(normalizedCwd.length + 1) : normalized;
198
+ function isBitfabManagedFunction(path, types) {
199
+ return isTraceDecoratorRoot(path, types) || isBitfabWrappedFunction(path, types);
159
200
  }
160
- function parameterInputs(factory, node) {
161
- return factory.createArrayLiteralExpression(
162
- node.parameters.map((parameter, index) => {
163
- if (!ts.isArrowFunction(node)) {
164
- if (parameter.dotDotDotToken) {
165
- return factory.createSpreadElement(
166
- factory.createCallExpression(
167
- factory.createPropertyAccessExpression(
168
- factory.createArrayLiteralExpression([
169
- factory.createSpreadElement(
170
- factory.createIdentifier("arguments")
171
- )
201
+ function runtimeParameters(node, types) {
202
+ return node.params.filter(
203
+ (parameter) => !types.isIdentifier(parameter, { name: "this" })
204
+ );
205
+ }
206
+ function parameterInputs(path, types) {
207
+ const elements = [];
208
+ for (const [index, parameter] of runtimeParameters(
209
+ path.node,
210
+ types
211
+ ).entries()) {
212
+ if (!types.isArrowFunctionExpression(path.node)) {
213
+ if (types.isRestElement(parameter)) {
214
+ elements.push(
215
+ types.spreadElement(
216
+ types.callExpression(
217
+ types.memberExpression(
218
+ types.arrayExpression([
219
+ types.spreadElement(types.identifier("arguments"))
172
220
  ]),
173
- "slice"
221
+ types.identifier("slice")
174
222
  ),
175
- void 0,
176
- [factory.createNumericLiteral(index)]
223
+ [types.numericLiteral(index)]
177
224
  )
178
- );
179
- }
180
- return factory.createElementAccessExpression(
181
- factory.createIdentifier("arguments"),
182
- factory.createNumericLiteral(index)
225
+ )
226
+ );
227
+ } else {
228
+ elements.push(
229
+ types.memberExpression(
230
+ types.identifier("arguments"),
231
+ types.numericLiteral(index),
232
+ true
233
+ )
183
234
  );
184
235
  }
185
- if (ts.isIdentifier(parameter.name)) {
186
- const identifier = factory.createIdentifier(parameter.name.text);
187
- return parameter.dotDotDotToken ? factory.createSpreadElement(identifier) : identifier;
188
- }
189
- throw new Error(
190
- "Bitfab transform invariant: arrow parameter requires argument wrapper"
236
+ continue;
237
+ }
238
+ if (types.isIdentifier(parameter)) {
239
+ elements.push(types.identifier(parameter.name));
240
+ } else if (types.isRestElement(parameter) && types.isIdentifier(parameter.argument)) {
241
+ elements.push(
242
+ types.spreadElement(types.identifier(parameter.argument.name))
191
243
  );
192
- })
193
- );
244
+ }
245
+ }
246
+ return types.arrayExpression(elements);
194
247
  }
195
- function needsArgumentWrapper(node) {
196
- return ts.isArrowFunction(node) && node.parameters.some(
197
- (parameter) => !ts.isIdentifier(parameter.name) || parameter.initializer !== void 0
248
+ function needsArgumentWrapper(path, types) {
249
+ return types.isArrowFunctionExpression(path.node) && path.node.params.some(
250
+ (parameter) => !types.isIdentifier(parameter) && !(types.isRestElement(parameter) && types.isIdentifier(parameter.argument))
198
251
  );
199
252
  }
200
- function isRestWrapper(node) {
201
- return node.parameters.length === 1 && node.parameters[0]?.dotDotDotToken !== void 0;
253
+ function isRestWrapper(path, types) {
254
+ const parameters = runtimeParameters(path.node, types);
255
+ return parameters.length === 1 && types.isRestElement(parameters[0]);
202
256
  }
203
- function splitDirectivePrologue(body) {
204
- const firstNonDirective = body.statements.findIndex(
205
- (statement) => !(ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression))
206
- );
207
- if (firstNonDirective === -1) {
208
- return { directives: body.statements, statements: [] };
209
- }
257
+ function bitfabBabelPlugin(api) {
258
+ const { types } = api;
210
259
  return {
211
- directives: body.statements.slice(0, firstNonDirective),
212
- statements: body.statements.slice(firstNonDirective)
213
- };
214
- }
215
- function updateFunctionBody(factory, node, body) {
216
- if (ts.isFunctionDeclaration(node)) {
217
- return factory.updateFunctionDeclaration(
218
- node,
219
- node.modifiers,
220
- node.asteriskToken,
221
- node.name,
222
- node.typeParameters,
223
- node.parameters,
224
- node.type,
225
- body
226
- );
227
- }
228
- if (ts.isFunctionExpression(node)) {
229
- return factory.updateFunctionExpression(
230
- node,
231
- node.modifiers,
232
- node.asteriskToken,
233
- node.name,
234
- node.typeParameters,
235
- node.parameters,
236
- node.type,
237
- body
238
- );
239
- }
240
- if (ts.isArrowFunction(node)) {
241
- return factory.updateArrowFunction(
242
- node,
243
- node.modifiers,
244
- node.typeParameters,
245
- node.parameters,
246
- node.type,
247
- node.equalsGreaterThanToken,
248
- body
249
- );
250
- }
251
- if (ts.isMethodDeclaration(node)) {
252
- return factory.updateMethodDeclaration(
253
- node,
254
- node.modifiers,
255
- node.asteriskToken,
256
- node.name,
257
- node.questionToken,
258
- node.typeParameters,
259
- node.parameters,
260
- node.type,
261
- body
262
- );
263
- }
264
- return node;
265
- }
266
- function createBitfabTypeScriptTransformer(options = {}) {
267
- return (context) => (sourceFile) => {
268
- if (hasUseClientDirective(sourceFile) || hasTransformMarker(sourceFile) || !shouldTransformBitfabFile(sourceFile.fileName, options)) {
269
- return sourceFile;
270
- }
271
- const { factory } = context;
272
- const { inlineRoots, referencedRoots } = collectBitfabWrappedFunctions(sourceFile);
273
- const runtimeIdentifier = factory.createUniqueName("bitfabAutoSpan");
274
- const activeIdentifier = factory.createUniqueName("bitfabAutoTraceActive");
275
- const wrapperIdentifier = factory.createUniqueName("bitfabAutoWrap");
276
- const transformedNodes = /* @__PURE__ */ new Set();
277
- const definitions = [];
278
- let usedRuntime = false;
279
- let usedWrapper = false;
280
- const cwd = options.cwd ?? process.cwd();
281
- const file = normalizedFilename(sourceFile.fileName, cwd);
282
- const visitor = (node) => {
283
- const visited = ts.visitEachChild(node, visitor, context);
284
- if (ts.isCallExpression(node) && ts.isCallExpression(visited)) {
285
- const configuredName = withNodeFunctionName(node);
286
- if (configuredName !== null) {
287
- const args = [...visited.arguments];
288
- if (args.length === 1) {
289
- args.push(factory.createIdentifier("undefined"));
290
- }
291
- args.push(factory.createStringLiteral(configuredName));
292
- return factory.updateCallExpression(
293
- visited,
294
- visited.expression,
295
- visited.typeArguments,
296
- args
260
+ name: "bitfab-auto-trace",
261
+ visitor: {
262
+ Program: {
263
+ enter(path, state) {
264
+ const filename = state.file.opts.filename ?? "unknown";
265
+ state.skipFile = !shouldTransformBitfabFile(filename, state.opts) || path.scope.hasBinding(AUTO_TRACE_TRANSFORM_MARKER) || path.node.directives.some(
266
+ (directive) => directive.value.value === "use client"
297
267
  );
298
- }
299
- }
300
- if (!isInstrumentableFunction(node)) {
301
- return visited;
302
- }
303
- if (!isInstrumentableFunction(visited) || transformedNodes.has(visited) || isTraceDecoratorRoot(node) || isBitfabWrappedFunction(node, inlineRoots, referencedRoots)) {
304
- return visited;
305
- }
306
- const name = functionName(node);
307
- if (name.startsWith("anonymous-")) {
308
- return visited;
309
- }
310
- const position = sourceFile.getLineAndCharacterOfPosition(node.getStart());
311
- const definition = factory.createObjectLiteralExpression(
312
- [
313
- factory.createPropertyAssignment(
314
- "id",
315
- factory.createStringLiteral(autoTraceFunctionId(file, name))
316
- ),
317
- factory.createPropertyAssignment(
318
- "name",
319
- factory.createStringLiteral(name)
320
- ),
321
- factory.createPropertyAssignment(
322
- "file",
323
- factory.createStringLiteral(file)
324
- ),
325
- factory.createPropertyAssignment(
326
- "line",
327
- factory.createNumericLiteral(position.line + 1)
328
- ),
329
- factory.createPropertyAssignment(
330
- "column",
331
- factory.createNumericLiteral(position.character)
332
- ),
333
- ...node.modifiers?.some(
334
- (modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword
335
- ) ? [factory.createPropertyAssignment("async", factory.createTrue())] : [],
336
- ...isRestWrapper(node) ? [
337
- factory.createPropertyAssignment(
338
- "wrapper",
339
- factory.createTrue()
340
- )
341
- ] : []
342
- ],
343
- false
344
- );
345
- const definitionIdentifier = factory.createUniqueName(
346
- "bitfabAutoDefinition"
347
- );
348
- definitions.push(
349
- factory.createVariableStatement(
350
- void 0,
351
- factory.createVariableDeclarationList(
352
- [
353
- factory.createVariableDeclaration(
354
- definitionIdentifier,
355
- void 0,
356
- void 0,
357
- definition
358
- )
359
- ],
360
- ts.NodeFlags.Const
361
- )
362
- )
363
- );
364
- if (needsArgumentWrapper(visited)) {
365
- usedRuntime = true;
366
- usedWrapper = true;
367
- return factory.createCallExpression(wrapperIdentifier, void 0, [
368
- definitionIdentifier,
369
- visited
370
- ]);
371
- }
372
- const visitedBody = visited.body;
373
- const originalBody = ts.isBlock(visitedBody) ? visitedBody : factory.createBlock(
374
- [factory.createReturnStatement(visitedBody)],
375
- true
376
- );
377
- const { directives, statements } = splitDirectivePrologue(originalBody);
378
- const invoke = factory.createArrowFunction(
379
- hasAsyncModifier(node) ? [factory.createModifier(ts.SyntaxKind.AsyncKeyword)] : void 0,
380
- void 0,
381
- [],
382
- void 0,
383
- factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken),
384
- factory.updateBlock(originalBody, statements)
385
- );
386
- const body = factory.createBlock(
387
- [
388
- ...directives,
389
- factory.createIfStatement(
390
- factory.createCallExpression(activeIdentifier, void 0, []),
391
- factory.createBlock(
268
+ state.runtimeIdentifier = path.scope.generateUidIdentifier("bitfabAutoSpan");
269
+ state.activeIdentifier = path.scope.generateUidIdentifier(
270
+ "bitfabAutoTraceActive"
271
+ );
272
+ state.wrapperIdentifier = path.scope.generateUidIdentifier("bitfabAutoWrap");
273
+ state.definitions = [];
274
+ state.usedRuntime = false;
275
+ state.usedWrapper = false;
276
+ },
277
+ exit(path, state) {
278
+ if (state.skipFile || !state.usedRuntime || !state.runtimeIdentifier || !state.activeIdentifier || !state.wrapperIdentifier) {
279
+ return;
280
+ }
281
+ state.file.metadata[AUTO_TRACE_TRANSFORM_MARKER] = true;
282
+ path.unshiftContainer("body", [
283
+ types.importDeclaration(
392
284
  [
393
- factory.createReturnStatement(
394
- factory.createCallExpression(runtimeIdentifier, void 0, [
395
- definitionIdentifier,
396
- parameterInputs(factory, visited),
397
- invoke
398
- ])
399
- )
400
- ],
401
- true
402
- )
403
- ),
404
- ...statements
405
- ],
406
- true
407
- );
408
- const updated = updateFunctionBody(factory, visited, body);
409
- transformedNodes.add(updated);
410
- usedRuntime = true;
411
- return updated;
412
- };
413
- const transformed = ts.visitEachChild(sourceFile, visitor, context);
414
- if (!usedRuntime) {
415
- return transformed;
416
- }
417
- const runtimeImport = factory.createImportDeclaration(
418
- void 0,
419
- factory.createImportClause(
420
- false,
421
- void 0,
422
- factory.createNamedImports([
423
- factory.createImportSpecifier(
424
- false,
425
- factory.createIdentifier("__bitfabAutoSpan"),
426
- runtimeIdentifier
427
- ),
428
- factory.createImportSpecifier(
429
- false,
430
- factory.createIdentifier("__bitfabAutoTraceActive"),
431
- activeIdentifier
432
- ),
433
- ...usedWrapper ? [
434
- factory.createImportSpecifier(
435
- false,
436
- factory.createIdentifier("__bitfabAutoWrap"),
437
- wrapperIdentifier
438
- )
439
- ] : []
440
- ])
441
- ),
442
- factory.createStringLiteral(options.runtimeModule ?? "@bitfab/sdk/auto")
443
- );
444
- const transformMarker = factory.createVariableStatement(
445
- void 0,
446
- factory.createVariableDeclarationList(
447
- [
448
- factory.createVariableDeclaration(
449
- factory.createIdentifier(AUTO_TRACE_TRANSFORM_MARKER),
450
- void 0,
451
- void 0,
452
- factory.createAssignment(
453
- factory.createPropertyAccessExpression(
454
- factory.createIdentifier("globalThis"),
455
- factory.createIdentifier(AUTO_TRACE_TRANSFORM_MARKER)
456
- ),
457
- factory.createTrue()
458
- )
459
- )
460
- ],
461
- ts.NodeFlags.Const
462
- )
463
- );
464
- return factory.updateSourceFile(transformed, [
465
- context.getCompilerOptions().module === ts.ModuleKind.CommonJS ? factory.createVariableStatement(
466
- void 0,
467
- factory.createVariableDeclarationList(
468
- [
469
- factory.createVariableDeclaration(
470
- factory.createObjectBindingPattern([
471
- factory.createBindingElement(
472
- void 0,
473
- "__bitfabAutoSpan",
474
- runtimeIdentifier
285
+ types.importSpecifier(
286
+ state.runtimeIdentifier,
287
+ types.identifier("__bitfabAutoSpan")
475
288
  ),
476
- factory.createBindingElement(
477
- void 0,
478
- "__bitfabAutoTraceActive",
479
- activeIdentifier
289
+ types.importSpecifier(
290
+ state.activeIdentifier,
291
+ types.identifier("__bitfabAutoTraceActive")
480
292
  ),
481
- ...usedWrapper ? [
482
- factory.createBindingElement(
483
- void 0,
484
- "__bitfabAutoWrap",
485
- wrapperIdentifier
293
+ ...state.usedWrapper ? [
294
+ types.importSpecifier(
295
+ state.wrapperIdentifier,
296
+ types.identifier("__bitfabAutoWrap")
486
297
  )
487
298
  ] : []
488
- ]),
489
- void 0,
490
- void 0,
491
- factory.createCallExpression(
492
- factory.createIdentifier("require"),
493
- void 0,
494
- [
495
- factory.createStringLiteral(
496
- options.runtimeModule ?? "@bitfab/sdk/auto"
497
- )
498
- ]
299
+ ],
300
+ types.stringLiteral(
301
+ state.opts.runtimeModule ?? "@bitfab/sdk/auto"
499
302
  )
500
- )
501
- ],
502
- ts.NodeFlags.Const
503
- )
504
- ) : runtimeImport,
505
- transformMarker,
506
- ...definitions,
507
- ...transformed.statements
508
- ]);
303
+ ),
304
+ types.variableDeclaration("const", [
305
+ types.variableDeclarator(
306
+ types.identifier(AUTO_TRACE_TRANSFORM_MARKER),
307
+ types.assignmentExpression(
308
+ "=",
309
+ types.memberExpression(
310
+ types.identifier("globalThis"),
311
+ types.identifier(AUTO_TRACE_TRANSFORM_MARKER)
312
+ ),
313
+ types.booleanLiteral(true)
314
+ )
315
+ )
316
+ ]),
317
+ ...state.definitions ?? []
318
+ ]);
319
+ }
320
+ },
321
+ CallExpression: {
322
+ exit(path, state) {
323
+ if (state.skipFile) {
324
+ return;
325
+ }
326
+ const configuredName = withNodeFunctionName(path, types);
327
+ if (configuredName === null) {
328
+ return;
329
+ }
330
+ if (path.node.arguments.length === 1) {
331
+ path.node.arguments.push(types.identifier("undefined"));
332
+ }
333
+ path.node.arguments.push(types.stringLiteral(configuredName));
334
+ }
335
+ },
336
+ Function: {
337
+ exit(path, state) {
338
+ const node = path.node;
339
+ if (state.skipFile || node._bitfabInstrumented || !isInstrumentableFunction(node, types) || isBitfabManagedFunction(path, types) || !state.runtimeIdentifier || !state.activeIdentifier || !state.wrapperIdentifier) {
340
+ return;
341
+ }
342
+ const name = qualifiedFunctionName(path, types);
343
+ if (name.startsWith("anonymous-")) {
344
+ return;
345
+ }
346
+ const normalizedFilename = autoTraceFilename(
347
+ state.file.opts.filename ?? "unknown",
348
+ state.opts.cwd ?? state.file.opts.cwd ?? process.cwd()
349
+ );
350
+ const { line, column } = sourcePosition(path);
351
+ const definition = types.objectExpression([
352
+ types.objectProperty(
353
+ types.identifier("id"),
354
+ types.stringLiteral(
355
+ autoTraceFunctionId(normalizedFilename, name)
356
+ )
357
+ ),
358
+ types.objectProperty(
359
+ types.identifier("name"),
360
+ types.stringLiteral(name)
361
+ ),
362
+ types.objectProperty(
363
+ types.identifier("file"),
364
+ types.stringLiteral(normalizedFilename)
365
+ ),
366
+ types.objectProperty(
367
+ types.identifier("line"),
368
+ types.numericLiteral(line)
369
+ ),
370
+ types.objectProperty(
371
+ types.identifier("column"),
372
+ types.numericLiteral(column)
373
+ ),
374
+ ...node.async ? [
375
+ types.objectProperty(
376
+ types.identifier("async"),
377
+ types.booleanLiteral(true)
378
+ )
379
+ ] : [],
380
+ ...isRestWrapper(path, types) ? [
381
+ types.objectProperty(
382
+ types.identifier("wrapper"),
383
+ types.booleanLiteral(true)
384
+ )
385
+ ] : []
386
+ ]);
387
+ const definitionIdentifier = path.scope.getProgramParent().generateUidIdentifier("bitfabAutoDefinition");
388
+ state.definitions?.push(
389
+ types.variableDeclaration("const", [
390
+ types.variableDeclarator(definitionIdentifier, definition)
391
+ ])
392
+ );
393
+ if (needsArgumentWrapper(path, types)) {
394
+ node._bitfabInstrumented = true;
395
+ path.replaceWith(
396
+ types.callExpression(types.cloneNode(state.wrapperIdentifier), [
397
+ types.cloneNode(definitionIdentifier),
398
+ node
399
+ ])
400
+ );
401
+ state.usedRuntime = true;
402
+ state.usedWrapper = true;
403
+ return;
404
+ }
405
+ const originalBody = types.isBlockStatement(node.body) ? node.body : types.blockStatement([types.returnStatement(node.body)]);
406
+ const directives = originalBody.directives;
407
+ originalBody.directives = [];
408
+ const body = types.blockStatement(
409
+ [
410
+ types.ifStatement(
411
+ types.callExpression(
412
+ types.cloneNode(state.activeIdentifier),
413
+ []
414
+ ),
415
+ types.blockStatement([
416
+ types.returnStatement(
417
+ types.callExpression(
418
+ types.cloneNode(state.runtimeIdentifier),
419
+ [
420
+ types.cloneNode(definitionIdentifier),
421
+ parameterInputs(path, types),
422
+ types.arrowFunctionExpression(
423
+ [],
424
+ types.cloneNode(originalBody, true),
425
+ node.async ?? false
426
+ )
427
+ ]
428
+ )
429
+ )
430
+ ])
431
+ ),
432
+ ...originalBody.body
433
+ ],
434
+ directives
435
+ );
436
+ node.body = body;
437
+ node._bitfabInstrumented = true;
438
+ state.usedRuntime = true;
439
+ }
440
+ }
441
+ }
509
442
  };
510
443
  }
511
- function hasAsyncModifier(node) {
512
- return ts.canHaveModifiers(node) ? ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) ?? false : false;
444
+
445
+ // ../bitfab-typescript-transform/src/transform.ts
446
+ import { transformSync } from "@babel/core";
447
+ function parserPlugins(filename) {
448
+ const path = sourceFilename(filename);
449
+ const typescript = /\.[cm]?tsx?$/.test(path);
450
+ const jsx = /\.tsx$/.test(path) || /\.[cm]?jsx?$/.test(path);
451
+ return [
452
+ ...typescript ? ["typescript"] : [],
453
+ ...jsx ? ["jsx"] : [],
454
+ "decorators"
455
+ ];
513
456
  }
514
457
 
515
458
  // ../bitfab-typescript-transform/src/loaderRuntime.ts
516
- var OPTIONS_THAT_ONLY_APPLY_TO_A_WHOLE_PROGRAM = [
517
- "composite",
518
- "declarationDir",
519
- "incremental",
520
- "outDir",
521
- "rootDir",
522
- "rootDirs",
523
- "tsBuildInfoFile"
524
- ];
525
459
  function readCompilerOptions(filename, configuredPath) {
526
- const configPath = configuredPath ?? ts2.findConfigFile(dirname(filename), ts2.sys.fileExists, "tsconfig.json");
527
- if (!configPath) {
528
- return {};
529
- }
530
- const config = ts2.readConfigFile(configPath, ts2.sys.readFile);
531
- if (config.error) {
532
- throw new Error(
533
- ts2.flattenDiagnosticMessageText(config.error.messageText, "\n")
534
- );
535
- }
536
- const { options } = ts2.parseJsonConfigFileContent(
537
- config.config,
538
- ts2.sys,
539
- dirname(configPath)
540
- );
541
- for (const option of OPTIONS_THAT_ONLY_APPLY_TO_A_WHOLE_PROGRAM) {
542
- delete options[option];
543
- }
544
- return options;
460
+ const config = configuredPath ? parseTsconfig(configuredPath) : getTsconfig(dirname(filename))?.config;
461
+ return config?.compilerOptions ?? {};
545
462
  }
546
- function moduleKindForFormat(filename, format) {
547
- if (format === "commonjs" || filename.endsWith(".cts")) {
548
- return ts2.ModuleKind.CommonJS;
463
+ function reactJsxOptions(compilerOptions) {
464
+ if (compilerOptions.jsx === "react") {
465
+ return [
466
+ reactJsxPlugin,
467
+ {
468
+ runtime: "classic",
469
+ ...compilerOptions.jsxFactory && {
470
+ pragma: compilerOptions.jsxFactory
471
+ },
472
+ ...compilerOptions.jsxFragmentFactory && {
473
+ pragmaFrag: compilerOptions.jsxFragmentFactory
474
+ }
475
+ }
476
+ ];
549
477
  }
550
- return ts2.ModuleKind.ESNext;
478
+ return [
479
+ reactJsxPlugin,
480
+ {
481
+ runtime: "automatic",
482
+ importSource: compilerOptions.jsxImportSource ?? "react"
483
+ }
484
+ ];
485
+ }
486
+ function compilePlugins(filename, compilerOptions, format) {
487
+ const path = sourceFilename(filename);
488
+ const isTypeScript = /\.[cm]?tsx?$/.test(path);
489
+ const hasJsx = /\.[jt]sx$/.test(path);
490
+ const isCommonJs = format === "commonjs" || path.endsWith(".cts");
491
+ return [
492
+ ...isTypeScript ? [
493
+ [
494
+ typeScriptPlugin,
495
+ {
496
+ onlyRemoveTypeImports: compilerOptions.verbatimModuleSyntax === true
497
+ }
498
+ ]
499
+ ] : [],
500
+ [
501
+ decoratorsPlugin,
502
+ {
503
+ version: compilerOptions.experimentalDecorators ? "legacy" : "2023-11"
504
+ }
505
+ ],
506
+ ...hasJsx ? [reactJsxOptions(compilerOptions)] : [],
507
+ ...isCommonJs ? [commonJsPlugin] : []
508
+ ];
551
509
  }
552
510
  function transformBitfabModuleToJavaScript(source, filename, options = {}, format, sourceMapMode = "external") {
553
511
  const { tsconfig, ...transformOptions } = options;
554
512
  if (!shouldTransformBitfabFile(filename, transformOptions)) {
555
513
  return { code: source };
556
514
  }
557
- const compilerOptions = readCompilerOptions(filename, tsconfig);
558
- const result = ts2.transpileModule(source, {
559
- compilerOptions: {
560
- ...compilerOptions,
561
- allowJs: true,
562
- declaration: false,
563
- emitDeclarationOnly: false,
564
- inlineSourceMap: sourceMapMode === "inline",
565
- inlineSources: sourceMapMode === "inline",
566
- module: moduleKindForFormat(filename, format),
567
- moduleResolution: format === "commonjs" ? ts2.ModuleResolutionKind.Node10 : ts2.ModuleResolutionKind.Bundler,
568
- noEmit: false,
569
- noEmitOnError: false,
570
- sourceMap: sourceMapMode === "external"
571
- },
572
- fileName: filename,
573
- reportDiagnostics: true,
574
- transformers: {
575
- before: [createBitfabTypeScriptTransformer(transformOptions)]
576
- }
515
+ const sourceFile = sourceFilename(filename);
516
+ const instrumented = transformSync2(source, {
517
+ ast: true,
518
+ babelrc: false,
519
+ code: false,
520
+ configFile: false,
521
+ filename: sourceFile,
522
+ parserOpts: { plugins: parserPlugins(filename), sourceType: "module" },
523
+ plugins: [[bitfabBabelPlugin, transformOptions]]
577
524
  });
578
- const errors = result.diagnostics?.filter(
579
- (diagnostic) => diagnostic.category === ts2.DiagnosticCategory.Error
580
- );
581
- if (errors && errors.length > 0) {
582
- throw new Error(
583
- ts2.formatDiagnostics(errors, {
584
- getCanonicalFileName: (file) => file,
585
- getCurrentDirectory: () => process.cwd(),
586
- getNewLine: () => "\n"
587
- })
588
- );
525
+ if (!instrumented?.ast) {
526
+ throw new Error(`Bitfab could not parse ${sourceFile}`);
527
+ }
528
+ const compiled = transformFromAstSync(instrumented.ast, source, {
529
+ babelrc: false,
530
+ cloneInputAst: false,
531
+ configFile: false,
532
+ filename: sourceFile,
533
+ plugins: compilePlugins(
534
+ filename,
535
+ readCompilerOptions(filename, tsconfig),
536
+ format
537
+ ),
538
+ sourceMaps: sourceMapMode === "inline" ? "inline" : true
539
+ });
540
+ if (compiled?.code === void 0 || compiled.code === null) {
541
+ throw new Error(`Bitfab could not compile ${sourceFile}`);
589
542
  }
590
543
  return {
591
- code: result.outputText,
592
- ...result.sourceMapText ? { map: result.sourceMapText } : {}
544
+ code: compiled.code,
545
+ ...compiled.map ? { map: JSON.stringify(compiled.map) } : {}
593
546
  };
594
547
  }
595
548