braintrust 3.25.0 → 3.26.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 (78) 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 +2455 -1116
  5. package/dev/dist/index.mjs +1599 -260
  6. package/dist/apply-auto-instrumentation.js +439 -398
  7. package/dist/apply-auto-instrumentation.mjs +242 -201
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +853 -337
  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 +5 -8
  12. package/dist/auto-instrumentations/bundler/next.cjs +852 -356
  13. package/dist/auto-instrumentations/bundler/next.mjs +6 -29
  14. package/dist/auto-instrumentations/bundler/rollup.cjs +853 -337
  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 +5 -8
  18. package/dist/auto-instrumentations/bundler/vite.cjs +853 -337
  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 +5 -8
  22. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1006 -266
  23. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +20 -12
  24. package/dist/auto-instrumentations/bundler/webpack.cjs +853 -337
  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 +5 -4
  28. package/dist/auto-instrumentations/{chunk-JPVCUKTY.mjs → chunk-6E22MYSW.mjs} +165 -73
  29. package/dist/auto-instrumentations/{chunk-VT6DDNKM.mjs → chunk-AKKPLXTP.mjs} +631 -194
  30. package/dist/auto-instrumentations/chunk-NRE4QUQR.mjs +509 -0
  31. package/dist/auto-instrumentations/{chunk-7P6563SW.mjs → chunk-V5LEODRX.mjs} +2 -6
  32. package/dist/auto-instrumentations/{chunk-M6DLIJ2Z.mjs → chunk-XYN63IG5.mjs} +124 -194
  33. package/dist/auto-instrumentations/{chunk-CZ24KNHT.mjs → chunk-XZHHE4Y3.mjs} +77 -68
  34. package/dist/auto-instrumentations/hook.mjs +247 -182
  35. package/dist/auto-instrumentations/index.cjs +557 -48
  36. package/dist/auto-instrumentations/index.d.mts +6 -2
  37. package/dist/auto-instrumentations/index.d.ts +6 -2
  38. package/dist/auto-instrumentations/index.mjs +6 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +492 -195
  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 +817 -197
  49. package/dist/browser.d.ts +817 -197
  50. package/dist/browser.js +1883 -265
  51. package/dist/browser.mjs +1883 -265
  52. package/dist/{chunk-ABR2QWDP.mjs → chunk-PN7EWK66.mjs} +581 -133
  53. package/dist/{chunk-GSIDVFE6.js → chunk-VRZZQPAA.js} +1670 -736
  54. package/dist/{chunk-P25IOOU4.js → chunk-VYNNEKSA.js} +586 -138
  55. package/dist/{chunk-2SANLSWX.mjs → chunk-XIZOM2HO.mjs} +1052 -118
  56. package/dist/cli.js +1601 -263
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +1883 -268
  60. package/dist/edge-light.mjs +1883 -268
  61. package/dist/index.d.mts +817 -197
  62. package/dist/index.d.ts +817 -197
  63. package/dist/index.js +695 -435
  64. package/dist/index.mjs +264 -4
  65. package/dist/instrumentation/index.d.mts +130 -6
  66. package/dist/instrumentation/index.d.ts +130 -6
  67. package/dist/instrumentation/index.js +1510 -80
  68. package/dist/instrumentation/index.mjs +1510 -80
  69. package/dist/vitest-evals-reporter.js +16 -16
  70. package/dist/vitest-evals-reporter.mjs +2 -2
  71. package/dist/workerd.d.mts +1 -1
  72. package/dist/workerd.d.ts +1 -1
  73. package/dist/workerd.js +1883 -268
  74. package/dist/workerd.mjs +1883 -268
  75. package/licenses/node-diagnostics-channel/LICENSE +19 -0
  76. package/package.json +34 -35
  77. package/dist/auto-instrumentations/plugin-D0KHwSJv.d.mts +0 -44
  78. package/dist/auto-instrumentations/plugin-G6fgxk1b.d.ts +0 -44
@@ -51,52 +51,583 @@ var import_source_map = require("source-map");
51
51
  // src/auto-instrumentations/orchestrion-js/transforms.ts
52
52
  var import_esquery = __toESM(require("esquery"));
53
53
  var import_meriyah = require("meriyah");
54
- var tracingChannelPredicate = (node) => node.declarations?.[0]?.id?.properties?.[0]?.value?.name === "tr_ch_apm_tracingChannel";
55
- var CHANNEL_REGEX = /[^\w]/g;
56
- function formatChannelVariable(channelName) {
57
- return `tr_ch_apm$${channelName.replace(CHANNEL_REGEX, "_")}`;
54
+
55
+ // src/global-instrumentation-hooks.ts
56
+ var GLOBAL_INSTRUMENTATION_HOOKS_KEY = "__braintrust_instrumentation_hooks";
57
+ var GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION = 1;
58
+ var GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND = "braintrust.global-instrumentation-hooks.registry";
59
+ var GLOBAL_INSTRUMENTATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.hook";
60
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
61
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
62
+ var errorReporter;
63
+ function reportError(error) {
64
+ try {
65
+ errorReporter?.(error);
66
+ } catch {
67
+ }
58
68
  }
59
- var transforms = {
60
- tracingChannelImport({ dcModule, moduleType }, node) {
61
- if (node.body.some(tracingChannelPredicate)) {
69
+ function setContextValue(context, key, value) {
70
+ try {
71
+ context[key] = value;
72
+ } catch (error) {
73
+ reportError(error);
74
+ }
75
+ }
76
+ function wrapStoreRun(store, message, next, transform) {
77
+ return () => {
78
+ let context;
79
+ try {
80
+ context = transform ? transform(message) : message;
81
+ } catch (error) {
82
+ reportError(error);
83
+ return next();
84
+ }
85
+ let called = false;
86
+ let result;
87
+ let providerError;
88
+ let providerThrew = false;
89
+ const runNext = () => {
90
+ if (called) {
91
+ reportError(
92
+ new Error(
93
+ "Instrumentation store invoked its callback more than once"
94
+ )
95
+ );
96
+ if (providerThrew) {
97
+ throw providerError;
98
+ }
99
+ return result;
100
+ }
101
+ called = true;
102
+ try {
103
+ result = next();
104
+ return result;
105
+ } catch (error) {
106
+ providerThrew = true;
107
+ providerError = error;
108
+ throw error;
109
+ }
110
+ };
111
+ try {
112
+ store.run(context, runNext);
113
+ } catch (error) {
114
+ if (!providerThrew || error !== providerError) {
115
+ reportError(error);
116
+ }
117
+ }
118
+ if (!called) {
119
+ reportError(
120
+ new Error("Instrumentation store did not invoke its callback")
121
+ );
122
+ return runNext();
123
+ }
124
+ if (providerThrew) {
125
+ throw providerError;
126
+ }
127
+ return result;
128
+ };
129
+ }
130
+ var HookChannel = class {
131
+ constructor(name) {
132
+ this.name = name;
133
+ }
134
+ name;
135
+ subscribers = [];
136
+ stores = /* @__PURE__ */ new Map();
137
+ get hasSubscribers() {
138
+ return this.subscribers.length > 0 || this.stores.size > 0;
139
+ }
140
+ subscribe(subscription) {
141
+ if (typeof subscription !== "function") {
142
+ throw new TypeError("subscription must be a function");
143
+ }
144
+ this.subscribers = [...this.subscribers, subscription];
145
+ }
146
+ unsubscribe(subscription) {
147
+ const index = this.subscribers.indexOf(subscription);
148
+ if (index === -1) {
149
+ return false;
150
+ }
151
+ this.subscribers = [
152
+ ...this.subscribers.slice(0, index),
153
+ ...this.subscribers.slice(index + 1)
154
+ ];
155
+ return true;
156
+ }
157
+ bindStore(store, transform) {
158
+ if (!store || typeof store.run !== "function") {
159
+ throw new TypeError("store must have a run method");
160
+ }
161
+ this.stores.set(
162
+ store,
163
+ transform
164
+ );
165
+ }
166
+ unbindStore(store) {
167
+ return this.stores.delete(store);
168
+ }
169
+ publish(message) {
170
+ const subscribers = this.subscribers;
171
+ for (const subscriber of subscribers) {
172
+ try {
173
+ subscriber(message, this.name);
174
+ } catch (error) {
175
+ reportError(error);
176
+ }
177
+ }
178
+ }
179
+ runStores(message, fn, thisArg, ...args) {
180
+ let run = () => {
181
+ this.publish(message);
182
+ return Reflect.apply(fn, thisArg, args);
183
+ };
184
+ for (const [store, transform] of this.stores.entries()) {
185
+ run = wrapStoreRun(store, message, run, transform);
186
+ }
187
+ return run();
188
+ }
189
+ };
190
+ var traceEvents = [
191
+ "start",
192
+ "end",
193
+ "asyncStart",
194
+ "asyncEnd",
195
+ "error"
196
+ ];
197
+ var TracingHook = class {
198
+ start;
199
+ end;
200
+ asyncStart;
201
+ asyncEnd;
202
+ error;
203
+ constructor(nameOrChannels) {
204
+ Object.defineProperty(this, hookBrand, {
205
+ configurable: false,
206
+ enumerable: false,
207
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
208
+ writable: false
209
+ });
210
+ if (typeof nameOrChannels === "string") {
211
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
212
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
213
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
214
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
215
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
62
216
  return;
63
217
  }
64
- const options = { module: moduleType === "esm" };
65
- const index = node.body.findIndex(
66
- (child) => child.directive === "use strict"
218
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
219
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
220
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
221
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
222
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
223
+ }
224
+ get hasSubscribers() {
225
+ return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
226
+ }
227
+ subscribe(handlers) {
228
+ for (const eventName of traceEvents) {
229
+ const handler = handlers[eventName];
230
+ if (handler) {
231
+ this[eventName].subscribe(handler);
232
+ }
233
+ }
234
+ }
235
+ unsubscribe(handlers) {
236
+ let done = true;
237
+ for (const eventName of traceEvents) {
238
+ const handler = handlers[eventName];
239
+ if (handler && !this[eventName].unsubscribe(handler)) {
240
+ done = false;
241
+ }
242
+ }
243
+ return done;
244
+ }
245
+ traceSync(fn, message = {}, thisArg, ...args) {
246
+ if (!this.hasSubscribers) {
247
+ return Reflect.apply(fn, thisArg, args);
248
+ }
249
+ const context = message;
250
+ return this.start.runStores(message, () => {
251
+ try {
252
+ const result = Reflect.apply(fn, thisArg, args);
253
+ setContextValue(context, "result", result);
254
+ return result;
255
+ } catch (error) {
256
+ setContextValue(context, "error", error);
257
+ this.error.publish(message);
258
+ throw error;
259
+ } finally {
260
+ this.end.publish(message);
261
+ }
262
+ });
263
+ }
264
+ tracePromise(fn, message = {}, thisArg, ...args) {
265
+ if (!this.hasSubscribers) {
266
+ return Reflect.apply(fn, thisArg, args);
267
+ }
268
+ const context = message;
269
+ return this.start.runStores(message, () => {
270
+ let result;
271
+ try {
272
+ result = Reflect.apply(fn, thisArg, args);
273
+ } catch (error) {
274
+ setContextValue(context, "error", error);
275
+ this.error.publish(message);
276
+ this.end.publish(message);
277
+ throw error;
278
+ }
279
+ this.end.publish(message);
280
+ if (!result || typeof result !== "object" && typeof result !== "function") {
281
+ setContextValue(context, "result", result);
282
+ this.asyncStart.publish(message);
283
+ this.asyncEnd.publish(message);
284
+ return result;
285
+ }
286
+ let terminalPublished = false;
287
+ const finishUnobservedResult = (error) => {
288
+ reportError(error);
289
+ if (!terminalPublished) {
290
+ terminalPublished = true;
291
+ setContextValue(context, "result", result);
292
+ this.asyncStart.publish(message);
293
+ this.asyncEnd.publish(message);
294
+ }
295
+ return result;
296
+ };
297
+ let then;
298
+ try {
299
+ then = result.then;
300
+ } catch (error) {
301
+ return finishUnobservedResult(error);
302
+ }
303
+ if (typeof then !== "function") {
304
+ setContextValue(context, "result", result);
305
+ this.asyncStart.publish(message);
306
+ this.asyncEnd.publish(message);
307
+ return result;
308
+ }
309
+ const resolve = (resolved) => {
310
+ if (!terminalPublished) {
311
+ terminalPublished = true;
312
+ setContextValue(context, "result", resolved);
313
+ this.asyncStart.publish(message);
314
+ this.asyncEnd.publish(message);
315
+ }
316
+ return resolved;
317
+ };
318
+ let rejectionThrown = false;
319
+ let rejectionError;
320
+ const reject = (error) => {
321
+ if (!terminalPublished) {
322
+ terminalPublished = true;
323
+ setContextValue(context, "error", error);
324
+ this.error.publish(message);
325
+ this.asyncStart.publish(message);
326
+ this.asyncEnd.publish(message);
327
+ }
328
+ rejectionThrown = true;
329
+ rejectionError = error;
330
+ throw error;
331
+ };
332
+ let isPlainPromise;
333
+ try {
334
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
335
+ } catch (error) {
336
+ return finishUnobservedResult(error);
337
+ }
338
+ try {
339
+ if (isPlainPromise) {
340
+ return Reflect.apply(then, result, [resolve, reject]);
341
+ }
342
+ Reflect.apply(then, result, [
343
+ resolve,
344
+ (error) => {
345
+ try {
346
+ reject(error);
347
+ } catch {
348
+ }
349
+ }
350
+ ]);
351
+ } catch (error) {
352
+ if (rejectionThrown && error === rejectionError) {
353
+ return result;
354
+ }
355
+ return finishUnobservedResult(error);
356
+ }
357
+ return result;
358
+ });
359
+ }
360
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
361
+ if (!this.hasSubscribers) {
362
+ return Reflect.apply(fn, thisArg, args);
363
+ }
364
+ const context = message;
365
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
366
+ const callback = Array.prototype.at.call(callArgs, position);
367
+ if (typeof callback !== "function") {
368
+ return Reflect.apply(fn, thisArg, args);
369
+ }
370
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
371
+ function wrappedCallback(error, result) {
372
+ if (error) {
373
+ setContextValue(context, "error", error);
374
+ errorChannel.publish(message);
375
+ } else {
376
+ setContextValue(context, "result", result);
377
+ }
378
+ return asyncStart.runStores(message, () => {
379
+ try {
380
+ return Reflect.apply(callback, this, arguments);
381
+ } finally {
382
+ asyncEnd.publish(message);
383
+ }
384
+ });
385
+ }
386
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
387
+ return this.start.runStores(message, () => {
388
+ try {
389
+ return Reflect.apply(fn, thisArg, args);
390
+ } catch (error) {
391
+ setContextValue(context, "error", error);
392
+ this.error.publish(message);
393
+ throw error;
394
+ } finally {
395
+ this.end.publish(message);
396
+ }
397
+ });
398
+ }
399
+ };
400
+ var inertChannel = Object.freeze({
401
+ name: "braintrust:inert",
402
+ hasSubscribers: false,
403
+ subscribe() {
404
+ },
405
+ unsubscribe() {
406
+ return false;
407
+ },
408
+ bindStore() {
409
+ },
410
+ unbindStore() {
411
+ return false;
412
+ },
413
+ publish() {
414
+ },
415
+ runStores(_message, fn, thisArg, ...args) {
416
+ return Reflect.apply(fn, thisArg, args);
417
+ }
418
+ });
419
+ var inertTracingHook = new TracingHook({
420
+ start: inertChannel,
421
+ end: inertChannel,
422
+ asyncStart: inertChannel,
423
+ asyncEnd: inertChannel,
424
+ error: inertChannel
425
+ });
426
+ function isHookChannel(value) {
427
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
428
+ return false;
429
+ }
430
+ try {
431
+ const channel2 = value;
432
+ return typeof channel2.hasSubscribers === "boolean" && typeof channel2.subscribe === "function" && typeof channel2.unsubscribe === "function" && typeof channel2.bindStore === "function" && typeof channel2.unbindStore === "function" && typeof channel2.publish === "function" && typeof channel2.runStores === "function";
433
+ } catch {
434
+ return false;
435
+ }
436
+ }
437
+ function hasTracingHookShape(value) {
438
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
439
+ return false;
440
+ }
441
+ try {
442
+ const hook = value;
443
+ return typeof hook.hasSubscribers === "boolean" && typeof hook.subscribe === "function" && typeof hook.unsubscribe === "function" && typeof hook.traceSync === "function" && typeof hook.tracePromise === "function" && typeof hook.traceCallback === "function" && isHookChannel(hook.start) && isHookChannel(hook.end) && isHookChannel(hook.asyncStart) && isHookChannel(hook.asyncEnd) && isHookChannel(hook.error);
444
+ } catch {
445
+ return false;
446
+ }
447
+ }
448
+ function isCompatibleTracingHook(value) {
449
+ try {
450
+ return value[hookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && hasTracingHookShape(value);
451
+ } catch {
452
+ return false;
453
+ }
454
+ }
455
+ function isCompatibleHookRegistry(value) {
456
+ try {
457
+ return value instanceof Map && value[registryBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION;
458
+ } catch {
459
+ return false;
460
+ }
461
+ }
462
+ function getHookRegistry() {
463
+ let descriptor;
464
+ try {
465
+ descriptor = Object.getOwnPropertyDescriptor(
466
+ globalThis,
467
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
67
468
  );
68
- const dc = moduleType === "esm" ? `import tr_ch_apm_dc from "${dcModule}"` : `const tr_ch_apm_dc = ${"require"}("${dcModule}")`;
69
- const tracingChannel = "const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc";
70
- const hasSubscribers = `const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
71
- || ch.end.hasSubscribers
72
- || ch.asyncStart.hasSubscribers
73
- || ch.asyncEnd.hasSubscribers
74
- || ch.error.hasSubscribers`;
75
- node.body.splice(
76
- index + 1,
77
- 0,
78
- (0, import_meriyah.parse)(dc, options).body[0],
79
- (0, import_meriyah.parse)(tracingChannel, options).body[0],
80
- (0, import_meriyah.parse)(hasSubscribers, options).body[0]
469
+ } catch (error) {
470
+ reportError(error);
471
+ return void 0;
472
+ }
473
+ if (descriptor && "value" in descriptor && isCompatibleHookRegistry(descriptor.value) && (descriptor.configurable || descriptor.enumerable === false)) {
474
+ if (descriptor.configurable || descriptor.writable) {
475
+ try {
476
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
477
+ configurable: false,
478
+ enumerable: false,
479
+ value: descriptor.value,
480
+ writable: false
481
+ });
482
+ } catch (error) {
483
+ reportError(error);
484
+ return void 0;
485
+ }
486
+ }
487
+ return descriptor.value;
488
+ }
489
+ if (descriptor && !descriptor.configurable) {
490
+ reportError(new Error("Incompatible global instrumentation hook registry"));
491
+ return void 0;
492
+ }
493
+ const registry = /* @__PURE__ */ new Map();
494
+ try {
495
+ Object.defineProperty(registry, registryBrand, {
496
+ configurable: false,
497
+ enumerable: false,
498
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
499
+ writable: false
500
+ });
501
+ } catch (error) {
502
+ reportError(error);
503
+ return void 0;
504
+ }
505
+ try {
506
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
507
+ configurable: false,
508
+ enumerable: false,
509
+ value: registry,
510
+ writable: false
511
+ });
512
+ return registry;
513
+ } catch (error) {
514
+ reportError(error);
515
+ return void 0;
516
+ }
517
+ }
518
+ function newGlobalTracingChannel(nameOrChannels) {
519
+ if (typeof nameOrChannels !== "string") {
520
+ return new TracingHook(nameOrChannels);
521
+ }
522
+ const registry = getHookRegistry();
523
+ if (!registry) {
524
+ return inertTracingHook;
525
+ }
526
+ let existing;
527
+ try {
528
+ existing = Map.prototype.get.call(registry, nameOrChannels);
529
+ } catch (error) {
530
+ reportError(error);
531
+ return inertTracingHook;
532
+ }
533
+ if (isCompatibleTracingHook(existing)) {
534
+ return existing;
535
+ }
536
+ if (existing !== void 0) {
537
+ reportError(
538
+ new Error(`Invalid global instrumentation hook: ${nameOrChannels}`)
81
539
  );
82
- },
83
- tracingChannelDeclaration(state, node) {
540
+ try {
541
+ Map.prototype.delete.call(registry, nameOrChannels);
542
+ } catch (error) {
543
+ reportError(error);
544
+ return inertTracingHook;
545
+ }
546
+ }
547
+ const hook = new TracingHook(nameOrChannels);
548
+ try {
549
+ Map.prototype.set.call(registry, nameOrChannels, hook);
550
+ } catch (error) {
551
+ reportError(error);
552
+ return inertTracingHook;
553
+ }
554
+ return hook;
555
+ }
556
+
557
+ // src/auto-instrumentations/orchestrion-js/transforms.ts
558
+ var CHANNEL_REGEX = /[^\w]/g;
559
+ var SHARED_HOOK_LOOKUP = "tr_ch_bt$get_hook";
560
+ function formatChannelVariable(channelName) {
561
+ return `tr_ch_bt$${channelName.replace(CHANNEL_REGEX, "_")}`;
562
+ }
563
+ function formatChannelGetter(channelName) {
564
+ return `tr_ch_bt$get_${channelName.replace(CHANNEL_REGEX, "_")}`;
565
+ }
566
+ var transforms = {
567
+ tracingHookDeclaration(state, node) {
84
568
  const {
85
569
  channelName,
86
- module: { name }
570
+ module: { name },
571
+ operator
87
572
  } = state;
88
573
  const channelVariable = formatChannelVariable(channelName);
574
+ const channelGetter = formatChannelGetter(channelName);
575
+ const hasSharedHookLookup = node.body.some(
576
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
577
+ );
89
578
  if (node.body.some(
90
- (child) => child.declarations?.[0]?.id?.name === channelVariable
579
+ (child) => child.declarations?.[0]?.id?.name === channelGetter
91
580
  )) {
92
581
  return;
93
582
  }
94
- transforms.tracingChannelImport(state, node, null, []);
95
- const index = node.body.findIndex(tracingChannelPredicate);
583
+ const sharedHookLookup = hasSharedHookLookup ? "" : `
584
+ const ${SHARED_HOOK_LOOKUP} = (__bt$hookName, __bt$operator) => {
585
+ try {
586
+ const __bt$hooks = globalThis[${JSON.stringify(
587
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
588
+ )}];
589
+ if (
590
+ !(__bt$hooks instanceof Map) ||
591
+ __bt$hooks[Symbol.for(${JSON.stringify(
592
+ GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND
593
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}
594
+ ) return undefined;
595
+ const __bt$hook = Map.prototype.get.call(
596
+ __bt$hooks,
597
+ __bt$hookName
598
+ );
599
+ if (
600
+ (__bt$hook === null ||
601
+ (typeof __bt$hook !== "object" &&
602
+ typeof __bt$hook !== "function")) ||
603
+ __bt$hook[Symbol.for(${JSON.stringify(
604
+ GLOBAL_INSTRUMENTATION_HOOK_BRAND
605
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION} ||
606
+ typeof __bt$hook.hasSubscribers !== "boolean" ||
607
+ typeof __bt$hook[__bt$operator] !== "function"
608
+ ) return undefined;
609
+ return __bt$hook;
610
+ } catch {
611
+ return undefined;
612
+ }
613
+ };
614
+ `;
96
615
  const code = `
97
- const ${channelVariable} = tr_ch_apm_tracingChannel("orchestrion:${name}:${channelName}")
616
+ ${sharedHookLookup}
617
+ let ${channelVariable};
618
+ const ${channelGetter} = () =>
619
+ ${channelVariable} ??= ${SHARED_HOOK_LOOKUP}(
620
+ ${JSON.stringify(`orchestrion:${name}:${channelName}`)},
621
+ ${JSON.stringify(operator)}
622
+ );
98
623
  `;
99
- node.body.splice(index + 1, 0, (0, import_meriyah.parse)(code).body[0]);
624
+ const sharedHookLookupIndex = node.body.findIndex(
625
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
626
+ );
627
+ const index = sharedHookLookupIndex === -1 ? node.body.findIndex(
628
+ (child) => child.directive === "use strict"
629
+ ) : sharedHookLookupIndex;
630
+ node.body.splice(index + 1, 0, ...(0, import_meriyah.parse)(code).body);
100
631
  },
101
632
  traceCallback: traceAny,
102
633
  tracePromise: traceAny,
@@ -111,25 +642,21 @@ function traceAny(state, node, _parent, ancestry) {
111
642
  }
112
643
  }
113
644
  function traceFunction(state, node, program) {
114
- transforms.tracingChannelDeclaration(state, program, null, []);
645
+ transforms.tracingHookDeclaration(state, program, null, []);
115
646
  const { functionQuery } = state;
116
647
  const methodName = "methodName" in functionQuery ? functionQuery.methodName : void 0;
117
648
  const privateMethodName = "privateMethodName" in functionQuery ? functionQuery.privateMethodName : void 0;
118
649
  const functionName = "functionName" in functionQuery ? functionQuery.functionName : void 0;
119
650
  const isConstructor = methodName === "constructor" || !methodName && !privateMethodName && !functionName;
120
651
  const type = isConstructor ? "ArrowFunctionExpression" : "FunctionExpression";
121
- node.body = wrap(
122
- state,
123
- {
124
- type,
125
- params: node.params,
126
- body: node.body,
127
- async: node.async,
128
- expression: false,
129
- generator: node.generator
130
- },
131
- program
132
- );
652
+ node.body = wrap(state, {
653
+ type,
654
+ params: node.params,
655
+ body: node.body,
656
+ async: node.async,
657
+ expression: false,
658
+ generator: node.generator
659
+ });
133
660
  node.generator = false;
134
661
  node.async = false;
135
662
  wrapSuper(node);
@@ -141,11 +668,11 @@ function traceInstanceMethod(state, node, program) {
141
668
  return;
142
669
  }
143
670
  const classBody = node.body;
144
- if (classBody.body.some(({ key }) => key.name === methodName)) {
671
+ if (classBody.body.some(({ key }) => key?.name === methodName)) {
145
672
  return;
146
673
  }
147
674
  let ctor = classBody.body.find(({ kind }) => kind === "constructor");
148
- transforms.tracingChannelDeclaration(state, program, null, []);
675
+ transforms.tracingHookDeclaration(state, program, null, []);
149
676
  if (!ctor) {
150
677
  ctor = (0, import_meriyah.parse)(
151
678
  node.superClass ? "class A extends Object { constructor (...args) { super(...args) } }" : "class A { constructor () {} }"
@@ -153,47 +680,46 @@ function traceInstanceMethod(state, node, program) {
153
680
  classBody.body.unshift(ctor);
154
681
  }
155
682
  const ctorBody = (0, import_meriyah.parse)(`
156
- const __apm$${methodName} = this["${methodName}"]
683
+ const __bt$${methodName} = this["${methodName}"]
157
684
  this["${methodName}"] = function () {}
158
685
  `).body;
159
686
  const fn = ctorBody[1].expression.right;
160
687
  fn.async = operator === "tracePromise";
161
- fn.body = wrap(
162
- state,
163
- { type: "Identifier", name: `__apm$${methodName}` },
164
- program
165
- );
688
+ fn.body = wrap(state, {
689
+ type: "Identifier",
690
+ name: `__bt$${methodName}`
691
+ });
166
692
  wrapSuper(fn);
167
693
  ctor.value.body.body.push(...ctorBody);
168
694
  }
169
- function wrap(state, node, program) {
695
+ function wrap(state, node) {
170
696
  const { operator, moduleVersion } = state;
171
697
  const wrapper = operator === "traceCallback" ? wrapCallback(state) : operator === "tracePromise" ? wrapPromise(state) : wrapSync(state);
172
698
  const block = wrapper.body[0].body;
173
699
  const common = (0, import_meriyah.parse)(
174
700
  node.type === "ArrowFunctionExpression" ? `
175
- const __apm$ctx = {
701
+ const __bt$ctx = {
176
702
  arguments,
177
703
  moduleVersion: ${JSON.stringify(moduleVersion)}
178
704
  };
179
- const __apm$traced = () => {
180
- const __apm$wrapped = () => {};
181
- return __apm$wrapped(...arguments);
705
+ const __bt$traced = () => {
706
+ const __bt$wrapped = () => {};
707
+ return __bt$wrapped(...arguments);
182
708
  };
183
709
  ` : `
184
- const __apm$ctx = {
710
+ const __bt$ctx = {
185
711
  arguments,
186
712
  self: this,
187
713
  moduleVersion: ${JSON.stringify(moduleVersion)}
188
714
  };
189
- const __apm$traced = () => {
190
- const __apm$wrapped = () => {};
191
- return __apm$wrapped.apply(this, arguments);
715
+ const __bt$traced = () => {
716
+ const __bt$wrapped = () => {};
717
+ return __bt$wrapped.apply(this, arguments);
192
718
  };
193
719
  `
194
720
  ).body;
195
721
  block.body.unshift(...common);
196
- import_esquery.default.query(block, "[id.name=__apm$wrapped]")[0].init = node;
722
+ import_esquery.default.query(block, "[id.name=__bt$wrapped]")[0].init = node;
197
723
  return block;
198
724
  }
199
725
  function wrapSuper(node) {
@@ -205,11 +731,11 @@ function wrapSuper(node) {
205
731
  const { name } = node2.property;
206
732
  let child;
207
733
  if (parent.callee) {
208
- const { expression } = (0, import_meriyah.parse)(`__apm$super['${name}'].call(this)`).body[0];
734
+ const { expression } = (0, import_meriyah.parse)(`__bt$super['${name}'].call(this)`).body[0];
209
735
  parent.callee = child = expression.callee;
210
736
  parent.arguments.unshift(...expression.arguments);
211
737
  } else {
212
- parent.expression = child = (0, import_meriyah.parse)(`__apm$super['${name}']`).body[0];
738
+ parent.expression = child = (0, import_meriyah.parse)(`__bt$super['${name}']`).body[0];
213
739
  }
214
740
  child.computed = parent.callee.computed;
215
741
  child.optional = parent.callee.optional;
@@ -220,14 +746,14 @@ function wrapSuper(node) {
220
746
  const member = (0, import_meriyah.parse)(`
221
747
  class Wrapper {
222
748
  wrapper () {
223
- __apm$super['${name}'] = super['${name}']
749
+ __bt$super['${name}'] = super['${name}']
224
750
  }
225
751
  }
226
752
  `).body[0].body.body[0].value.body.body[0];
227
753
  node.body.body.unshift(member);
228
754
  }
229
755
  if (members.size > 0) {
230
- node.body.body.unshift((0, import_meriyah.parse)("const __apm$super = {}").body[0]);
756
+ node.body.body.unshift((0, import_meriyah.parse)("const __bt$super = {}").body[0]);
231
757
  }
232
758
  }
233
759
  function wrapCallback(state) {
@@ -235,136 +761,41 @@ function wrapCallback(state) {
235
761
  channelName,
236
762
  functionQuery: { callbackIndex = -1 }
237
763
  } = state;
238
- const channelVariable = formatChannelVariable(channelName);
764
+ const channelGetter = formatChannelGetter(channelName);
239
765
  return (0, import_meriyah.parse)(`
240
766
  function wrapper () {
241
- const __apm$cb = Array.prototype.at.call(arguments, ${callbackIndex});
242
-
243
- if (!${channelVariable}.start.hasSubscribers) return __apm$traced();
244
-
245
- function __apm$wrappedCb(err, res) {
246
- if (err) {
247
- __apm$ctx.error = err;
248
- ${channelVariable}.error.publish(__apm$ctx);
249
- } else {
250
- __apm$ctx.result = res;
251
- }
252
-
253
- ${channelVariable}.asyncStart.runStores(__apm$ctx, () => {
254
- try {
255
- if (__apm$cb) {
256
- return __apm$cb.apply(this, arguments);
257
- }
258
- } finally {
259
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
260
- }
261
- });
262
- }
263
-
264
- if (typeof __apm$cb !== 'function') {
265
- return __apm$traced();
266
- }
267
- Array.prototype.splice.call(arguments, ${callbackIndex}, 1, __apm$wrappedCb);
268
-
269
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
270
- try {
271
- return __apm$traced();
272
- } catch (err) {
273
- __apm$ctx.error = err;
274
- ${channelVariable}.error.publish(__apm$ctx);
275
- throw err;
276
- } finally {
277
- __apm$ctx.self ??= this;
278
- ${channelVariable}.end.publish(__apm$ctx);
279
- }
280
- });
767
+ const __bt$hook = ${channelGetter}();
768
+ if (!__bt$hook?.hasSubscribers) return __bt$traced();
769
+ __bt$ctx.self ??= this;
770
+ return __bt$hook.traceCallback(
771
+ __bt$traced,
772
+ ${callbackIndex},
773
+ __bt$ctx
774
+ );
281
775
  }
282
776
  `);
283
777
  }
284
778
  function wrapPromise(state) {
285
779
  const { channelName } = state;
286
- const channelVariable = formatChannelVariable(channelName);
780
+ const channelGetter = formatChannelGetter(channelName);
287
781
  return (0, import_meriyah.parse)(`
288
782
  function wrapper () {
289
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
290
-
291
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
292
- try {
293
- let promise = __apm$traced();
294
- if (typeof promise?.then !== 'function') {
295
- __apm$ctx.result = promise;
296
- return promise;
297
- }
298
- // Mirror Node.js core diagnostics_channel behaviour: for native Promise
299
- // instances, chain normally (safe since there is no subclass API to
300
- // preserve). For Promise subclasses and other thenables, side-chain the
301
- // callbacks for event publishing and return the original so that any
302
- // subclass-specific methods (e.g. APIPromise.withResponse()) remain
303
- // accessible to the caller.
304
- if (promise instanceof Promise && promise.constructor === Promise) {
305
- return promise.then(
306
- result => {
307
- __apm$ctx.result = result;
308
- ${channelVariable}.asyncStart.publish(__apm$ctx);
309
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
310
- return result;
311
- },
312
- err => {
313
- __apm$ctx.error = err;
314
- ${channelVariable}.error.publish(__apm$ctx);
315
- ${channelVariable}.asyncStart.publish(__apm$ctx);
316
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
317
- throw err;
318
- }
319
- );
320
- }
321
- promise.then(
322
- result => {
323
- __apm$ctx.result = result;
324
- ${channelVariable}.asyncStart.publish(__apm$ctx);
325
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
326
- },
327
- err => {
328
- __apm$ctx.error = err;
329
- ${channelVariable}.error.publish(__apm$ctx);
330
- ${channelVariable}.asyncStart.publish(__apm$ctx);
331
- ${channelVariable}.asyncEnd.publish(__apm$ctx);
332
- }
333
- );
334
- return promise;
335
- } catch (err) {
336
- __apm$ctx.error = err;
337
- ${channelVariable}.error.publish(__apm$ctx);
338
- throw err;
339
- } finally {
340
- __apm$ctx.self ??= this;
341
- ${channelVariable}.end.publish(__apm$ctx);
342
- }
343
- });
783
+ const __bt$hook = ${channelGetter}();
784
+ if (!__bt$hook?.hasSubscribers) return __bt$traced();
785
+ __bt$ctx.self ??= this;
786
+ return __bt$hook.tracePromise(__bt$traced, __bt$ctx);
344
787
  }
345
788
  `);
346
789
  }
347
790
  function wrapSync(state) {
348
791
  const { channelName } = state;
349
- const channelVariable = formatChannelVariable(channelName);
792
+ const channelGetter = formatChannelGetter(channelName);
350
793
  return (0, import_meriyah.parse)(`
351
794
  function wrapper () {
352
- if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
353
-
354
- return ${channelVariable}.start.runStores(__apm$ctx, () => {
355
- try {
356
- const result = __apm$traced();
357
- __apm$ctx.result = result;
358
- return result;
359
- } catch (err) {
360
- __apm$ctx.error = err;
361
- ${channelVariable}.error.publish(__apm$ctx);
362
- throw err;
363
- } finally {
364
- __apm$ctx.self ??= this;
365
- ${channelVariable}.end.publish(__apm$ctx);
366
- }
367
- });
795
+ const __bt$hook = ${channelGetter}();
796
+ if (!__bt$hook?.hasSubscribers) return __bt$traced();
797
+ __bt$ctx.self ??= this;
798
+ return __bt$hook.traceSync(__bt$traced, __bt$ctx);
368
799
  }
369
800
  `);
370
801
  }
@@ -375,16 +806,14 @@ var Transformer = class {
375
806
  version;
376
807
  filePath;
377
808
  configs = [];
378
- dcModule;
379
- constructor(moduleName, version, filePath, configs, dcModule) {
809
+ constructor(moduleName, version, filePath, configs) {
380
810
  this.moduleName = moduleName;
381
811
  this.version = version;
382
812
  this.filePath = filePath;
383
813
  this.configs = configs;
384
- this.dcModule = dcModule;
385
814
  }
386
815
  /**
387
- * Instruments `code` by injecting diagnostics_channel tracing around the
816
+ * Instruments `code` by injecting global tracing hooks around the
388
817
  * target functions defined by this transformer's configs.
389
818
  */
390
819
  transform(code, moduleType) {
@@ -422,8 +851,6 @@ var Transformer = class {
422
851
  const query = astQuery || this.fromFunctionQuery(resolvedFunctionQuery);
423
852
  const state = {
424
853
  ...config,
425
- dcModule: this.dcModule,
426
- moduleType,
427
854
  moduleVersion: this.version,
428
855
  functionQuery: resolvedFunctionQuery,
429
856
  operator: this.getOperator(resolvedFunctionQuery.kind)
@@ -573,11 +1000,9 @@ var Transformer = class {
573
1000
  // src/auto-instrumentations/orchestrion-js/matcher.ts
574
1001
  var InstrumentationMatcher = class {
575
1002
  configs = [];
576
- dcModule;
577
1003
  transformers = {};
578
- constructor(configs, dcModule) {
1004
+ constructor(configs) {
579
1005
  this.configs = configs;
580
- this.dcModule = dcModule || "diagnostics_channel";
581
1006
  }
582
1007
  /**
583
1008
  * Returns a Transformer for the given module/file/version, or undefined if no
@@ -599,8 +1024,7 @@ var InstrumentationMatcher = class {
599
1024
  moduleName,
600
1025
  version,
601
1026
  filePath,
602
- configs,
603
- this.dcModule
1027
+ configs
604
1028
  );
605
1029
  return this.transformers[id];
606
1030
  }
@@ -610,8 +1034,8 @@ var InstrumentationMatcher = class {
610
1034
  };
611
1035
 
612
1036
  // src/auto-instrumentations/orchestrion-js/index.ts
613
- function create(configs, dcModule) {
614
- return new InstrumentationMatcher(configs, dcModule);
1037
+ function create(configs) {
1038
+ return new InstrumentationMatcher(configs);
615
1039
  }
616
1040
 
617
1041
  // src/auto-instrumentations/bundler/plugin.ts
@@ -637,6 +1061,9 @@ var envIntegrationAliases = {
637
1061
  strandsagentsdk: "strandsAgentSDK",
638
1062
  "strands-agent-sdk": "strandsAgentSDK",
639
1063
  "@strands-agents/sdk": "strandsAgentSDK",
1064
+ agents: "cloudflareAgents",
1065
+ "cloudflare-agents": "cloudflareAgents",
1066
+ cloudflareagents: "cloudflareAgents",
640
1067
  anthropic: "anthropic",
641
1068
  aisdk: "aisdk",
642
1069
  "ai-sdk": "aisdk",
@@ -644,6 +1071,9 @@ var envIntegrationAliases = {
644
1071
  vercel: "vercel",
645
1072
  claudeagentsdk: "claudeAgentSDK",
646
1073
  "claude-agent-sdk": "claudeAgentSDK",
1074
+ cloudflareaichat: "cloudflareAIChat",
1075
+ "cloudflare-ai-chat": "cloudflareAIChat",
1076
+ "@cloudflare/ai-chat": "cloudflareAIChat",
647
1077
  cursor: "cursor",
648
1078
  "cursor-sdk": "cursorSDK",
649
1079
  cursorsdk: "cursorSDK",
@@ -658,6 +1088,8 @@ var envIntegrationAliases = {
658
1088
  "google-genai": "googleGenAI",
659
1089
  googlegenai: "googleGenAI",
660
1090
  huggingface: "huggingface",
1091
+ "@huggingface/transformers": "huggingface",
1092
+ transformers: "huggingface",
661
1093
  openrouter: "openrouter",
662
1094
  openrouteragent: "openrouterAgent",
663
1095
  "openrouter-agent": "openrouterAgent",
@@ -714,73 +1146,6 @@ var DefaultAsyncLocalStorage = class {
714
1146
  return void 0;
715
1147
  }
716
1148
  };
717
- var DefaultChannel = class {
718
- constructor(name) {
719
- this.name = name;
720
- }
721
- name;
722
- hasSubscribers = false;
723
- subscribe(_subscription) {
724
- }
725
- unsubscribe(_subscription) {
726
- return false;
727
- }
728
- bindStore(_store, _transform) {
729
- }
730
- unbindStore(_store) {
731
- return false;
732
- }
733
- publish(_message) {
734
- }
735
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
736
- runStores(_message, fn, thisArg, ...args) {
737
- return fn.apply(thisArg, args);
738
- }
739
- };
740
- var DefaultTracingChannel = class {
741
- start;
742
- end;
743
- asyncStart;
744
- asyncEnd;
745
- error;
746
- constructor(nameOrChannels) {
747
- if (typeof nameOrChannels === "string") {
748
- this.start = new DefaultChannel(`tracing:${nameOrChannels}:start`);
749
- this.end = new DefaultChannel(`tracing:${nameOrChannels}:end`);
750
- this.asyncStart = new DefaultChannel(
751
- `tracing:${nameOrChannels}:asyncStart`
752
- );
753
- this.asyncEnd = new DefaultChannel(`tracing:${nameOrChannels}:asyncEnd`);
754
- this.error = new DefaultChannel(`tracing:${nameOrChannels}:error`);
755
- return;
756
- }
757
- this.start = nameOrChannels.start ?? new DefaultChannel("tracing:start");
758
- this.end = nameOrChannels.end ?? new DefaultChannel("tracing:end");
759
- this.asyncStart = nameOrChannels.asyncStart ?? new DefaultChannel("tracing:asyncStart");
760
- this.asyncEnd = nameOrChannels.asyncEnd ?? new DefaultChannel("tracing:asyncEnd");
761
- this.error = nameOrChannels.error ?? new DefaultChannel("tracing:error");
762
- }
763
- get hasSubscribers() {
764
- return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
765
- }
766
- subscribe(_handlers) {
767
- }
768
- unsubscribe(_handlers) {
769
- return false;
770
- }
771
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
772
- traceSync(fn, _message, thisArg, ...args) {
773
- return fn.apply(thisArg, args);
774
- }
775
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
776
- tracePromise(fn, _message, thisArg, ...args) {
777
- return fn.apply(thisArg, args);
778
- }
779
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
780
- traceCallback(fn, _position, _message, thisArg, ...args) {
781
- return fn.apply(thisArg, args);
782
- }
783
- };
784
1149
  var iso = {
785
1150
  buildType: "unknown",
786
1151
  // Will be set by configureBrowser() or configureNode()
@@ -791,7 +1156,7 @@ var iso = {
791
1156
  getCallerLocation: () => void 0,
792
1157
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
793
1158
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
794
- newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
1159
+ newTracingChannel: (nameOrChannels) => newGlobalTracingChannel(nameOrChannels),
795
1160
  processOn: (_0, _1) => {
796
1161
  },
797
1162
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
@@ -856,6 +1221,8 @@ var INSTRUMENTATION_NAMES = {
856
1221
  BEDROCK_RUNTIME: "bedrock-runtime",
857
1222
  BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
858
1223
  CLAUDE_AGENT_SDK: "claude-agent-sdk",
1224
+ CLOUDFLARE_AI_CHAT: "cloudflare-ai-chat",
1225
+ CLOUDFLARE_AGENTS: "cloudflare-agents",
859
1226
  COHERE: "cohere",
860
1227
  CURSOR_SDK: "cursor-sdk",
861
1228
  EVE: "eve",
@@ -1633,6 +2000,74 @@ var claudeAgentSDKConfigs = [
1633
2000
  }
1634
2001
  ];
1635
2002
 
2003
+ // src/instrumentation/plugins/cloudflare-ai-chat-channels.ts
2004
+ var cloudflareAIChatChannels = defineChannels(
2005
+ "@cloudflare/ai-chat",
2006
+ {
2007
+ runExclusiveChatTurn: channel({
2008
+ channelName: "AIChatAgent._runExclusiveChatTurn",
2009
+ kind: "async"
2010
+ }),
2011
+ onChatResponse: channel({
2012
+ channelName: "AIChatAgent.onChatResponse",
2013
+ kind: "sync-stream"
2014
+ })
2015
+ },
2016
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT }
2017
+ );
2018
+
2019
+ // src/auto-instrumentations/configs/cloudflare-ai-chat.ts
2020
+ var cloudflareAIChatVersionRange = ">=0.9.0 <0.10.0";
2021
+ var cloudflareAIChatConfigs = [
2022
+ {
2023
+ // AIChatAgent subclasses replace onChatMessage, so there is no stable
2024
+ // public implementation for the transformer to target. This runner is
2025
+ // the narrowest shared boundary around every chat turn; keep the version
2026
+ // range tight because it is an internal method.
2027
+ channelName: cloudflareAIChatChannels.runExclusiveChatTurn.channelName,
2028
+ module: {
2029
+ name: "@cloudflare/ai-chat",
2030
+ versionRange: cloudflareAIChatVersionRange,
2031
+ filePath: "dist/index.js"
2032
+ },
2033
+ functionQuery: {
2034
+ className: "AIChatAgent",
2035
+ methodName: "_runExclusiveChatTurn",
2036
+ kind: "Async"
2037
+ }
2038
+ }
2039
+ ];
2040
+
2041
+ // src/instrumentation/plugins/cloudflare-agents-channels.ts
2042
+ var cloudflareAgentsChannels = defineChannels(
2043
+ "agents",
2044
+ {
2045
+ runAgentTool: channel({
2046
+ channelName: "Agent.runAgentTool",
2047
+ kind: "async"
2048
+ })
2049
+ },
2050
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS }
2051
+ );
2052
+
2053
+ // src/auto-instrumentations/configs/cloudflare-agents.ts
2054
+ var cloudflareAgentsVersionRange = ">=0.17.0 <0.18.0";
2055
+ var cloudflareAgentsConfigs = [
2056
+ {
2057
+ channelName: cloudflareAgentsChannels.runAgentTool.channelName,
2058
+ module: {
2059
+ name: "agents",
2060
+ versionRange: cloudflareAgentsVersionRange,
2061
+ filePath: "dist/index.js"
2062
+ },
2063
+ functionQuery: {
2064
+ className: "Agent",
2065
+ methodName: "runAgentTool",
2066
+ kind: "Async"
2067
+ }
2068
+ }
2069
+ ];
2070
+
1636
2071
  // src/instrumentation/plugins/cohere-channels.ts
1637
2072
  var cohereChannels = defineChannels(
1638
2073
  "cohere-ai",
@@ -2995,6 +3430,83 @@ var huggingFaceConfigs = [
2995
3430
  }
2996
3431
  ];
2997
3432
 
3433
+ // src/instrumentation/plugins/huggingface-transformers-channels.ts
3434
+ var huggingFaceTransformersChannels = defineChannels(
3435
+ "@huggingface/transformers",
3436
+ {
3437
+ pipeline: channel({
3438
+ channelName: "pipeline",
3439
+ kind: "async"
3440
+ }),
3441
+ pipelineCall: channel({
3442
+ channelName: "pipeline.call",
3443
+ kind: "async"
3444
+ })
3445
+ },
3446
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
3447
+ );
3448
+
3449
+ // src/auto-instrumentations/configs/huggingface-transformers.ts
3450
+ var moduleFiles = [
3451
+ {
3452
+ filePath: "dist/transformers.mjs",
3453
+ versionRange: ">=3.0.0 <3.4.0"
3454
+ },
3455
+ {
3456
+ filePath: "dist/transformers.cjs",
3457
+ versionRange: ">=3.0.0 <3.4.0"
3458
+ },
3459
+ {
3460
+ filePath: "dist/transformers.js",
3461
+ versionRange: ">=3.0.0 <3.4.0"
3462
+ },
3463
+ {
3464
+ filePath: "dist/transformers.node.mjs",
3465
+ versionRange: ">=3.4.0 <5.0.0"
3466
+ },
3467
+ {
3468
+ filePath: "dist/transformers.node.cjs",
3469
+ versionRange: ">=3.4.0 <5.0.0"
3470
+ },
3471
+ {
3472
+ filePath: "dist/transformers.web.js",
3473
+ versionRange: ">=3.4.0 <5.0.0"
3474
+ }
3475
+ ];
3476
+ var pipelineClasses = [
3477
+ "TextGenerationPipeline",
3478
+ "Text2TextGenerationPipeline",
3479
+ "FeatureExtractionPipeline",
3480
+ "QuestionAnsweringPipeline"
3481
+ ];
3482
+ var huggingFaceTransformersConfigs = moduleFiles.flatMap(({ filePath, versionRange: versionRange2 }) => [
3483
+ {
3484
+ channelName: huggingFaceTransformersChannels.pipeline.channelName,
3485
+ module: {
3486
+ name: "@huggingface/transformers",
3487
+ versionRange: versionRange2,
3488
+ filePath
3489
+ },
3490
+ functionQuery: {
3491
+ functionName: "pipeline",
3492
+ kind: "Async"
3493
+ }
3494
+ },
3495
+ ...pipelineClasses.map((className) => ({
3496
+ channelName: huggingFaceTransformersChannels.pipelineCall.channelName,
3497
+ module: {
3498
+ name: "@huggingface/transformers",
3499
+ versionRange: versionRange2,
3500
+ filePath
3501
+ },
3502
+ functionQuery: {
3503
+ className,
3504
+ methodName: "_call",
3505
+ kind: "Async"
3506
+ }
3507
+ }))
3508
+ ]);
3509
+
2998
3510
  // src/instrumentation/plugins/langchain-channels.ts
2999
3511
  var langChainChannels = defineChannels(
3000
3512
  "@langchain/core",
@@ -4013,6 +4525,14 @@ var defaultInstrumentationConfigGroups = [
4013
4525
  integrations: ["claudeAgentSDK"],
4014
4526
  configs: claudeAgentSDKConfigs
4015
4527
  },
4528
+ {
4529
+ integrations: ["cloudflareAIChat"],
4530
+ configs: cloudflareAIChatConfigs
4531
+ },
4532
+ {
4533
+ integrations: ["cloudflareAgents"],
4534
+ configs: cloudflareAgentsConfigs
4535
+ },
4016
4536
  { integrations: ["cursor", "cursorSDK"], configs: cursorSDKConfigs },
4017
4537
  {
4018
4538
  integrations: ["openAIAgents"],
@@ -4022,7 +4542,10 @@ var defaultInstrumentationConfigGroups = [
4022
4542
  integrations: ["google", "googleGenAI"],
4023
4543
  configs: googleGenAIConfigs
4024
4544
  },
4025
- { integrations: ["huggingface"], configs: huggingFaceConfigs },
4545
+ {
4546
+ integrations: ["huggingface"],
4547
+ configs: [...huggingFaceConfigs, ...huggingFaceTransformersConfigs]
4548
+ },
4026
4549
  {
4027
4550
  integrations: ["langchain", "langgraph"],
4028
4551
  configs: langchainConfigs
@@ -4276,6 +4799,9 @@ function applySpecialCasePatch(input) {
4276
4799
  if (input.packageName === "openai" && input.modulePath.includes("api-promise")) {
4277
4800
  return input.source + OPENAI_API_PROMISE_PATCH;
4278
4801
  }
4802
+ if (input.browser) {
4803
+ return null;
4804
+ }
4279
4805
  const mastraTarget = classifyMastraTarget(
4280
4806
  input.packageName,
4281
4807
  input.modulePath
@@ -4298,78 +4824,72 @@ function getModuleVersion(basedir) {
4298
4824
  }
4299
4825
  return void 0;
4300
4826
  }
4301
- var unplugin = (0, import_unplugin.createUnplugin)(
4302
- (options = {}) => {
4303
- const allInstrumentations = getDefaultInstrumentationConfigs({
4304
- additionalInstrumentations: options.instrumentations
4305
- });
4306
- const dcModule = options.browser === false ? void 0 : "dc-browser";
4307
- const instrumentationMatcher = create(allInstrumentations, dcModule);
4308
- return {
4309
- name: "code-transformer",
4310
- enforce: "pre",
4311
- transform(code, id) {
4312
- if (!id) {
4313
- return null;
4314
- }
4315
- const filePath = id.startsWith("file:") ? (0, import_url.fileURLToPath)(id) : id;
4316
- const ext = (0, import_path.extname)(filePath);
4317
- let isModule = ext === ".mjs" || ext === ".ts" || ext === ".tsx";
4318
- if (ext === ".js") {
4319
- isModule = code.includes("export ") || code.includes("import ");
4320
- }
4321
- const normalizedForPlatform = filePath.split("/").join(import_path.sep);
4322
- const moduleDetails = (0, import_module_details_from_path.default)(normalizedForPlatform);
4323
- if (!moduleDetails) {
4324
- return null;
4325
- }
4326
- const moduleName = moduleDetails.name;
4327
- const normalizedModulePath = moduleDetails.path.replace(/\\/g, "/");
4328
- const moduleVersion = getModuleVersion(moduleDetails.basedir);
4329
- if (options.browser !== true) {
4330
- const patched = applySpecialCasePatch({
4331
- packageName: moduleName,
4332
- modulePath: normalizedModulePath,
4333
- source: code,
4334
- format: isModule ? "esm" : "cjs"
4335
- });
4336
- if (patched !== null) {
4337
- return { code: patched, map: null };
4338
- }
4339
- }
4340
- if (!moduleVersion) {
4341
- console.warn(
4342
- `No 'package.json' version found for module ${moduleName} at ${moduleDetails.basedir}. Skipping transformation.`
4343
- );
4344
- return null;
4345
- }
4346
- const transformer = instrumentationMatcher.getTransformer(
4347
- moduleName,
4348
- moduleVersion,
4349
- normalizedModulePath
4827
+ var unplugin = (0, import_unplugin.createUnplugin)((options = {}) => {
4828
+ const browser = options.browser ?? options.useDiagnosticChannelCompatShim ?? false;
4829
+ const allInstrumentations = getDefaultInstrumentationConfigs({
4830
+ additionalInstrumentations: options.instrumentations
4831
+ });
4832
+ const instrumentationMatcher = create(allInstrumentations);
4833
+ return {
4834
+ name: "code-transformer",
4835
+ enforce: "pre",
4836
+ transform(code, id) {
4837
+ if (!id) {
4838
+ return null;
4839
+ }
4840
+ const cleanId = id.replace(/[?#].*$/, "");
4841
+ const filePath = cleanId.startsWith("file:") ? (0, import_url.fileURLToPath)(cleanId) : cleanId;
4842
+ const ext = (0, import_path.extname)(filePath);
4843
+ let isModule = ext === ".mjs" || ext === ".ts" || ext === ".tsx";
4844
+ if (ext === ".js") {
4845
+ isModule = code.includes("export ") || code.includes("import ");
4846
+ }
4847
+ const normalizedForPlatform = filePath.split("/").join(import_path.sep);
4848
+ const moduleDetails = (0, import_module_details_from_path.default)(normalizedForPlatform);
4849
+ if (!moduleDetails) {
4850
+ return null;
4851
+ }
4852
+ const moduleName = moduleDetails.name;
4853
+ const normalizedModulePath = moduleDetails.path.replace(/\\/g, "/");
4854
+ const moduleVersion = getModuleVersion(moduleDetails.basedir);
4855
+ const patched = applySpecialCasePatch({
4856
+ packageName: moduleName,
4857
+ modulePath: normalizedModulePath,
4858
+ source: code,
4859
+ format: isModule ? "esm" : "cjs",
4860
+ browser
4861
+ });
4862
+ if (patched !== null) {
4863
+ return { code: patched, map: null };
4864
+ }
4865
+ if (!moduleVersion) {
4866
+ console.warn(
4867
+ `No 'package.json' version found for module ${moduleName} at ${moduleDetails.basedir}. Skipping transformation.`
4350
4868
  );
4351
- if (!transformer) {
4352
- return null;
4353
- }
4354
- try {
4355
- const moduleType = isModule ? "esm" : "cjs";
4356
- const result = transformer.transform(code, moduleType);
4357
- const transformedCode = result.code.replace(
4358
- /const \{tracingChannel: ([A-Za-z_$][\w$]*)\} = ([A-Za-z_$][\w$]*);/g,
4359
- "const $1 = $2.tracingChannel;"
4360
- );
4361
- return {
4362
- code: transformedCode,
4363
- map: result.map
4364
- };
4365
- } catch (error) {
4366
- console.warn(`Code transformation failed for ${id}: ${error}`);
4367
- return null;
4368
- }
4869
+ return null;
4369
4870
  }
4370
- };
4371
- }
4372
- );
4871
+ const transformer = instrumentationMatcher.getTransformer(
4872
+ moduleName,
4873
+ moduleVersion,
4874
+ normalizedModulePath
4875
+ );
4876
+ if (!transformer) {
4877
+ return null;
4878
+ }
4879
+ try {
4880
+ const moduleType = isModule ? "esm" : "cjs";
4881
+ const result = transformer.transform(code, moduleType);
4882
+ return {
4883
+ code: result.code,
4884
+ map: result.map
4885
+ };
4886
+ } catch (error) {
4887
+ console.warn(`Code transformation failed for ${id}: ${error}`);
4888
+ return null;
4889
+ }
4890
+ }
4891
+ };
4892
+ });
4373
4893
 
4374
4894
  // src/auto-instrumentations/bundler/webpack.ts
4375
4895
  var webpackPlugin = unplugin.webpack;
@@ -4446,33 +4966,9 @@ function wrapWebpackConfig(userWebpack) {
4446
4966
  }
4447
4967
  function wrapTurbopackConfig(turbopackConfig) {
4448
4968
  const config = { ...turbopackConfig ?? {} };
4449
- const resolveAlias = config.resolveAlias && typeof config.resolveAlias === "object" && !Array.isArray(config.resolveAlias) ? config.resolveAlias : {};
4450
4969
  const rules = config.rules && typeof config.rules === "object" && !Array.isArray(config.rules) ? config.rules : {};
4451
- let dcBrowserPath;
4452
- try {
4453
- dcBrowserPath = (0, import_node_module.createRequire)(
4454
- requireFromProject.resolve("braintrust/package.json")
4455
- ).resolve("dc-browser");
4456
- } catch {
4457
- try {
4458
- dcBrowserPath = requireFromProject.resolve("dc-browser");
4459
- } catch {
4460
- dcBrowserPath = void 0;
4461
- }
4462
- }
4463
- if (dcBrowserPath && (0, import_node_path.isAbsolute)(dcBrowserPath)) {
4464
- const relativeDcBrowserPath = (0, import_node_path.relative)(
4465
- process.cwd(),
4466
- dcBrowserPath
4467
- ).replace(/\\/g, "/");
4468
- dcBrowserPath = relativeDcBrowserPath.startsWith(".") ? relativeDcBrowserPath : `./${relativeDcBrowserPath}`;
4469
- }
4470
4970
  return {
4471
4971
  ...config,
4472
- // Turbopack resolves modules emitted by our loader from the app graph. The
4473
- // browser diagnostics-channel shim is Braintrust's dependency, so alias it
4474
- // to the copy installed with Braintrust while still letting user aliases win.
4475
- resolveAlias: dcBrowserPath && resolveAlias["dc-browser"] === void 0 ? { ...resolveAlias, "dc-browser": dcBrowserPath } : config.resolveAlias,
4476
4972
  rules: addBraintrustTurbopackRule(rules)
4477
4973
  };
4478
4974
  }