braintrust 3.25.0 → 3.27.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 (79) hide show
  1. package/NOTICE +6 -0
  2. package/dev/dist/index.d.mts +130 -2
  3. package/dev/dist/index.d.ts +130 -2
  4. package/dev/dist/index.js +4133 -1421
  5. package/dev/dist/index.mjs +3242 -530
  6. package/dist/apply-auto-instrumentation.js +526 -426
  7. package/dist/apply-auto-instrumentation.mjs +329 -229
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +1198 -364
  9. package/dist/auto-instrumentations/bundler/esbuild.d.mts +4 -4
  10. package/dist/auto-instrumentations/bundler/esbuild.d.ts +4 -4
  11. package/dist/auto-instrumentations/bundler/esbuild.mjs +6 -8
  12. package/dist/auto-instrumentations/bundler/next.cjs +1227 -413
  13. package/dist/auto-instrumentations/bundler/next.mjs +7 -29
  14. package/dist/auto-instrumentations/bundler/rollup.cjs +1198 -364
  15. package/dist/auto-instrumentations/bundler/rollup.d.mts +4 -4
  16. package/dist/auto-instrumentations/bundler/rollup.d.ts +4 -4
  17. package/dist/auto-instrumentations/bundler/rollup.mjs +6 -8
  18. package/dist/auto-instrumentations/bundler/vite.cjs +1249 -387
  19. package/dist/auto-instrumentations/bundler/vite.d.mts +4 -4
  20. package/dist/auto-instrumentations/bundler/vite.d.ts +4 -4
  21. package/dist/auto-instrumentations/bundler/vite.mjs +34 -8
  22. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1368 -324
  23. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +20 -12
  24. package/dist/auto-instrumentations/bundler/webpack.cjs +1198 -364
  25. package/dist/auto-instrumentations/bundler/webpack.d.mts +4 -4
  26. package/dist/auto-instrumentations/bundler/webpack.d.ts +4 -4
  27. package/dist/auto-instrumentations/bundler/webpack.mjs +6 -4
  28. package/dist/auto-instrumentations/chunk-2AMDGD65.mjs +1396 -0
  29. package/dist/auto-instrumentations/{chunk-7P6563SW.mjs → chunk-BW33ULMW.mjs} +2 -6
  30. package/dist/auto-instrumentations/{chunk-M6DLIJ2Z.mjs → chunk-I55G56ZL.mjs} +114 -221
  31. package/dist/auto-instrumentations/chunk-JPUFNW7X.mjs +649 -0
  32. package/dist/auto-instrumentations/{chunk-JPVCUKTY.mjs → chunk-XEYKUBLY.mjs} +191 -73
  33. package/dist/auto-instrumentations/{chunk-CZ24KNHT.mjs → chunk-ZNHTSSGI.mjs} +231 -69
  34. package/dist/auto-instrumentations/hook.mjs +406 -183
  35. package/dist/auto-instrumentations/index.cjs +853 -49
  36. package/dist/auto-instrumentations/index.d.mts +10 -2
  37. package/dist/auto-instrumentations/index.d.ts +10 -2
  38. package/dist/auto-instrumentations/index.mjs +10 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +566 -221
  40. package/dist/auto-instrumentations/loader/cjs-patch.d.mts +2 -2
  41. package/dist/auto-instrumentations/loader/cjs-patch.d.ts +2 -2
  42. package/dist/auto-instrumentations/loader/cjs-patch.mjs +3 -2
  43. package/dist/auto-instrumentations/loader/esm-hook.mjs +1 -1
  44. package/dist/auto-instrumentations/plugin-B-aZh7EP.d.ts +30 -0
  45. package/dist/auto-instrumentations/plugin-Bnj4E_6B.d.mts +30 -0
  46. package/dist/auto-instrumentations/{types-RNPaKi9o.d.mts → types-C1fVeiCp.d.mts} +1 -1
  47. package/dist/auto-instrumentations/{types-RNPaKi9o.d.ts → types-C1fVeiCp.d.ts} +1 -1
  48. package/dist/browser.d.mts +871 -199
  49. package/dist/browser.d.ts +871 -199
  50. package/dist/browser.js +3737 -549
  51. package/dist/browser.mjs +3737 -549
  52. package/dist/{chunk-ABR2QWDP.mjs → chunk-CZM5JIQL.mjs} +788 -132
  53. package/dist/{chunk-P25IOOU4.js → chunk-MF7NU6BT.js} +795 -139
  54. package/dist/{chunk-GSIDVFE6.js → chunk-QRHGVBKU.js} +3580 -1463
  55. package/dist/{chunk-2SANLSWX.mjs → chunk-YKD22IMR.mjs} +2505 -388
  56. package/dist/cli.js +3244 -533
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +3737 -552
  60. package/dist/edge-light.mjs +3737 -552
  61. package/dist/index.d.mts +871 -199
  62. package/dist/index.d.ts +871 -199
  63. package/dist/index.js +893 -446
  64. package/dist/index.mjs +463 -16
  65. package/dist/instrumentation/index.d.mts +138 -6
  66. package/dist/instrumentation/index.d.ts +138 -6
  67. package/dist/instrumentation/index.js +3362 -559
  68. package/dist/instrumentation/index.mjs +3362 -559
  69. package/dist/vitest-evals-reporter.js +45 -43
  70. package/dist/vitest-evals-reporter.mjs +5 -3
  71. package/dist/workerd.d.mts +1 -1
  72. package/dist/workerd.d.ts +1 -1
  73. package/dist/workerd.js +3737 -552
  74. package/dist/workerd.mjs +3737 -552
  75. package/licenses/node-diagnostics-channel/LICENSE +19 -0
  76. package/package.json +34 -35
  77. package/dist/auto-instrumentations/chunk-VT6DDNKM.mjs +0 -856
  78. package/dist/auto-instrumentations/plugin-D0KHwSJv.d.mts +0 -44
  79. package/dist/auto-instrumentations/plugin-G6fgxk1b.d.ts +0 -44
@@ -46,52 +46,535 @@ var import_source_map = require("source-map");
46
46
  // src/auto-instrumentations/orchestrion-js/transforms.ts
47
47
  var import_esquery = __toESM(require("esquery"));
48
48
  var import_meriyah = require("meriyah");
49
- var tracingChannelPredicate = (node) => node.declarations?.[0]?.id?.properties?.[0]?.value?.name === "tr_ch_apm_tracingChannel";
50
- var CHANNEL_REGEX = /[^\w]/g;
51
- function formatChannelVariable(channelName) {
52
- return `tr_ch_apm$${channelName.replace(CHANNEL_REGEX, "_")}`;
49
+
50
+ // src/global-instrumentation-hooks.ts
51
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
52
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
53
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
54
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
55
+ var GLOBAL_INVOCATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.invocation-hook";
56
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
57
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
58
+ var invocationHookBrand = Symbol.for(GLOBAL_INVOCATION_HOOK_BRAND);
59
+ var errorReporter;
60
+ function reportError(error) {
61
+ try {
62
+ errorReporter?.(error);
63
+ } catch {
64
+ }
53
65
  }
54
- var transforms = {
55
- tracingChannelImport({ dcModule, moduleType }, node) {
56
- if (node.body.some(tracingChannelPredicate)) {
57
- return;
66
+ function setContextValue(context, key, value) {
67
+ try {
68
+ context[key] = value;
69
+ } catch (error) {
70
+ reportError(error);
71
+ }
72
+ }
73
+ function wrapStoreRun(store, message, next, transform) {
74
+ return () => {
75
+ let context;
76
+ try {
77
+ context = transform ? transform(message) : message;
78
+ } catch (error) {
79
+ reportError(error);
80
+ return next();
58
81
  }
59
- const options = { module: moduleType === "esm" };
60
- const index = node.body.findIndex(
61
- (child) => child.directive === "use strict"
82
+ let called = false;
83
+ let result;
84
+ let providerError;
85
+ let providerThrew = false;
86
+ const runNext = () => {
87
+ if (called) {
88
+ reportError(
89
+ new Error(
90
+ "Instrumentation store invoked its callback more than once"
91
+ )
92
+ );
93
+ if (providerThrew) {
94
+ throw providerError;
95
+ }
96
+ return result;
97
+ }
98
+ called = true;
99
+ try {
100
+ result = next();
101
+ return result;
102
+ } catch (error) {
103
+ providerThrew = true;
104
+ providerError = error;
105
+ throw error;
106
+ }
107
+ };
108
+ try {
109
+ store.run(context, runNext);
110
+ } catch (error) {
111
+ if (!providerThrew || error !== providerError) {
112
+ reportError(error);
113
+ }
114
+ }
115
+ if (!called) {
116
+ reportError(
117
+ new Error("Instrumentation store did not invoke its callback")
118
+ );
119
+ return runNext();
120
+ }
121
+ if (providerThrew) {
122
+ throw providerError;
123
+ }
124
+ return result;
125
+ };
126
+ }
127
+ var HookChannel = class {
128
+ constructor(name) {
129
+ this.name = name;
130
+ }
131
+ name;
132
+ subscribers = [];
133
+ stores = /* @__PURE__ */ new Map();
134
+ get hasSubscribers() {
135
+ return this.subscribers.length > 0 || this.stores.size > 0;
136
+ }
137
+ subscribe(subscription) {
138
+ if (typeof subscription !== "function") {
139
+ throw new TypeError("subscription must be a function");
140
+ }
141
+ this.subscribers = [...this.subscribers, subscription];
142
+ }
143
+ unsubscribe(subscription) {
144
+ const index = this.subscribers.indexOf(subscription);
145
+ if (index === -1) {
146
+ return false;
147
+ }
148
+ this.subscribers = [
149
+ ...this.subscribers.slice(0, index),
150
+ ...this.subscribers.slice(index + 1)
151
+ ];
152
+ return true;
153
+ }
154
+ bindStore(store, transform) {
155
+ if (!store || typeof store.run !== "function") {
156
+ throw new TypeError("store must have a run method");
157
+ }
158
+ this.stores.set(
159
+ store,
160
+ transform
62
161
  );
63
- const dc = moduleType === "esm" ? `import tr_ch_apm_dc from "${dcModule}"` : `const tr_ch_apm_dc = ${"require"}("${dcModule}")`;
64
- const tracingChannel = "const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc";
65
- const hasSubscribers = `const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
66
- || ch.end.hasSubscribers
67
- || ch.asyncStart.hasSubscribers
68
- || ch.asyncEnd.hasSubscribers
69
- || ch.error.hasSubscribers`;
70
- node.body.splice(
71
- index + 1,
72
- 0,
73
- (0, import_meriyah.parse)(dc, options).body[0],
74
- (0, import_meriyah.parse)(tracingChannel, options).body[0],
75
- (0, import_meriyah.parse)(hasSubscribers, options).body[0]
162
+ }
163
+ unbindStore(store) {
164
+ return this.stores.delete(store);
165
+ }
166
+ publish(message) {
167
+ const subscribers = this.subscribers;
168
+ for (const subscriber of subscribers) {
169
+ try {
170
+ subscriber(message, this.name);
171
+ } catch (error) {
172
+ reportError(error);
173
+ }
174
+ }
175
+ }
176
+ runStores(message, fn, thisArg, ...args) {
177
+ let run = () => {
178
+ this.publish(message);
179
+ return Reflect.apply(fn, thisArg, args);
180
+ };
181
+ for (const [store, transform] of this.stores.entries()) {
182
+ run = wrapStoreRun(store, message, run, transform);
183
+ }
184
+ return run();
185
+ }
186
+ };
187
+ var traceEvents = [
188
+ "start",
189
+ "end",
190
+ "asyncStart",
191
+ "asyncEnd",
192
+ "error"
193
+ ];
194
+ function traceInvocation(hook, operator, target, thisArg, args, additional, callbackIndex = -1) {
195
+ const context = {
196
+ ...additional,
197
+ arguments: args,
198
+ self: thisArg
199
+ };
200
+ const invoke = () => hook.invoke(target, thisArg, args, additional);
201
+ if (operator === "traceCallback") {
202
+ return hook.traceCallback(invoke, callbackIndex, context);
203
+ }
204
+ if (operator === "tracePromise") {
205
+ return hook.tracePromise(invoke, context);
206
+ }
207
+ return hook.traceSync(invoke, context);
208
+ }
209
+ var InvocationHook = class {
210
+ interceptors = [];
211
+ get hasInterceptors() {
212
+ return this.interceptors.length > 0;
213
+ }
214
+ intercept(interceptor) {
215
+ if (typeof interceptor !== "function") {
216
+ throw new TypeError("interceptor must be a function");
217
+ }
218
+ this.interceptors = [...this.interceptors, interceptor];
219
+ let active = true;
220
+ return () => {
221
+ if (!active) {
222
+ return;
223
+ }
224
+ active = false;
225
+ const index = this.interceptors.indexOf(interceptor);
226
+ if (index !== -1) {
227
+ this.interceptors = [
228
+ ...this.interceptors.slice(0, index),
229
+ ...this.interceptors.slice(index + 1)
230
+ ];
231
+ }
232
+ };
233
+ }
234
+ invoke(target, thisArg, args, additional) {
235
+ const interceptors = this.interceptors;
236
+ if (interceptors.length === 0) {
237
+ return Reflect.apply(target, thisArg, args);
238
+ }
239
+ let next = target;
240
+ for (let index = interceptors.length - 1; index >= 0; index -= 1) {
241
+ const interceptor = interceptors[index];
242
+ const downstream = next;
243
+ next = function(...nextArgs) {
244
+ return interceptor(downstream, this, nextArgs, additional);
245
+ };
246
+ }
247
+ return Reflect.apply(next, thisArg, args);
248
+ }
249
+ };
250
+ var TracingHook = class {
251
+ start;
252
+ end;
253
+ asyncStart;
254
+ asyncEnd;
255
+ error;
256
+ invocationHook = new InvocationHook();
257
+ constructor(nameOrChannels) {
258
+ Object.defineProperty(this, hookBrand, {
259
+ configurable: false,
260
+ enumerable: false,
261
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
262
+ writable: false
263
+ });
264
+ Object.defineProperty(this, invocationHookBrand, {
265
+ configurable: false,
266
+ enumerable: false,
267
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
268
+ writable: false
269
+ });
270
+ if (typeof nameOrChannels === "string") {
271
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
272
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
273
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
274
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
275
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
276
+ return;
277
+ }
278
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
279
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
280
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
281
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
282
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
283
+ }
284
+ get hasSubscribers() {
285
+ return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
286
+ }
287
+ get hasInterceptors() {
288
+ return this.invocationHook.hasInterceptors;
289
+ }
290
+ intercept(interceptor) {
291
+ return this.invocationHook.intercept(interceptor);
292
+ }
293
+ invoke(target, thisArg, args, additional) {
294
+ return this.invocationHook.invoke(target, thisArg, args, additional);
295
+ }
296
+ traceInvocation(operator, target, thisArg, args, additional, callbackIndex = -1) {
297
+ return traceInvocation(
298
+ this,
299
+ operator,
300
+ target,
301
+ thisArg,
302
+ args,
303
+ additional,
304
+ callbackIndex
76
305
  );
306
+ }
307
+ subscribe(handlers) {
308
+ for (const eventName of traceEvents) {
309
+ const handler = handlers[eventName];
310
+ if (handler) {
311
+ this[eventName].subscribe(handler);
312
+ }
313
+ }
314
+ }
315
+ unsubscribe(handlers) {
316
+ let done = true;
317
+ for (const eventName of traceEvents) {
318
+ const handler = handlers[eventName];
319
+ if (handler && !this[eventName].unsubscribe(handler)) {
320
+ done = false;
321
+ }
322
+ }
323
+ return done;
324
+ }
325
+ traceSync(fn, message = {}, thisArg, ...args) {
326
+ if (!this.hasSubscribers) {
327
+ return Reflect.apply(fn, thisArg, args);
328
+ }
329
+ const context = message;
330
+ return this.start.runStores(message, () => {
331
+ try {
332
+ const result = Reflect.apply(fn, thisArg, args);
333
+ setContextValue(context, "result", result);
334
+ return result;
335
+ } catch (error) {
336
+ setContextValue(context, "error", error);
337
+ this.error.publish(message);
338
+ throw error;
339
+ } finally {
340
+ this.end.publish(message);
341
+ }
342
+ });
343
+ }
344
+ tracePromise(fn, message = {}, thisArg, ...args) {
345
+ if (!this.hasSubscribers) {
346
+ return Reflect.apply(fn, thisArg, args);
347
+ }
348
+ const context = message;
349
+ return this.start.runStores(message, () => {
350
+ let result;
351
+ try {
352
+ result = Reflect.apply(fn, thisArg, args);
353
+ } catch (error) {
354
+ setContextValue(context, "error", error);
355
+ this.error.publish(message);
356
+ this.end.publish(message);
357
+ throw error;
358
+ }
359
+ this.end.publish(message);
360
+ if (!result || typeof result !== "object" && typeof result !== "function") {
361
+ setContextValue(context, "result", result);
362
+ this.asyncStart.publish(message);
363
+ this.asyncEnd.publish(message);
364
+ return result;
365
+ }
366
+ let terminalPublished = false;
367
+ const finishUnobservedResult = (error) => {
368
+ reportError(error);
369
+ if (!terminalPublished) {
370
+ terminalPublished = true;
371
+ setContextValue(context, "result", result);
372
+ this.asyncStart.publish(message);
373
+ this.asyncEnd.publish(message);
374
+ }
375
+ return result;
376
+ };
377
+ let then;
378
+ try {
379
+ then = result.then;
380
+ } catch (error) {
381
+ return finishUnobservedResult(error);
382
+ }
383
+ if (typeof then !== "function") {
384
+ setContextValue(context, "result", result);
385
+ this.asyncStart.publish(message);
386
+ this.asyncEnd.publish(message);
387
+ return result;
388
+ }
389
+ const resolve = (resolved) => {
390
+ if (!terminalPublished) {
391
+ terminalPublished = true;
392
+ setContextValue(context, "result", resolved);
393
+ this.asyncStart.publish(message);
394
+ this.asyncEnd.publish(message);
395
+ }
396
+ return resolved;
397
+ };
398
+ let rejectionThrown = false;
399
+ let rejectionError;
400
+ const reject = (error) => {
401
+ if (!terminalPublished) {
402
+ terminalPublished = true;
403
+ setContextValue(context, "error", error);
404
+ this.error.publish(message);
405
+ this.asyncStart.publish(message);
406
+ this.asyncEnd.publish(message);
407
+ }
408
+ rejectionThrown = true;
409
+ rejectionError = error;
410
+ throw error;
411
+ };
412
+ let isPlainPromise;
413
+ try {
414
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
415
+ } catch (error) {
416
+ return finishUnobservedResult(error);
417
+ }
418
+ try {
419
+ if (isPlainPromise) {
420
+ return Reflect.apply(then, result, [resolve, reject]);
421
+ }
422
+ Reflect.apply(then, result, [
423
+ resolve,
424
+ (error) => {
425
+ try {
426
+ reject(error);
427
+ } catch {
428
+ }
429
+ }
430
+ ]);
431
+ } catch (error) {
432
+ if (rejectionThrown && error === rejectionError) {
433
+ return result;
434
+ }
435
+ return finishUnobservedResult(error);
436
+ }
437
+ return result;
438
+ });
439
+ }
440
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
441
+ if (!this.hasSubscribers) {
442
+ return Reflect.apply(fn, thisArg, args);
443
+ }
444
+ const context = message;
445
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
446
+ const callback = Array.prototype.at.call(callArgs, position);
447
+ if (typeof callback !== "function") {
448
+ return Reflect.apply(fn, thisArg, args);
449
+ }
450
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
451
+ function wrappedCallback(error, result) {
452
+ if (error) {
453
+ setContextValue(context, "error", error);
454
+ errorChannel.publish(message);
455
+ } else {
456
+ setContextValue(context, "result", result);
457
+ }
458
+ return asyncStart.runStores(message, () => {
459
+ try {
460
+ return Reflect.apply(callback, this, arguments);
461
+ } finally {
462
+ asyncEnd.publish(message);
463
+ }
464
+ });
465
+ }
466
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
467
+ return this.start.runStores(message, () => {
468
+ try {
469
+ return Reflect.apply(fn, thisArg, args);
470
+ } catch (error) {
471
+ setContextValue(context, "error", error);
472
+ this.error.publish(message);
473
+ throw error;
474
+ } finally {
475
+ this.end.publish(message);
476
+ }
477
+ });
478
+ }
479
+ };
480
+ var inertChannel = Object.freeze({
481
+ name: "braintrust:inert",
482
+ hasSubscribers: false,
483
+ subscribe() {
484
+ },
485
+ unsubscribe() {
486
+ return false;
487
+ },
488
+ bindStore() {
489
+ },
490
+ unbindStore() {
491
+ return false;
492
+ },
493
+ publish() {
77
494
  },
78
- tracingChannelDeclaration(state, node) {
495
+ runStores(_message, fn, thisArg, ...args) {
496
+ return Reflect.apply(fn, thisArg, args);
497
+ }
498
+ });
499
+ var inertTracingHook = new TracingHook({
500
+ start: inertChannel,
501
+ end: inertChannel,
502
+ asyncStart: inertChannel,
503
+ asyncEnd: inertChannel,
504
+ error: inertChannel
505
+ });
506
+
507
+ // src/auto-instrumentations/orchestrion-js/transforms.ts
508
+ var CHANNEL_REGEX = /[^\w]/g;
509
+ var SHARED_HOOK_LOOKUP = "tr_ch_bt$get_hook";
510
+ function formatChannelVariable(channelName) {
511
+ return `tr_ch_bt$${channelName.replace(CHANNEL_REGEX, "_")}`;
512
+ }
513
+ function formatChannelGetter(channelName) {
514
+ return `tr_ch_bt$get_${channelName.replace(CHANNEL_REGEX, "_")}`;
515
+ }
516
+ var transforms = {
517
+ tracingHookDeclaration(state, node) {
79
518
  const {
80
519
  channelName,
81
520
  module: { name }
82
521
  } = state;
83
522
  const channelVariable = formatChannelVariable(channelName);
523
+ const channelGetter = formatChannelGetter(channelName);
524
+ const hasSharedHookLookup = node.body.some(
525
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
526
+ );
84
527
  if (node.body.some(
85
- (child) => child.declarations?.[0]?.id?.name === channelVariable
528
+ (child) => child.declarations?.[0]?.id?.name === channelGetter
86
529
  )) {
87
530
  return;
88
531
  }
89
- transforms.tracingChannelImport(state, node, null, []);
90
- const index = node.body.findIndex(tracingChannelPredicate);
532
+ const sharedHookLookup = hasSharedHookLookup ? "" : `
533
+ const ${SHARED_HOOK_LOOKUP} = (__bt$hookName) => {
534
+ try {
535
+ const __bt$hooks = globalThis[${JSON.stringify(
536
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
537
+ )}];
538
+ if (
539
+ !(__bt$hooks instanceof Map) ||
540
+ __bt$hooks[Symbol.for(${JSON.stringify(
541
+ GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND
542
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}
543
+ ) return undefined;
544
+ const __bt$hook = Map.prototype.get.call(
545
+ __bt$hooks,
546
+ __bt$hookName
547
+ );
548
+ if (
549
+ (__bt$hook === null ||
550
+ (typeof __bt$hook !== "object" &&
551
+ typeof __bt$hook !== "function")) ||
552
+ __bt$hook[Symbol.for(${JSON.stringify(
553
+ GLOBAL_INSTRUMENTATION_HOOK_BRAND
554
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION} ||
555
+ typeof __bt$hook.traceInvocation !== "function"
556
+ ) return undefined;
557
+ return __bt$hook;
558
+ } catch {
559
+ return undefined;
560
+ }
561
+ };
562
+ `;
91
563
  const code = `
92
- const ${channelVariable} = tr_ch_apm_tracingChannel("orchestrion:${name}:${channelName}")
564
+ ${sharedHookLookup}
565
+ let ${channelVariable};
566
+ const ${channelGetter} = () =>
567
+ ${channelVariable} ??= ${SHARED_HOOK_LOOKUP}(
568
+ ${JSON.stringify(`orchestrion:${name}:${channelName}`)}
569
+ );
93
570
  `;
94
- node.body.splice(index + 1, 0, (0, import_meriyah.parse)(code).body[0]);
571
+ const sharedHookLookupIndex = node.body.findIndex(
572
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
573
+ );
574
+ const index = sharedHookLookupIndex === -1 ? node.body.findIndex(
575
+ (child) => child.directive === "use strict"
576
+ ) : sharedHookLookupIndex;
577
+ node.body.splice(index + 1, 0, ...(0, import_meriyah.parse)(code).body);
95
578
  },
96
579
  traceCallback: traceAny,
97
580
  tracePromise: traceAny,
@@ -106,25 +589,21 @@ function traceAny(state, node, _parent, ancestry) {
106
589
  }
107
590
  }
108
591
  function traceFunction(state, node, program) {
109
- transforms.tracingChannelDeclaration(state, program, null, []);
592
+ transforms.tracingHookDeclaration(state, program, null, []);
110
593
  const { functionQuery } = state;
111
594
  const methodName = "methodName" in functionQuery ? functionQuery.methodName : void 0;
112
595
  const privateMethodName = "privateMethodName" in functionQuery ? functionQuery.privateMethodName : void 0;
113
596
  const functionName = "functionName" in functionQuery ? functionQuery.functionName : void 0;
114
597
  const isConstructor = methodName === "constructor" || !methodName && !privateMethodName && !functionName;
115
598
  const type = isConstructor ? "ArrowFunctionExpression" : "FunctionExpression";
116
- node.body = wrap(
117
- state,
118
- {
119
- type,
120
- params: node.params,
121
- body: node.body,
122
- async: node.async,
123
- expression: false,
124
- generator: node.generator
125
- },
126
- program
127
- );
599
+ node.body = wrap(state, {
600
+ type,
601
+ params: node.params,
602
+ body: node.body,
603
+ async: node.async,
604
+ expression: false,
605
+ generator: node.generator
606
+ });
128
607
  node.generator = false;
129
608
  node.async = false;
130
609
  wrapSuper(node);
@@ -136,11 +615,11 @@ function traceInstanceMethod(state, node, program) {
136
615
  return;
137
616
  }
138
617
  const classBody = node.body;
139
- if (classBody.body.some(({ key }) => key.name === methodName)) {
618
+ if (classBody.body.some(({ key }) => key?.name === methodName)) {
140
619
  return;
141
620
  }
142
621
  let ctor = classBody.body.find(({ kind }) => kind === "constructor");
143
- transforms.tracingChannelDeclaration(state, program, null, []);
622
+ transforms.tracingHookDeclaration(state, program, null, []);
144
623
  if (!ctor) {
145
624
  ctor = (0, import_meriyah.parse)(
146
625
  node.superClass ? "class A extends Object { constructor (...args) { super(...args) } }" : "class A { constructor () {} }"
@@ -148,47 +627,36 @@ function traceInstanceMethod(state, node, program) {
148
627
  classBody.body.unshift(ctor);
149
628
  }
150
629
  const ctorBody = (0, import_meriyah.parse)(`
151
- const __apm$${methodName} = this["${methodName}"]
630
+ const __bt$${methodName} = this["${methodName}"]
152
631
  this["${methodName}"] = function () {}
153
632
  `).body;
154
633
  const fn = ctorBody[1].expression.right;
155
634
  fn.async = operator === "tracePromise";
156
- fn.body = wrap(
157
- state,
158
- { type: "Identifier", name: `__apm$${methodName}` },
159
- program
160
- );
635
+ fn.body = wrap(state, {
636
+ type: "Identifier",
637
+ name: `__bt$${methodName}`
638
+ });
161
639
  wrapSuper(fn);
162
640
  ctor.value.body.body.push(...ctorBody);
163
641
  }
164
- function wrap(state, node, program) {
165
- const { operator, moduleVersion } = state;
166
- const wrapper = operator === "traceCallback" ? wrapCallback(state) : operator === "tracePromise" ? wrapPromise(state) : wrapSync(state);
642
+ function wrap(state, node) {
643
+ const wrapper = wrapInvocation(state);
167
644
  const block = wrapper.body[0].body;
168
645
  const common = (0, import_meriyah.parse)(
169
646
  node.type === "ArrowFunctionExpression" ? `
170
- const __apm$ctx = {
171
- arguments,
172
- moduleVersion: ${JSON.stringify(moduleVersion)}
173
- };
174
- const __apm$traced = () => {
175
- const __apm$wrapped = () => {};
176
- return __apm$wrapped(...arguments);
647
+ const __bt$target = (...__bt$args) => {
648
+ const __bt$wrapped = () => {};
649
+ return __bt$wrapped(...__bt$args);
177
650
  };
178
651
  ` : `
179
- const __apm$ctx = {
180
- arguments,
181
- self: this,
182
- moduleVersion: ${JSON.stringify(moduleVersion)}
183
- };
184
- const __apm$traced = () => {
185
- const __apm$wrapped = () => {};
186
- return __apm$wrapped.apply(this, arguments);
652
+ const __bt$target = function (...__bt$args) {
653
+ const __bt$wrapped = () => {};
654
+ return __bt$wrapped.apply(this, __bt$args);
187
655
  };
188
656
  `
189
657
  ).body;
190
658
  block.body.unshift(...common);
191
- import_esquery.default.query(block, "[id.name=__apm$wrapped]")[0].init = node;
659
+ import_esquery.default.query(block, "[id.name=__bt$wrapped]")[0].init = node;
192
660
  return block;
193
661
  }
194
662
  function wrapSuper(node) {
@@ -200,11 +668,11 @@ function wrapSuper(node) {
200
668
  const { name } = node2.property;
201
669
  let child;
202
670
  if (parent.callee) {
203
- const { expression } = (0, import_meriyah.parse)(`__apm$super['${name}'].call(this)`).body[0];
671
+ const { expression } = (0, import_meriyah.parse)(`__bt$super['${name}'].call(this)`).body[0];
204
672
  parent.callee = child = expression.callee;
205
673
  parent.arguments.unshift(...expression.arguments);
206
674
  } else {
207
- parent.expression = child = (0, import_meriyah.parse)(`__apm$super['${name}']`).body[0];
675
+ parent.expression = child = (0, import_meriyah.parse)(`__bt$super['${name}']`).body[0];
208
676
  }
209
677
  child.computed = parent.callee.computed;
210
678
  child.optional = parent.callee.optional;
@@ -215,151 +683,32 @@ function wrapSuper(node) {
215
683
  const member = (0, import_meriyah.parse)(`
216
684
  class Wrapper {
217
685
  wrapper () {
218
- __apm$super['${name}'] = super['${name}']
686
+ __bt$super['${name}'] = super['${name}']
219
687
  }
220
688
  }
221
689
  `).body[0].body.body[0].value.body.body[0];
222
690
  node.body.body.unshift(member);
223
691
  }
224
692
  if (members.size > 0) {
225
- node.body.body.unshift((0, import_meriyah.parse)("const __apm$super = {}").body[0]);
693
+ node.body.body.unshift((0, import_meriyah.parse)("const __bt$super = {}").body[0]);
226
694
  }
227
695
  }
228
- function wrapCallback(state) {
229
- const {
230
- channelName,
231
- functionQuery: { callbackIndex = -1 }
232
- } = state;
233
- const channelVariable = formatChannelVariable(channelName);
696
+ function wrapInvocation(state) {
697
+ const { channelName, moduleVersion, operator, functionQuery } = state;
698
+ const channelGetter = formatChannelGetter(channelName);
699
+ const callbackIndex = functionQuery.callbackIndex ?? -1;
234
700
  return (0, import_meriyah.parse)(`
235
701
  function wrapper () {
236
- const __apm$cb = Array.prototype.at.call(arguments, ${callbackIndex});
237
-
238
- if (!${channelVariable}.start.hasSubscribers) return __apm$traced();
239
-
240
- function __apm$wrappedCb(err, res) {
241
- if (err) {
242
- __apm$ctx.error = err;
243
- ${channelVariable}.error.publish(__apm$ctx);
244
- } else {
245
- __apm$ctx.result = res;
246
- }
247
-
248
- ${channelVariable}.asyncStart.runStores(__apm$ctx, () => {
249
- try {
250
- if (__apm$cb) {
251
- return __apm$cb.apply(this, arguments);
252
- }
253
- } finally {
254
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
255
- }
256
- });
257
- }
258
-
259
- if (typeof __apm$cb !== 'function') {
260
- return __apm$traced();
261
- }
262
- Array.prototype.splice.call(arguments, ${callbackIndex}, 1, __apm$wrappedCb);
263
-
264
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
265
- try {
266
- return __apm$traced();
267
- } catch (err) {
268
- __apm$ctx.error = err;
269
- ${channelVariable}.error.publish(__apm$ctx);
270
- throw err;
271
- } finally {
272
- __apm$ctx.self ??= this;
273
- ${channelVariable}.end.publish(__apm$ctx);
274
- }
275
- });
276
- }
277
- `);
278
- }
279
- function wrapPromise(state) {
280
- const { channelName } = state;
281
- const channelVariable = formatChannelVariable(channelName);
282
- return (0, import_meriyah.parse)(`
283
- function wrapper () {
284
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
285
-
286
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
287
- try {
288
- let promise = __apm$traced();
289
- if (typeof promise?.then !== 'function') {
290
- __apm$ctx.result = promise;
291
- return promise;
292
- }
293
- // Mirror Node.js core diagnostics_channel behaviour: for native Promise
294
- // instances, chain normally (safe since there is no subclass API to
295
- // preserve). For Promise subclasses and other thenables, side-chain the
296
- // callbacks for event publishing and return the original so that any
297
- // subclass-specific methods (e.g. APIPromise.withResponse()) remain
298
- // accessible to the caller.
299
- if (promise instanceof Promise && promise.constructor === Promise) {
300
- return promise.then(
301
- result => {
302
- __apm$ctx.result = result;
303
- ${channelVariable}.asyncStart.publish(__apm$ctx);
304
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
305
- return result;
306
- },
307
- err => {
308
- __apm$ctx.error = err;
309
- ${channelVariable}.error.publish(__apm$ctx);
310
- ${channelVariable}.asyncStart.publish(__apm$ctx);
311
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
312
- throw err;
313
- }
314
- );
315
- }
316
- promise.then(
317
- result => {
318
- __apm$ctx.result = result;
319
- ${channelVariable}.asyncStart.publish(__apm$ctx);
320
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
321
- },
322
- err => {
323
- __apm$ctx.error = err;
324
- ${channelVariable}.error.publish(__apm$ctx);
325
- ${channelVariable}.asyncStart.publish(__apm$ctx);
326
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
327
- }
328
- );
329
- return promise;
330
- } catch (err) {
331
- __apm$ctx.error = err;
332
- ${channelVariable}.error.publish(__apm$ctx);
333
- throw err;
334
- } finally {
335
- __apm$ctx.self ??= this;
336
- ${channelVariable}.end.publish(__apm$ctx);
337
- }
338
- });
339
- }
340
- `);
341
- }
342
- function wrapSync(state) {
343
- const { channelName } = state;
344
- const channelVariable = formatChannelVariable(channelName);
345
- return (0, import_meriyah.parse)(`
346
- function wrapper () {
347
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
348
-
349
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
350
- try {
351
- const result = __apm$traced();
352
- __apm$ctx.result = result;
353
- return result;
354
- } catch (err) {
355
- __apm$ctx.error = err;
356
- ${channelVariable}.error.publish(__apm$ctx);
357
- throw err;
358
- } finally {
359
- __apm$ctx.self ??= this;
360
- ${channelVariable}.end.publish(__apm$ctx);
361
- }
362
- });
702
+ const __bt$hook = ${channelGetter}();
703
+ if (!__bt$hook) return __bt$target.apply(this, arguments);
704
+ return __bt$hook.traceInvocation(
705
+ ${JSON.stringify(operator)},
706
+ __bt$target,
707
+ this,
708
+ arguments,
709
+ { moduleVersion: ${JSON.stringify(moduleVersion)} },
710
+ ${callbackIndex}
711
+ );
363
712
  }
364
713
  `);
365
714
  }
@@ -370,16 +719,14 @@ var Transformer = class {
370
719
  version;
371
720
  filePath;
372
721
  configs = [];
373
- dcModule;
374
- constructor(moduleName, version, filePath, configs, dcModule) {
722
+ constructor(moduleName, version, filePath, configs) {
375
723
  this.moduleName = moduleName;
376
724
  this.version = version;
377
725
  this.filePath = filePath;
378
726
  this.configs = configs;
379
- this.dcModule = dcModule;
380
727
  }
381
728
  /**
382
- * Instruments `code` by injecting diagnostics_channel tracing around the
729
+ * Instruments `code` by injecting global tracing hooks around the
383
730
  * target functions defined by this transformer's configs.
384
731
  */
385
732
  transform(code, moduleType) {
@@ -417,8 +764,6 @@ var Transformer = class {
417
764
  const query = astQuery || this.fromFunctionQuery(resolvedFunctionQuery);
418
765
  const state = {
419
766
  ...config,
420
- dcModule: this.dcModule,
421
- moduleType,
422
767
  moduleVersion: this.version,
423
768
  functionQuery: resolvedFunctionQuery,
424
769
  operator: this.getOperator(resolvedFunctionQuery.kind)
@@ -568,11 +913,9 @@ var Transformer = class {
568
913
  // src/auto-instrumentations/orchestrion-js/matcher.ts
569
914
  var InstrumentationMatcher = class {
570
915
  configs = [];
571
- dcModule;
572
916
  transformers = {};
573
- constructor(configs, dcModule) {
917
+ constructor(configs) {
574
918
  this.configs = configs;
575
- this.dcModule = dcModule || "diagnostics_channel";
576
919
  }
577
920
  /**
578
921
  * Returns a Transformer for the given module/file/version, or undefined if no
@@ -594,8 +937,7 @@ var InstrumentationMatcher = class {
594
937
  moduleName,
595
938
  version,
596
939
  filePath,
597
- configs,
598
- this.dcModule
940
+ configs
599
941
  );
600
942
  return this.transformers[id];
601
943
  }
@@ -605,8 +947,8 @@ var InstrumentationMatcher = class {
605
947
  };
606
948
 
607
949
  // src/auto-instrumentations/orchestrion-js/index.ts
608
- function create(configs, dcModule) {
609
- return new InstrumentationMatcher(configs, dcModule);
950
+ function create(configs) {
951
+ return new InstrumentationMatcher(configs);
610
952
  }
611
953
 
612
954
  // src/auto-instrumentations/loader/cjs-patch.ts
@@ -864,6 +1206,9 @@ function applySpecialCasePatch(input) {
864
1206
  if (input.packageName === "openai" && input.modulePath.includes("api-promise")) {
865
1207
  return input.source + OPENAI_API_PROMISE_PATCH;
866
1208
  }
1209
+ if (input.browser) {
1210
+ return null;
1211
+ }
867
1212
  const mastraTarget = classifyMastraTarget(
868
1213
  input.packageName,
869
1214
  input.modulePath
@@ -892,7 +1237,7 @@ var ModulePatch = class {
892
1237
  /**
893
1238
  * Patches the Node.js module class method that is responsible for compiling code.
894
1239
  * If a module is found that has an instrumentator, it will transform the code before compiling it
895
- * with tracing channel methods.
1240
+ * with global hook calls.
896
1241
  */
897
1242
  patch() {
898
1243
  const self = this;