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