braintrust 3.25.0 → 3.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/NOTICE +6 -0
  2. package/dev/dist/index.d.mts +130 -2
  3. package/dev/dist/index.d.ts +130 -2
  4. package/dev/dist/index.js +4133 -1421
  5. package/dev/dist/index.mjs +3242 -530
  6. package/dist/apply-auto-instrumentation.js +526 -426
  7. package/dist/apply-auto-instrumentation.mjs +329 -229
  8. package/dist/auto-instrumentations/bundler/esbuild.cjs +1198 -364
  9. package/dist/auto-instrumentations/bundler/esbuild.d.mts +4 -4
  10. package/dist/auto-instrumentations/bundler/esbuild.d.ts +4 -4
  11. package/dist/auto-instrumentations/bundler/esbuild.mjs +6 -8
  12. package/dist/auto-instrumentations/bundler/next.cjs +1227 -413
  13. package/dist/auto-instrumentations/bundler/next.mjs +7 -29
  14. package/dist/auto-instrumentations/bundler/rollup.cjs +1198 -364
  15. package/dist/auto-instrumentations/bundler/rollup.d.mts +4 -4
  16. package/dist/auto-instrumentations/bundler/rollup.d.ts +4 -4
  17. package/dist/auto-instrumentations/bundler/rollup.mjs +6 -8
  18. package/dist/auto-instrumentations/bundler/vite.cjs +1249 -387
  19. package/dist/auto-instrumentations/bundler/vite.d.mts +4 -4
  20. package/dist/auto-instrumentations/bundler/vite.d.ts +4 -4
  21. package/dist/auto-instrumentations/bundler/vite.mjs +34 -8
  22. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1368 -324
  23. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +20 -12
  24. package/dist/auto-instrumentations/bundler/webpack.cjs +1198 -364
  25. package/dist/auto-instrumentations/bundler/webpack.d.mts +4 -4
  26. package/dist/auto-instrumentations/bundler/webpack.d.ts +4 -4
  27. package/dist/auto-instrumentations/bundler/webpack.mjs +6 -4
  28. package/dist/auto-instrumentations/chunk-2AMDGD65.mjs +1396 -0
  29. package/dist/auto-instrumentations/{chunk-7P6563SW.mjs → chunk-BW33ULMW.mjs} +2 -6
  30. package/dist/auto-instrumentations/{chunk-M6DLIJ2Z.mjs → chunk-I55G56ZL.mjs} +114 -221
  31. package/dist/auto-instrumentations/chunk-JPUFNW7X.mjs +649 -0
  32. package/dist/auto-instrumentations/{chunk-JPVCUKTY.mjs → chunk-XEYKUBLY.mjs} +191 -73
  33. package/dist/auto-instrumentations/{chunk-CZ24KNHT.mjs → chunk-ZNHTSSGI.mjs} +231 -69
  34. package/dist/auto-instrumentations/hook.mjs +406 -183
  35. package/dist/auto-instrumentations/index.cjs +853 -49
  36. package/dist/auto-instrumentations/index.d.mts +10 -2
  37. package/dist/auto-instrumentations/index.d.ts +10 -2
  38. package/dist/auto-instrumentations/index.mjs +10 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +566 -221
  40. package/dist/auto-instrumentations/loader/cjs-patch.d.mts +2 -2
  41. package/dist/auto-instrumentations/loader/cjs-patch.d.ts +2 -2
  42. package/dist/auto-instrumentations/loader/cjs-patch.mjs +3 -2
  43. package/dist/auto-instrumentations/loader/esm-hook.mjs +1 -1
  44. package/dist/auto-instrumentations/plugin-B-aZh7EP.d.ts +30 -0
  45. package/dist/auto-instrumentations/plugin-Bnj4E_6B.d.mts +30 -0
  46. package/dist/auto-instrumentations/{types-RNPaKi9o.d.mts → types-C1fVeiCp.d.mts} +1 -1
  47. package/dist/auto-instrumentations/{types-RNPaKi9o.d.ts → types-C1fVeiCp.d.ts} +1 -1
  48. package/dist/browser.d.mts +871 -199
  49. package/dist/browser.d.ts +871 -199
  50. package/dist/browser.js +3737 -549
  51. package/dist/browser.mjs +3737 -549
  52. package/dist/{chunk-ABR2QWDP.mjs → chunk-CZM5JIQL.mjs} +788 -132
  53. package/dist/{chunk-P25IOOU4.js → chunk-MF7NU6BT.js} +795 -139
  54. package/dist/{chunk-GSIDVFE6.js → chunk-QRHGVBKU.js} +3580 -1463
  55. package/dist/{chunk-2SANLSWX.mjs → chunk-YKD22IMR.mjs} +2505 -388
  56. package/dist/cli.js +3244 -533
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +3737 -552
  60. package/dist/edge-light.mjs +3737 -552
  61. package/dist/index.d.mts +871 -199
  62. package/dist/index.d.ts +871 -199
  63. package/dist/index.js +893 -446
  64. package/dist/index.mjs +463 -16
  65. package/dist/instrumentation/index.d.mts +138 -6
  66. package/dist/instrumentation/index.d.ts +138 -6
  67. package/dist/instrumentation/index.js +3362 -559
  68. package/dist/instrumentation/index.mjs +3362 -559
  69. package/dist/vitest-evals-reporter.js +45 -43
  70. package/dist/vitest-evals-reporter.mjs +5 -3
  71. package/dist/workerd.d.mts +1 -1
  72. package/dist/workerd.d.ts +1 -1
  73. package/dist/workerd.js +3737 -552
  74. package/dist/workerd.mjs +3737 -552
  75. package/licenses/node-diagnostics-channel/LICENSE +19 -0
  76. package/package.json +34 -35
  77. package/dist/auto-instrumentations/chunk-VT6DDNKM.mjs +0 -856
  78. package/dist/auto-instrumentations/plugin-D0KHwSJv.d.mts +0 -44
  79. package/dist/auto-instrumentations/plugin-G6fgxk1b.d.ts +0 -44
@@ -34,7 +34,7 @@ __export(next_exports, {
34
34
  });
35
35
  module.exports = __toCommonJS(next_exports);
36
36
  var import_node_module = require("module");
37
- var import_node_path = require("path");
37
+ var import_node_path2 = require("path");
38
38
 
39
39
  // src/auto-instrumentations/bundler/plugin.ts
40
40
  var import_unplugin = require("unplugin");
@@ -51,52 +51,720 @@ 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 GLOBAL_INVOCATION_HOOK_BRAND = "braintrust.global-instrumentation-hooks.invocation-hook";
61
+ var registryBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND);
62
+ var hookBrand = Symbol.for(GLOBAL_INSTRUMENTATION_HOOK_BRAND);
63
+ var invocationHookBrand = Symbol.for(GLOBAL_INVOCATION_HOOK_BRAND);
64
+ var errorReporter;
65
+ function reportError(error) {
66
+ try {
67
+ errorReporter?.(error);
68
+ } catch {
69
+ }
58
70
  }
59
- var transforms = {
60
- tracingChannelImport({ dcModule, moduleType }, node) {
61
- if (node.body.some(tracingChannelPredicate)) {
62
- return;
71
+ function setContextValue(context, key, value) {
72
+ try {
73
+ context[key] = value;
74
+ } catch (error) {
75
+ reportError(error);
76
+ }
77
+ }
78
+ function wrapStoreRun(store, message, next, transform) {
79
+ return () => {
80
+ let context;
81
+ try {
82
+ context = transform ? transform(message) : message;
83
+ } catch (error) {
84
+ reportError(error);
85
+ return next();
86
+ }
87
+ let called = false;
88
+ let result;
89
+ let providerError;
90
+ let providerThrew = false;
91
+ const runNext = () => {
92
+ if (called) {
93
+ reportError(
94
+ new Error(
95
+ "Instrumentation store invoked its callback more than once"
96
+ )
97
+ );
98
+ if (providerThrew) {
99
+ throw providerError;
100
+ }
101
+ return result;
102
+ }
103
+ called = true;
104
+ try {
105
+ result = next();
106
+ return result;
107
+ } catch (error) {
108
+ providerThrew = true;
109
+ providerError = error;
110
+ throw error;
111
+ }
112
+ };
113
+ try {
114
+ store.run(context, runNext);
115
+ } catch (error) {
116
+ if (!providerThrew || error !== providerError) {
117
+ reportError(error);
118
+ }
63
119
  }
64
- const options = { module: moduleType === "esm" };
65
- const index = node.body.findIndex(
66
- (child) => child.directive === "use strict"
120
+ if (!called) {
121
+ reportError(
122
+ new Error("Instrumentation store did not invoke its callback")
123
+ );
124
+ return runNext();
125
+ }
126
+ if (providerThrew) {
127
+ throw providerError;
128
+ }
129
+ return result;
130
+ };
131
+ }
132
+ var HookChannel = class {
133
+ constructor(name) {
134
+ this.name = name;
135
+ }
136
+ name;
137
+ subscribers = [];
138
+ stores = /* @__PURE__ */ new Map();
139
+ get hasSubscribers() {
140
+ return this.subscribers.length > 0 || this.stores.size > 0;
141
+ }
142
+ subscribe(subscription) {
143
+ if (typeof subscription !== "function") {
144
+ throw new TypeError("subscription must be a function");
145
+ }
146
+ this.subscribers = [...this.subscribers, subscription];
147
+ }
148
+ unsubscribe(subscription) {
149
+ const index = this.subscribers.indexOf(subscription);
150
+ if (index === -1) {
151
+ return false;
152
+ }
153
+ this.subscribers = [
154
+ ...this.subscribers.slice(0, index),
155
+ ...this.subscribers.slice(index + 1)
156
+ ];
157
+ return true;
158
+ }
159
+ bindStore(store, transform) {
160
+ if (!store || typeof store.run !== "function") {
161
+ throw new TypeError("store must have a run method");
162
+ }
163
+ this.stores.set(
164
+ store,
165
+ transform
67
166
  );
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]
167
+ }
168
+ unbindStore(store) {
169
+ return this.stores.delete(store);
170
+ }
171
+ publish(message) {
172
+ const subscribers = this.subscribers;
173
+ for (const subscriber of subscribers) {
174
+ try {
175
+ subscriber(message, this.name);
176
+ } catch (error) {
177
+ reportError(error);
178
+ }
179
+ }
180
+ }
181
+ runStores(message, fn, thisArg, ...args) {
182
+ let run = () => {
183
+ this.publish(message);
184
+ return Reflect.apply(fn, thisArg, args);
185
+ };
186
+ for (const [store, transform] of this.stores.entries()) {
187
+ run = wrapStoreRun(store, message, run, transform);
188
+ }
189
+ return run();
190
+ }
191
+ };
192
+ var traceEvents = [
193
+ "start",
194
+ "end",
195
+ "asyncStart",
196
+ "asyncEnd",
197
+ "error"
198
+ ];
199
+ function traceInvocation(hook, operator, target, thisArg, args, additional, callbackIndex = -1) {
200
+ const context = {
201
+ ...additional,
202
+ arguments: args,
203
+ self: thisArg
204
+ };
205
+ const invoke = () => hook.invoke(target, thisArg, args, additional);
206
+ if (operator === "traceCallback") {
207
+ return hook.traceCallback(invoke, callbackIndex, context);
208
+ }
209
+ if (operator === "tracePromise") {
210
+ return hook.tracePromise(invoke, context);
211
+ }
212
+ return hook.traceSync(invoke, context);
213
+ }
214
+ var InvocationHook = class {
215
+ interceptors = [];
216
+ get hasInterceptors() {
217
+ return this.interceptors.length > 0;
218
+ }
219
+ intercept(interceptor) {
220
+ if (typeof interceptor !== "function") {
221
+ throw new TypeError("interceptor must be a function");
222
+ }
223
+ this.interceptors = [...this.interceptors, interceptor];
224
+ let active = true;
225
+ return () => {
226
+ if (!active) {
227
+ return;
228
+ }
229
+ active = false;
230
+ const index = this.interceptors.indexOf(interceptor);
231
+ if (index !== -1) {
232
+ this.interceptors = [
233
+ ...this.interceptors.slice(0, index),
234
+ ...this.interceptors.slice(index + 1)
235
+ ];
236
+ }
237
+ };
238
+ }
239
+ invoke(target, thisArg, args, additional) {
240
+ const interceptors = this.interceptors;
241
+ if (interceptors.length === 0) {
242
+ return Reflect.apply(target, thisArg, args);
243
+ }
244
+ let next = target;
245
+ for (let index = interceptors.length - 1; index >= 0; index -= 1) {
246
+ const interceptor = interceptors[index];
247
+ const downstream = next;
248
+ next = function(...nextArgs) {
249
+ return interceptor(downstream, this, nextArgs, additional);
250
+ };
251
+ }
252
+ return Reflect.apply(next, thisArg, args);
253
+ }
254
+ };
255
+ var TracingHook = class {
256
+ start;
257
+ end;
258
+ asyncStart;
259
+ asyncEnd;
260
+ error;
261
+ invocationHook = new InvocationHook();
262
+ constructor(nameOrChannels) {
263
+ Object.defineProperty(this, hookBrand, {
264
+ configurable: false,
265
+ enumerable: false,
266
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
267
+ writable: false
268
+ });
269
+ Object.defineProperty(this, invocationHookBrand, {
270
+ configurable: false,
271
+ enumerable: false,
272
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
273
+ writable: false
274
+ });
275
+ if (typeof nameOrChannels === "string") {
276
+ this.start = new HookChannel(`tracing:${nameOrChannels}:start`);
277
+ this.end = new HookChannel(`tracing:${nameOrChannels}:end`);
278
+ this.asyncStart = new HookChannel(`tracing:${nameOrChannels}:asyncStart`);
279
+ this.asyncEnd = new HookChannel(`tracing:${nameOrChannels}:asyncEnd`);
280
+ this.error = new HookChannel(`tracing:${nameOrChannels}:error`);
281
+ return;
282
+ }
283
+ this.start = nameOrChannels.start ?? new HookChannel("tracing:start");
284
+ this.end = nameOrChannels.end ?? new HookChannel("tracing:end");
285
+ this.asyncStart = nameOrChannels.asyncStart ?? new HookChannel("tracing:asyncStart");
286
+ this.asyncEnd = nameOrChannels.asyncEnd ?? new HookChannel("tracing:asyncEnd");
287
+ this.error = nameOrChannels.error ?? new HookChannel("tracing:error");
288
+ }
289
+ get hasSubscribers() {
290
+ return this.start.hasSubscribers || this.end.hasSubscribers || this.asyncStart.hasSubscribers || this.asyncEnd.hasSubscribers || this.error.hasSubscribers;
291
+ }
292
+ get hasInterceptors() {
293
+ return this.invocationHook.hasInterceptors;
294
+ }
295
+ intercept(interceptor) {
296
+ return this.invocationHook.intercept(interceptor);
297
+ }
298
+ invoke(target, thisArg, args, additional) {
299
+ return this.invocationHook.invoke(target, thisArg, args, additional);
300
+ }
301
+ traceInvocation(operator, target, thisArg, args, additional, callbackIndex = -1) {
302
+ return traceInvocation(
303
+ this,
304
+ operator,
305
+ target,
306
+ thisArg,
307
+ args,
308
+ additional,
309
+ callbackIndex
81
310
  );
311
+ }
312
+ subscribe(handlers) {
313
+ for (const eventName of traceEvents) {
314
+ const handler = handlers[eventName];
315
+ if (handler) {
316
+ this[eventName].subscribe(handler);
317
+ }
318
+ }
319
+ }
320
+ unsubscribe(handlers) {
321
+ let done = true;
322
+ for (const eventName of traceEvents) {
323
+ const handler = handlers[eventName];
324
+ if (handler && !this[eventName].unsubscribe(handler)) {
325
+ done = false;
326
+ }
327
+ }
328
+ return done;
329
+ }
330
+ traceSync(fn, message = {}, thisArg, ...args) {
331
+ if (!this.hasSubscribers) {
332
+ return Reflect.apply(fn, thisArg, args);
333
+ }
334
+ const context = message;
335
+ return this.start.runStores(message, () => {
336
+ try {
337
+ const result = Reflect.apply(fn, thisArg, args);
338
+ setContextValue(context, "result", result);
339
+ return result;
340
+ } catch (error) {
341
+ setContextValue(context, "error", error);
342
+ this.error.publish(message);
343
+ throw error;
344
+ } finally {
345
+ this.end.publish(message);
346
+ }
347
+ });
348
+ }
349
+ tracePromise(fn, message = {}, thisArg, ...args) {
350
+ if (!this.hasSubscribers) {
351
+ return Reflect.apply(fn, thisArg, args);
352
+ }
353
+ const context = message;
354
+ return this.start.runStores(message, () => {
355
+ let result;
356
+ try {
357
+ result = Reflect.apply(fn, thisArg, args);
358
+ } catch (error) {
359
+ setContextValue(context, "error", error);
360
+ this.error.publish(message);
361
+ this.end.publish(message);
362
+ throw error;
363
+ }
364
+ this.end.publish(message);
365
+ if (!result || typeof result !== "object" && typeof result !== "function") {
366
+ setContextValue(context, "result", result);
367
+ this.asyncStart.publish(message);
368
+ this.asyncEnd.publish(message);
369
+ return result;
370
+ }
371
+ let terminalPublished = false;
372
+ const finishUnobservedResult = (error) => {
373
+ reportError(error);
374
+ if (!terminalPublished) {
375
+ terminalPublished = true;
376
+ setContextValue(context, "result", result);
377
+ this.asyncStart.publish(message);
378
+ this.asyncEnd.publish(message);
379
+ }
380
+ return result;
381
+ };
382
+ let then;
383
+ try {
384
+ then = result.then;
385
+ } catch (error) {
386
+ return finishUnobservedResult(error);
387
+ }
388
+ if (typeof then !== "function") {
389
+ setContextValue(context, "result", result);
390
+ this.asyncStart.publish(message);
391
+ this.asyncEnd.publish(message);
392
+ return result;
393
+ }
394
+ const resolve = (resolved) => {
395
+ if (!terminalPublished) {
396
+ terminalPublished = true;
397
+ setContextValue(context, "result", resolved);
398
+ this.asyncStart.publish(message);
399
+ this.asyncEnd.publish(message);
400
+ }
401
+ return resolved;
402
+ };
403
+ let rejectionThrown = false;
404
+ let rejectionError;
405
+ const reject = (error) => {
406
+ if (!terminalPublished) {
407
+ terminalPublished = true;
408
+ setContextValue(context, "error", error);
409
+ this.error.publish(message);
410
+ this.asyncStart.publish(message);
411
+ this.asyncEnd.publish(message);
412
+ }
413
+ rejectionThrown = true;
414
+ rejectionError = error;
415
+ throw error;
416
+ };
417
+ let isPlainPromise;
418
+ try {
419
+ isPlainPromise = result instanceof Promise && result.constructor === Promise;
420
+ } catch (error) {
421
+ return finishUnobservedResult(error);
422
+ }
423
+ try {
424
+ if (isPlainPromise) {
425
+ return Reflect.apply(then, result, [resolve, reject]);
426
+ }
427
+ Reflect.apply(then, result, [
428
+ resolve,
429
+ (error) => {
430
+ try {
431
+ reject(error);
432
+ } catch {
433
+ }
434
+ }
435
+ ]);
436
+ } catch (error) {
437
+ if (rejectionThrown && error === rejectionError) {
438
+ return result;
439
+ }
440
+ return finishUnobservedResult(error);
441
+ }
442
+ return result;
443
+ });
444
+ }
445
+ traceCallback(fn, position = -1, message = {}, thisArg, ...args) {
446
+ if (!this.hasSubscribers) {
447
+ return Reflect.apply(fn, thisArg, args);
448
+ }
449
+ const context = message;
450
+ const callArgs = args.length > 0 ? args : context.arguments ?? args;
451
+ const callback = Array.prototype.at.call(callArgs, position);
452
+ if (typeof callback !== "function") {
453
+ return Reflect.apply(fn, thisArg, args);
454
+ }
455
+ const { asyncStart, asyncEnd, error: errorChannel } = this;
456
+ function wrappedCallback(error, result) {
457
+ if (error) {
458
+ setContextValue(context, "error", error);
459
+ errorChannel.publish(message);
460
+ } else {
461
+ setContextValue(context, "result", result);
462
+ }
463
+ return asyncStart.runStores(message, () => {
464
+ try {
465
+ return Reflect.apply(callback, this, arguments);
466
+ } finally {
467
+ asyncEnd.publish(message);
468
+ }
469
+ });
470
+ }
471
+ Array.prototype.splice.call(callArgs, position, 1, wrappedCallback);
472
+ return this.start.runStores(message, () => {
473
+ try {
474
+ return Reflect.apply(fn, thisArg, args);
475
+ } catch (error) {
476
+ setContextValue(context, "error", error);
477
+ this.error.publish(message);
478
+ throw error;
479
+ } finally {
480
+ this.end.publish(message);
481
+ }
482
+ });
483
+ }
484
+ };
485
+ var inertChannel = Object.freeze({
486
+ name: "braintrust:inert",
487
+ hasSubscribers: false,
488
+ subscribe() {
489
+ },
490
+ unsubscribe() {
491
+ return false;
492
+ },
493
+ bindStore() {
82
494
  },
83
- tracingChannelDeclaration(state, node) {
495
+ unbindStore() {
496
+ return false;
497
+ },
498
+ publish() {
499
+ },
500
+ runStores(_message, fn, thisArg, ...args) {
501
+ return Reflect.apply(fn, thisArg, args);
502
+ }
503
+ });
504
+ var inertTracingHook = new TracingHook({
505
+ start: inertChannel,
506
+ end: inertChannel,
507
+ asyncStart: inertChannel,
508
+ asyncEnd: inertChannel,
509
+ error: inertChannel
510
+ });
511
+ function isHookChannel(value) {
512
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
513
+ return false;
514
+ }
515
+ try {
516
+ const channel2 = value;
517
+ 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";
518
+ } catch {
519
+ return false;
520
+ }
521
+ }
522
+ function hasTracingHookShape(value) {
523
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
524
+ return false;
525
+ }
526
+ try {
527
+ const hook = value;
528
+ 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);
529
+ } catch {
530
+ return false;
531
+ }
532
+ }
533
+ function hasInvocationHookShape(value) {
534
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
535
+ return false;
536
+ }
537
+ try {
538
+ const hook = value;
539
+ return value[invocationHookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && typeof hook.hasInterceptors === "boolean" && typeof hook.intercept === "function" && typeof hook.invoke === "function";
540
+ } catch {
541
+ return false;
542
+ }
543
+ }
544
+ function installInvocationHook(value) {
545
+ const hasInvocationHook = hasInvocationHookShape(value);
546
+ const invocationHook = new InvocationHook();
547
+ try {
548
+ if (!hasInvocationHook) {
549
+ Object.defineProperties(value, {
550
+ [invocationHookBrand]: {
551
+ configurable: false,
552
+ enumerable: false,
553
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
554
+ writable: false
555
+ },
556
+ hasInterceptors: {
557
+ configurable: false,
558
+ enumerable: false,
559
+ get: () => invocationHook.hasInterceptors
560
+ },
561
+ intercept: {
562
+ configurable: false,
563
+ enumerable: false,
564
+ value: invocationHook.intercept.bind(invocationHook),
565
+ writable: false
566
+ },
567
+ invoke: {
568
+ configurable: false,
569
+ enumerable: false,
570
+ value: invocationHook.invoke.bind(invocationHook),
571
+ writable: false
572
+ }
573
+ });
574
+ }
575
+ if (typeof value.traceInvocation !== "function") {
576
+ Object.defineProperty(value, "traceInvocation", {
577
+ configurable: false,
578
+ enumerable: false,
579
+ value: traceInvocation.bind(void 0, value),
580
+ writable: false
581
+ });
582
+ }
583
+ } catch (error) {
584
+ reportError(error);
585
+ }
586
+ }
587
+ function isCompatibleTracingHook(value) {
588
+ try {
589
+ return value[hookBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION && hasTracingHookShape(value);
590
+ } catch {
591
+ return false;
592
+ }
593
+ }
594
+ function isCompatibleHookRegistry(value) {
595
+ try {
596
+ return value instanceof Map && value[registryBrand] === GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION;
597
+ } catch {
598
+ return false;
599
+ }
600
+ }
601
+ function getHookRegistry() {
602
+ let descriptor;
603
+ try {
604
+ descriptor = Object.getOwnPropertyDescriptor(
605
+ globalThis,
606
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
607
+ );
608
+ } catch (error) {
609
+ reportError(error);
610
+ return void 0;
611
+ }
612
+ if (descriptor && "value" in descriptor && isCompatibleHookRegistry(descriptor.value) && (descriptor.configurable || descriptor.enumerable === false)) {
613
+ if (descriptor.configurable || descriptor.writable) {
614
+ try {
615
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
616
+ configurable: false,
617
+ enumerable: false,
618
+ value: descriptor.value,
619
+ writable: false
620
+ });
621
+ } catch (error) {
622
+ reportError(error);
623
+ return void 0;
624
+ }
625
+ }
626
+ return descriptor.value;
627
+ }
628
+ if (descriptor && !descriptor.configurable) {
629
+ reportError(new Error("Incompatible global instrumentation hook registry"));
630
+ return void 0;
631
+ }
632
+ const registry = /* @__PURE__ */ new Map();
633
+ try {
634
+ Object.defineProperty(registry, registryBrand, {
635
+ configurable: false,
636
+ enumerable: false,
637
+ value: GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION,
638
+ writable: false
639
+ });
640
+ } catch (error) {
641
+ reportError(error);
642
+ return void 0;
643
+ }
644
+ try {
645
+ Object.defineProperty(globalThis, GLOBAL_INSTRUMENTATION_HOOKS_KEY, {
646
+ configurable: false,
647
+ enumerable: false,
648
+ value: registry,
649
+ writable: false
650
+ });
651
+ return registry;
652
+ } catch (error) {
653
+ reportError(error);
654
+ return void 0;
655
+ }
656
+ }
657
+ function newGlobalTracingChannel(nameOrChannels) {
658
+ if (typeof nameOrChannels !== "string") {
659
+ return new TracingHook(nameOrChannels);
660
+ }
661
+ const registry = getHookRegistry();
662
+ if (!registry) {
663
+ return inertTracingHook;
664
+ }
665
+ let existing;
666
+ try {
667
+ existing = Map.prototype.get.call(registry, nameOrChannels);
668
+ } catch (error) {
669
+ reportError(error);
670
+ return inertTracingHook;
671
+ }
672
+ if (isCompatibleTracingHook(existing)) {
673
+ installInvocationHook(existing);
674
+ return existing;
675
+ }
676
+ if (existing !== void 0) {
677
+ reportError(
678
+ new Error(`Invalid global instrumentation hook: ${nameOrChannels}`)
679
+ );
680
+ try {
681
+ Map.prototype.delete.call(registry, nameOrChannels);
682
+ } catch (error) {
683
+ reportError(error);
684
+ return inertTracingHook;
685
+ }
686
+ }
687
+ const hook = new TracingHook(nameOrChannels);
688
+ try {
689
+ Map.prototype.set.call(registry, nameOrChannels, hook);
690
+ } catch (error) {
691
+ reportError(error);
692
+ return inertTracingHook;
693
+ }
694
+ return hook;
695
+ }
696
+
697
+ // src/auto-instrumentations/orchestrion-js/transforms.ts
698
+ var CHANNEL_REGEX = /[^\w]/g;
699
+ var SHARED_HOOK_LOOKUP = "tr_ch_bt$get_hook";
700
+ function formatChannelVariable(channelName) {
701
+ return `tr_ch_bt$${channelName.replace(CHANNEL_REGEX, "_")}`;
702
+ }
703
+ function formatChannelGetter(channelName) {
704
+ return `tr_ch_bt$get_${channelName.replace(CHANNEL_REGEX, "_")}`;
705
+ }
706
+ var transforms = {
707
+ tracingHookDeclaration(state, node) {
84
708
  const {
85
709
  channelName,
86
710
  module: { name }
87
711
  } = state;
88
712
  const channelVariable = formatChannelVariable(channelName);
713
+ const channelGetter = formatChannelGetter(channelName);
714
+ const hasSharedHookLookup = node.body.some(
715
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
716
+ );
89
717
  if (node.body.some(
90
- (child) => child.declarations?.[0]?.id?.name === channelVariable
718
+ (child) => child.declarations?.[0]?.id?.name === channelGetter
91
719
  )) {
92
720
  return;
93
721
  }
94
- transforms.tracingChannelImport(state, node, null, []);
95
- const index = node.body.findIndex(tracingChannelPredicate);
722
+ const sharedHookLookup = hasSharedHookLookup ? "" : `
723
+ const ${SHARED_HOOK_LOOKUP} = (__bt$hookName) => {
724
+ try {
725
+ const __bt$hooks = globalThis[${JSON.stringify(
726
+ GLOBAL_INSTRUMENTATION_HOOKS_KEY
727
+ )}];
728
+ if (
729
+ !(__bt$hooks instanceof Map) ||
730
+ __bt$hooks[Symbol.for(${JSON.stringify(
731
+ GLOBAL_INSTRUMENTATION_HOOKS_REGISTRY_BRAND
732
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION}
733
+ ) return undefined;
734
+ const __bt$hook = Map.prototype.get.call(
735
+ __bt$hooks,
736
+ __bt$hookName
737
+ );
738
+ if (
739
+ (__bt$hook === null ||
740
+ (typeof __bt$hook !== "object" &&
741
+ typeof __bt$hook !== "function")) ||
742
+ __bt$hook[Symbol.for(${JSON.stringify(
743
+ GLOBAL_INSTRUMENTATION_HOOK_BRAND
744
+ )})] !== ${GLOBAL_INSTRUMENTATION_HOOKS_PROTOCOL_VERSION} ||
745
+ typeof __bt$hook.traceInvocation !== "function"
746
+ ) return undefined;
747
+ return __bt$hook;
748
+ } catch {
749
+ return undefined;
750
+ }
751
+ };
752
+ `;
96
753
  const code = `
97
- const ${channelVariable} = tr_ch_apm_tracingChannel("orchestrion:${name}:${channelName}")
754
+ ${sharedHookLookup}
755
+ let ${channelVariable};
756
+ const ${channelGetter} = () =>
757
+ ${channelVariable} ??= ${SHARED_HOOK_LOOKUP}(
758
+ ${JSON.stringify(`orchestrion:${name}:${channelName}`)}
759
+ );
98
760
  `;
99
- node.body.splice(index + 1, 0, (0, import_meriyah.parse)(code).body[0]);
761
+ const sharedHookLookupIndex = node.body.findIndex(
762
+ (child) => child.declarations?.[0]?.id?.name === SHARED_HOOK_LOOKUP
763
+ );
764
+ const index = sharedHookLookupIndex === -1 ? node.body.findIndex(
765
+ (child) => child.directive === "use strict"
766
+ ) : sharedHookLookupIndex;
767
+ node.body.splice(index + 1, 0, ...(0, import_meriyah.parse)(code).body);
100
768
  },
101
769
  traceCallback: traceAny,
102
770
  tracePromise: traceAny,
@@ -111,25 +779,21 @@ function traceAny(state, node, _parent, ancestry) {
111
779
  }
112
780
  }
113
781
  function traceFunction(state, node, program) {
114
- transforms.tracingChannelDeclaration(state, program, null, []);
782
+ transforms.tracingHookDeclaration(state, program, null, []);
115
783
  const { functionQuery } = state;
116
784
  const methodName = "methodName" in functionQuery ? functionQuery.methodName : void 0;
117
785
  const privateMethodName = "privateMethodName" in functionQuery ? functionQuery.privateMethodName : void 0;
118
786
  const functionName = "functionName" in functionQuery ? functionQuery.functionName : void 0;
119
787
  const isConstructor = methodName === "constructor" || !methodName && !privateMethodName && !functionName;
120
788
  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
- );
789
+ node.body = wrap(state, {
790
+ type,
791
+ params: node.params,
792
+ body: node.body,
793
+ async: node.async,
794
+ expression: false,
795
+ generator: node.generator
796
+ });
133
797
  node.generator = false;
134
798
  node.async = false;
135
799
  wrapSuper(node);
@@ -141,11 +805,11 @@ function traceInstanceMethod(state, node, program) {
141
805
  return;
142
806
  }
143
807
  const classBody = node.body;
144
- if (classBody.body.some(({ key }) => key.name === methodName)) {
808
+ if (classBody.body.some(({ key }) => key?.name === methodName)) {
145
809
  return;
146
810
  }
147
811
  let ctor = classBody.body.find(({ kind }) => kind === "constructor");
148
- transforms.tracingChannelDeclaration(state, program, null, []);
812
+ transforms.tracingHookDeclaration(state, program, null, []);
149
813
  if (!ctor) {
150
814
  ctor = (0, import_meriyah.parse)(
151
815
  node.superClass ? "class A extends Object { constructor (...args) { super(...args) } }" : "class A { constructor () {} }"
@@ -153,47 +817,36 @@ function traceInstanceMethod(state, node, program) {
153
817
  classBody.body.unshift(ctor);
154
818
  }
155
819
  const ctorBody = (0, import_meriyah.parse)(`
156
- const __apm$${methodName} = this["${methodName}"]
820
+ const __bt$${methodName} = this["${methodName}"]
157
821
  this["${methodName}"] = function () {}
158
822
  `).body;
159
823
  const fn = ctorBody[1].expression.right;
160
824
  fn.async = operator === "tracePromise";
161
- fn.body = wrap(
162
- state,
163
- { type: "Identifier", name: `__apm$${methodName}` },
164
- program
165
- );
825
+ fn.body = wrap(state, {
826
+ type: "Identifier",
827
+ name: `__bt$${methodName}`
828
+ });
166
829
  wrapSuper(fn);
167
830
  ctor.value.body.body.push(...ctorBody);
168
831
  }
169
- function wrap(state, node, program) {
170
- const { operator, moduleVersion } = state;
171
- const wrapper = operator === "traceCallback" ? wrapCallback(state) : operator === "tracePromise" ? wrapPromise(state) : wrapSync(state);
832
+ function wrap(state, node) {
833
+ const wrapper = wrapInvocation(state);
172
834
  const block = wrapper.body[0].body;
173
835
  const common = (0, import_meriyah.parse)(
174
836
  node.type === "ArrowFunctionExpression" ? `
175
- const __apm$ctx = {
176
- arguments,
177
- moduleVersion: ${JSON.stringify(moduleVersion)}
178
- };
179
- const __apm$traced = () => {
180
- const __apm$wrapped = () => {};
181
- return __apm$wrapped(...arguments);
837
+ const __bt$target = (...__bt$args) => {
838
+ const __bt$wrapped = () => {};
839
+ return __bt$wrapped(...__bt$args);
182
840
  };
183
841
  ` : `
184
- const __apm$ctx = {
185
- arguments,
186
- self: this,
187
- moduleVersion: ${JSON.stringify(moduleVersion)}
188
- };
189
- const __apm$traced = () => {
190
- const __apm$wrapped = () => {};
191
- return __apm$wrapped.apply(this, arguments);
842
+ const __bt$target = function (...__bt$args) {
843
+ const __bt$wrapped = () => {};
844
+ return __bt$wrapped.apply(this, __bt$args);
192
845
  };
193
846
  `
194
847
  ).body;
195
848
  block.body.unshift(...common);
196
- import_esquery.default.query(block, "[id.name=__apm$wrapped]")[0].init = node;
849
+ import_esquery.default.query(block, "[id.name=__bt$wrapped]")[0].init = node;
197
850
  return block;
198
851
  }
199
852
  function wrapSuper(node) {
@@ -205,11 +858,11 @@ function wrapSuper(node) {
205
858
  const { name } = node2.property;
206
859
  let child;
207
860
  if (parent.callee) {
208
- const { expression } = (0, import_meriyah.parse)(`__apm$super['${name}'].call(this)`).body[0];
861
+ const { expression } = (0, import_meriyah.parse)(`__bt$super['${name}'].call(this)`).body[0];
209
862
  parent.callee = child = expression.callee;
210
863
  parent.arguments.unshift(...expression.arguments);
211
864
  } else {
212
- parent.expression = child = (0, import_meriyah.parse)(`__apm$super['${name}']`).body[0];
865
+ parent.expression = child = (0, import_meriyah.parse)(`__bt$super['${name}']`).body[0];
213
866
  }
214
867
  child.computed = parent.callee.computed;
215
868
  child.optional = parent.callee.optional;
@@ -220,151 +873,32 @@ function wrapSuper(node) {
220
873
  const member = (0, import_meriyah.parse)(`
221
874
  class Wrapper {
222
875
  wrapper () {
223
- __apm$super['${name}'] = super['${name}']
876
+ __bt$super['${name}'] = super['${name}']
224
877
  }
225
878
  }
226
879
  `).body[0].body.body[0].value.body.body[0];
227
880
  node.body.body.unshift(member);
228
881
  }
229
882
  if (members.size > 0) {
230
- node.body.body.unshift((0, import_meriyah.parse)("const __apm$super = {}").body[0]);
883
+ node.body.body.unshift((0, import_meriyah.parse)("const __bt$super = {}").body[0]);
231
884
  }
232
885
  }
233
- function wrapCallback(state) {
234
- const {
235
- channelName,
236
- functionQuery: { callbackIndex = -1 }
237
- } = state;
238
- const channelVariable = formatChannelVariable(channelName);
239
- return (0, import_meriyah.parse)(`
240
- 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
- });
281
- }
282
- `);
283
- }
284
- function wrapPromise(state) {
285
- const { channelName } = state;
286
- const channelVariable = formatChannelVariable(channelName);
287
- return (0, import_meriyah.parse)(`
288
- 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
- });
344
- }
345
- `);
346
- }
347
- function wrapSync(state) {
348
- const { channelName } = state;
349
- const channelVariable = formatChannelVariable(channelName);
886
+ function wrapInvocation(state) {
887
+ const { channelName, moduleVersion, operator, functionQuery } = state;
888
+ const channelGetter = formatChannelGetter(channelName);
889
+ const callbackIndex = functionQuery.callbackIndex ?? -1;
350
890
  return (0, import_meriyah.parse)(`
351
891
  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
- });
892
+ const __bt$hook = ${channelGetter}();
893
+ if (!__bt$hook) return __bt$target.apply(this, arguments);
894
+ return __bt$hook.traceInvocation(
895
+ ${JSON.stringify(operator)},
896
+ __bt$target,
897
+ this,
898
+ arguments,
899
+ { moduleVersion: ${JSON.stringify(moduleVersion)} },
900
+ ${callbackIndex}
901
+ );
368
902
  }
369
903
  `);
370
904
  }
@@ -375,16 +909,14 @@ var Transformer = class {
375
909
  version;
376
910
  filePath;
377
911
  configs = [];
378
- dcModule;
379
- constructor(moduleName, version, filePath, configs, dcModule) {
912
+ constructor(moduleName, version, filePath, configs) {
380
913
  this.moduleName = moduleName;
381
914
  this.version = version;
382
915
  this.filePath = filePath;
383
916
  this.configs = configs;
384
- this.dcModule = dcModule;
385
917
  }
386
918
  /**
387
- * Instruments `code` by injecting diagnostics_channel tracing around the
919
+ * Instruments `code` by injecting global tracing hooks around the
388
920
  * target functions defined by this transformer's configs.
389
921
  */
390
922
  transform(code, moduleType) {
@@ -422,8 +954,6 @@ var Transformer = class {
422
954
  const query = astQuery || this.fromFunctionQuery(resolvedFunctionQuery);
423
955
  const state = {
424
956
  ...config,
425
- dcModule: this.dcModule,
426
- moduleType,
427
957
  moduleVersion: this.version,
428
958
  functionQuery: resolvedFunctionQuery,
429
959
  operator: this.getOperator(resolvedFunctionQuery.kind)
@@ -573,11 +1103,9 @@ var Transformer = class {
573
1103
  // src/auto-instrumentations/orchestrion-js/matcher.ts
574
1104
  var InstrumentationMatcher = class {
575
1105
  configs = [];
576
- dcModule;
577
1106
  transformers = {};
578
- constructor(configs, dcModule) {
1107
+ constructor(configs) {
579
1108
  this.configs = configs;
580
- this.dcModule = dcModule || "diagnostics_channel";
581
1109
  }
582
1110
  /**
583
1111
  * Returns a Transformer for the given module/file/version, or undefined if no
@@ -599,8 +1127,7 @@ var InstrumentationMatcher = class {
599
1127
  moduleName,
600
1128
  version,
601
1129
  filePath,
602
- configs,
603
- this.dcModule
1130
+ configs
604
1131
  );
605
1132
  return this.transformers[id];
606
1133
  }
@@ -610,8 +1137,8 @@ var InstrumentationMatcher = class {
610
1137
  };
611
1138
 
612
1139
  // src/auto-instrumentations/orchestrion-js/index.ts
613
- function create(configs, dcModule) {
614
- return new InstrumentationMatcher(configs, dcModule);
1140
+ function create(configs) {
1141
+ return new InstrumentationMatcher(configs);
615
1142
  }
616
1143
 
617
1144
  // src/auto-instrumentations/bundler/plugin.ts
@@ -637,6 +1164,9 @@ var envIntegrationAliases = {
637
1164
  strandsagentsdk: "strandsAgentSDK",
638
1165
  "strands-agent-sdk": "strandsAgentSDK",
639
1166
  "@strands-agents/sdk": "strandsAgentSDK",
1167
+ agents: "cloudflareAgents",
1168
+ "cloudflare-agents": "cloudflareAgents",
1169
+ cloudflareagents: "cloudflareAgents",
640
1170
  anthropic: "anthropic",
641
1171
  aisdk: "aisdk",
642
1172
  "ai-sdk": "aisdk",
@@ -644,6 +1174,10 @@ var envIntegrationAliases = {
644
1174
  vercel: "vercel",
645
1175
  claudeagentsdk: "claudeAgentSDK",
646
1176
  "claude-agent-sdk": "claudeAgentSDK",
1177
+ cloudflareaichat: "cloudflareAIChat",
1178
+ "cloudflare-ai-chat": "cloudflareAIChat",
1179
+ "@cloudflare/ai-chat": "cloudflareAIChat",
1180
+ cloudflarethink: "cloudflareThink",
647
1181
  cursor: "cursor",
648
1182
  "cursor-sdk": "cursorSDK",
649
1183
  cursorsdk: "cursorSDK",
@@ -658,10 +1192,13 @@ var envIntegrationAliases = {
658
1192
  "google-genai": "googleGenAI",
659
1193
  googlegenai: "googleGenAI",
660
1194
  huggingface: "huggingface",
1195
+ "@huggingface/transformers": "huggingface",
1196
+ transformers: "huggingface",
661
1197
  openrouter: "openrouter",
662
1198
  openrouteragent: "openrouterAgent",
663
1199
  "openrouter-agent": "openrouterAgent",
664
1200
  mistral: "mistral",
1201
+ ollama: "ollama",
665
1202
  googleadk: "googleADK",
666
1203
  "google-adk": "googleADK",
667
1204
  cohere: "cohere",
@@ -679,106 +1216,39 @@ var envIntegrationAliases = {
679
1216
  "github-copilot": "gitHubCopilot",
680
1217
  "copilot-sdk": "gitHubCopilot",
681
1218
  langchain: "langchain",
682
- "langchain-js": "langchain",
683
- "@langchain": "langchain",
684
- langgraph: "langgraph",
685
- langsmith: "langsmith"
686
- };
687
- function readDisabledInstrumentationEnvConfig(disabledList) {
688
- const integrations = {};
689
- if (disabledList) {
690
- for (const value of disabledList.split(",")) {
691
- const rawSdk = value.trim();
692
- const sdk = rawSdk.toLowerCase();
693
- if (sdk.length > 0) {
694
- integrations[envIntegrationAliases[rawSdk] ?? envIntegrationAliases[sdk] ?? sdk] = false;
695
- }
696
- }
697
- }
698
- return { integrations };
699
- }
700
- function isInstrumentationIntegrationDisabled(integrations, ...names) {
701
- return names.some((name) => integrations?.[name] === false);
702
- }
703
-
704
- // src/isomorph.ts
705
- var DefaultAsyncLocalStorage = class {
706
- constructor() {
707
- }
708
- enterWith(_) {
709
- }
710
- run(_, callback) {
711
- return callback();
712
- }
713
- getStore() {
714
- return void 0;
715
- }
716
- };
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;
1219
+ "langchain-js": "langchain",
1220
+ "@langchain": "langchain",
1221
+ langgraph: "langgraph",
1222
+ langsmith: "langsmith"
1223
+ };
1224
+ function readDisabledInstrumentationEnvConfig(disabledList) {
1225
+ const integrations = {};
1226
+ if (disabledList) {
1227
+ for (const value of disabledList.split(",")) {
1228
+ const rawSdk = value.trim();
1229
+ const sdk = rawSdk.toLowerCase();
1230
+ if (sdk.length > 0) {
1231
+ integrations[envIntegrationAliases[rawSdk] ?? envIntegrationAliases[sdk] ?? sdk] = false;
1232
+ }
756
1233
  }
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
1234
  }
768
- unsubscribe(_handlers) {
769
- return false;
1235
+ return { integrations };
1236
+ }
1237
+ function isInstrumentationIntegrationDisabled(integrations, ...names) {
1238
+ return names.some((name) => integrations?.[name] === false);
1239
+ }
1240
+
1241
+ // src/isomorph.ts
1242
+ var DefaultAsyncLocalStorage = class {
1243
+ constructor() {
770
1244
  }
771
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
772
- traceSync(fn, _message, thisArg, ...args) {
773
- return fn.apply(thisArg, args);
1245
+ enterWith(_) {
774
1246
  }
775
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
776
- tracePromise(fn, _message, thisArg, ...args) {
777
- return fn.apply(thisArg, args);
1247
+ run(_, callback) {
1248
+ return callback();
778
1249
  }
779
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
780
- traceCallback(fn, _position, _message, thisArg, ...args) {
781
- return fn.apply(thisArg, args);
1250
+ getStore() {
1251
+ return void 0;
782
1252
  }
783
1253
  };
784
1254
  var iso = {
@@ -791,7 +1261,7 @@ var iso = {
791
1261
  getCallerLocation: () => void 0,
792
1262
  newAsyncLocalStorage: () => new DefaultAsyncLocalStorage(),
793
1263
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
794
- newTracingChannel: (nameOrChannels) => new DefaultTracingChannel(nameOrChannels),
1264
+ newTracingChannel: (nameOrChannels) => newGlobalTracingChannel(nameOrChannels),
795
1265
  processOn: (_0, _1) => {
796
1266
  },
797
1267
  basename: (filepath) => filepath.split(/[\\/]/).pop() || filepath,
@@ -814,11 +1284,21 @@ function defineChannels(pkg, channels, options) {
814
1284
  const tracingChannel2 = () => isomorph_default.newTracingChannel(
815
1285
  fullChannelName
816
1286
  );
1287
+ const intercept2 = (interceptor) => {
1288
+ const hook = tracingChannel2();
1289
+ return typeof hook.intercept === "function" ? hook.intercept(interceptor) : () => {
1290
+ };
1291
+ };
817
1292
  return [
818
1293
  key,
819
1294
  {
820
1295
  ...asyncSpec,
821
1296
  instrumentationName,
1297
+ intercept: intercept2,
1298
+ invoke: (target, thisArg, args, additional) => {
1299
+ const hook = tracingChannel2();
1300
+ return typeof hook.invoke === "function" ? hook.invoke(target, thisArg, args, additional) : Reflect.apply(target, thisArg, args);
1301
+ },
822
1302
  tracingChannel: tracingChannel2,
823
1303
  tracePromise: (fn, context) => tracingChannel2().tracePromise(
824
1304
  fn,
@@ -832,11 +1312,21 @@ function defineChannels(pkg, channels, options) {
832
1312
  const tracingChannel = () => isomorph_default.newTracingChannel(
833
1313
  fullChannelName
834
1314
  );
1315
+ const intercept = (interceptor) => {
1316
+ const hook = tracingChannel();
1317
+ return typeof hook.intercept === "function" ? hook.intercept(interceptor) : () => {
1318
+ };
1319
+ };
835
1320
  return [
836
1321
  key,
837
1322
  {
838
1323
  ...syncSpec,
839
1324
  instrumentationName,
1325
+ intercept,
1326
+ invoke: (target, thisArg, args, additional) => {
1327
+ const hook = tracingChannel();
1328
+ return typeof hook.invoke === "function" ? hook.invoke(target, thisArg, args, additional) : Reflect.apply(target, thisArg, args);
1329
+ },
840
1330
  tracingChannel,
841
1331
  traceSync: (fn, context) => tracingChannel().traceSync(
842
1332
  fn,
@@ -856,6 +1346,9 @@ var INSTRUMENTATION_NAMES = {
856
1346
  BEDROCK_RUNTIME: "bedrock-runtime",
857
1347
  BRAINTRUST_JS_LOGGER: "braintrust-js-logger",
858
1348
  CLAUDE_AGENT_SDK: "claude-agent-sdk",
1349
+ CLOUDFLARE_AI_CHAT: "cloudflare-ai-chat",
1350
+ CLOUDFLARE_AGENTS: "cloudflare-agents",
1351
+ CLOUDFLARE_THINK: "cloudflare-think",
859
1352
  COHERE: "cohere",
860
1353
  CURSOR_SDK: "cursor-sdk",
861
1354
  EVE: "eve",
@@ -870,6 +1363,7 @@ var INSTRUMENTATION_NAMES = {
870
1363
  LANGSMITH: "langsmith",
871
1364
  MASTRA: "mastra",
872
1365
  MISTRAL: "mistral",
1366
+ OLLAMA: "ollama",
873
1367
  OPENAI: "openai",
874
1368
  OPENAI_AGENTS: "openai-agents",
875
1369
  OPENAI_CODEX: "openai-codex",
@@ -1386,6 +1880,14 @@ var anthropicChannels = defineChannels(
1386
1880
  betaMessagesToolRunner: channel({
1387
1881
  channelName: "beta.messages.toolRunner",
1388
1882
  kind: "sync-stream"
1883
+ }),
1884
+ betaSessionsEventsStream: channel({
1885
+ channelName: "beta.sessions.events.stream",
1886
+ kind: "async"
1887
+ }),
1888
+ betaSessionsThreadsEventsStream: channel({
1889
+ channelName: "beta.sessions.threads.events.stream",
1890
+ kind: "async"
1389
1891
  })
1390
1892
  },
1391
1893
  { instrumentationName: INSTRUMENTATION_NAMES.ANTHROPIC }
@@ -1504,7 +2006,40 @@ var anthropicConfigs = [
1504
2006
  methodName: "toolRunner",
1505
2007
  kind: "Sync"
1506
2008
  }
1507
- }
2009
+ },
2010
+ // Managed Agents Sessions event streams are discovered automatically, but
2011
+ // remain passive until the user calls collectAnthropicSession() on the
2012
+ // returned stream.
2013
+ ...["mjs", "js"].map(
2014
+ (extension) => ({
2015
+ channelName: anthropicChannels.betaSessionsEventsStream.channelName,
2016
+ module: {
2017
+ name: "@anthropic-ai/sdk",
2018
+ versionRange: ">=0.86.0",
2019
+ filePath: `resources/beta/sessions/events.${extension}`
2020
+ },
2021
+ functionQuery: {
2022
+ className: "Events",
2023
+ methodName: "stream",
2024
+ kind: "Async"
2025
+ }
2026
+ })
2027
+ ),
2028
+ ...["mjs", "js"].map(
2029
+ (extension) => ({
2030
+ channelName: anthropicChannels.betaSessionsThreadsEventsStream.channelName,
2031
+ module: {
2032
+ name: "@anthropic-ai/sdk",
2033
+ versionRange: ">=0.86.0",
2034
+ filePath: `resources/beta/sessions/threads/events.${extension}`
2035
+ },
2036
+ functionQuery: {
2037
+ className: "Events",
2038
+ methodName: "stream",
2039
+ kind: "Async"
2040
+ }
2041
+ })
2042
+ )
1508
2043
  ];
1509
2044
 
1510
2045
  // src/instrumentation/plugins/bedrock-runtime-channels.ts
@@ -1633,6 +2168,104 @@ var claudeAgentSDKConfigs = [
1633
2168
  }
1634
2169
  ];
1635
2170
 
2171
+ // src/instrumentation/plugins/cloudflare-ai-chat-channels.ts
2172
+ var cloudflareAIChatChannels = defineChannels(
2173
+ "@cloudflare/ai-chat",
2174
+ {
2175
+ runExclusiveChatTurn: channel({
2176
+ channelName: "AIChatAgent._runExclusiveChatTurn",
2177
+ kind: "async"
2178
+ }),
2179
+ onChatResponse: channel({
2180
+ channelName: "AIChatAgent.onChatResponse",
2181
+ kind: "sync-stream"
2182
+ })
2183
+ },
2184
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AI_CHAT }
2185
+ );
2186
+
2187
+ // src/auto-instrumentations/configs/cloudflare-ai-chat.ts
2188
+ var cloudflareAIChatVersionRange = ">=0.9.0 <0.10.0";
2189
+ var cloudflareAIChatConfigs = [
2190
+ {
2191
+ // AIChatAgent subclasses replace onChatMessage, so there is no stable
2192
+ // public implementation for the transformer to target. This runner is
2193
+ // the narrowest shared boundary around every chat turn; keep the version
2194
+ // range tight because it is an internal method.
2195
+ channelName: cloudflareAIChatChannels.runExclusiveChatTurn.channelName,
2196
+ module: {
2197
+ name: "@cloudflare/ai-chat",
2198
+ versionRange: cloudflareAIChatVersionRange,
2199
+ filePath: "dist/index.js"
2200
+ },
2201
+ functionQuery: {
2202
+ className: "AIChatAgent",
2203
+ methodName: "_runExclusiveChatTurn",
2204
+ kind: "Async"
2205
+ }
2206
+ }
2207
+ ];
2208
+
2209
+ // src/instrumentation/plugins/cloudflare-agents-channels.ts
2210
+ var cloudflareAgentsChannels = defineChannels(
2211
+ "agents",
2212
+ {
2213
+ runAgentTool: channel({
2214
+ channelName: "Agent.runAgentTool",
2215
+ kind: "async"
2216
+ })
2217
+ },
2218
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_AGENTS }
2219
+ );
2220
+
2221
+ // src/auto-instrumentations/configs/cloudflare-agents.ts
2222
+ var cloudflareAgentsVersionRange = ">=0.17.0 <0.18.0";
2223
+ var cloudflareAgentsConfigs = [
2224
+ {
2225
+ channelName: cloudflareAgentsChannels.runAgentTool.channelName,
2226
+ module: {
2227
+ name: "agents",
2228
+ versionRange: cloudflareAgentsVersionRange,
2229
+ filePath: "dist/index.js"
2230
+ },
2231
+ functionQuery: {
2232
+ className: "Agent",
2233
+ methodName: "runAgentTool",
2234
+ kind: "Async"
2235
+ }
2236
+ }
2237
+ ];
2238
+
2239
+ // src/instrumentation/plugins/cloudflare-think-channels.ts
2240
+ var cloudflareThinkChannels = defineChannels(
2241
+ "@cloudflare/think",
2242
+ {
2243
+ runInferenceLoop: channel({
2244
+ channelName: "Think.runInferenceLoop",
2245
+ kind: "async"
2246
+ })
2247
+ },
2248
+ { instrumentationName: INSTRUMENTATION_NAMES.CLOUDFLARE_THINK }
2249
+ );
2250
+
2251
+ // src/auto-instrumentations/configs/cloudflare-think.ts
2252
+ var cloudflareThinkVersionRange = ">=0.13.0 <0.14.0";
2253
+ var cloudflareThinkConfigs = [
2254
+ {
2255
+ channelName: cloudflareThinkChannels.runInferenceLoop.channelName,
2256
+ module: {
2257
+ name: "@cloudflare/think",
2258
+ versionRange: cloudflareThinkVersionRange,
2259
+ filePath: "dist/think.js"
2260
+ },
2261
+ functionQuery: {
2262
+ className: "Think",
2263
+ methodName: "_runInferenceLoop",
2264
+ kind: "Async"
2265
+ }
2266
+ }
2267
+ ];
2268
+
1636
2269
  // src/instrumentation/plugins/cohere-channels.ts
1637
2270
  var cohereChannels = defineChannels(
1638
2271
  "cohere-ai",
@@ -2995,6 +3628,83 @@ var huggingFaceConfigs = [
2995
3628
  }
2996
3629
  ];
2997
3630
 
3631
+ // src/instrumentation/plugins/huggingface-transformers-channels.ts
3632
+ var huggingFaceTransformersChannels = defineChannels(
3633
+ "@huggingface/transformers",
3634
+ {
3635
+ pipeline: channel({
3636
+ channelName: "pipeline",
3637
+ kind: "async"
3638
+ }),
3639
+ pipelineCall: channel({
3640
+ channelName: "pipeline.call",
3641
+ kind: "async"
3642
+ })
3643
+ },
3644
+ { instrumentationName: INSTRUMENTATION_NAMES.HUGGINGFACE }
3645
+ );
3646
+
3647
+ // src/auto-instrumentations/configs/huggingface-transformers.ts
3648
+ var moduleFiles = [
3649
+ {
3650
+ filePath: "dist/transformers.mjs",
3651
+ versionRange: ">=3.0.0 <3.4.0"
3652
+ },
3653
+ {
3654
+ filePath: "dist/transformers.cjs",
3655
+ versionRange: ">=3.0.0 <3.4.0"
3656
+ },
3657
+ {
3658
+ filePath: "dist/transformers.js",
3659
+ versionRange: ">=3.0.0 <3.4.0"
3660
+ },
3661
+ {
3662
+ filePath: "dist/transformers.node.mjs",
3663
+ versionRange: ">=3.4.0 <5.0.0"
3664
+ },
3665
+ {
3666
+ filePath: "dist/transformers.node.cjs",
3667
+ versionRange: ">=3.4.0 <5.0.0"
3668
+ },
3669
+ {
3670
+ filePath: "dist/transformers.web.js",
3671
+ versionRange: ">=3.4.0 <5.0.0"
3672
+ }
3673
+ ];
3674
+ var pipelineClasses = [
3675
+ "TextGenerationPipeline",
3676
+ "Text2TextGenerationPipeline",
3677
+ "FeatureExtractionPipeline",
3678
+ "QuestionAnsweringPipeline"
3679
+ ];
3680
+ var huggingFaceTransformersConfigs = moduleFiles.flatMap(({ filePath, versionRange: versionRange2 }) => [
3681
+ {
3682
+ channelName: huggingFaceTransformersChannels.pipeline.channelName,
3683
+ module: {
3684
+ name: "@huggingface/transformers",
3685
+ versionRange: versionRange2,
3686
+ filePath
3687
+ },
3688
+ functionQuery: {
3689
+ functionName: "pipeline",
3690
+ kind: "Async"
3691
+ }
3692
+ },
3693
+ ...pipelineClasses.map((className) => ({
3694
+ channelName: huggingFaceTransformersChannels.pipelineCall.channelName,
3695
+ module: {
3696
+ name: "@huggingface/transformers",
3697
+ versionRange: versionRange2,
3698
+ filePath
3699
+ },
3700
+ functionQuery: {
3701
+ className,
3702
+ methodName: "_call",
3703
+ kind: "Async"
3704
+ }
3705
+ }))
3706
+ ]);
3707
+
2998
3708
  // src/instrumentation/plugins/langchain-channels.ts
2999
3709
  var langChainChannels = defineChannels(
3000
3710
  "@langchain/core",
@@ -3439,6 +4149,51 @@ var mistralConfigs = [
3439
4149
  }
3440
4150
  ];
3441
4151
 
4152
+ // src/instrumentation/plugins/ollama-channels.ts
4153
+ var ollamaChannels = defineChannels(
4154
+ "ollama",
4155
+ {
4156
+ chat: channel({
4157
+ channelName: "chat",
4158
+ kind: "async"
4159
+ }),
4160
+ generate: channel({
4161
+ channelName: "generate",
4162
+ kind: "async"
4163
+ }),
4164
+ embed: channel({
4165
+ channelName: "embed",
4166
+ kind: "async"
4167
+ })
4168
+ },
4169
+ { instrumentationName: INSTRUMENTATION_NAMES.OLLAMA }
4170
+ );
4171
+
4172
+ // src/auto-instrumentations/configs/ollama.ts
4173
+ var methods = [
4174
+ ["chat", ollamaChannels.chat.channelName],
4175
+ ["generate", ollamaChannels.generate.channelName],
4176
+ ["embed", ollamaChannels.embed.channelName]
4177
+ ];
4178
+ var implementationFiles = ["dist/browser.mjs", "dist/browser.cjs"];
4179
+ var ollamaConfigs = [
4180
+ ...implementationFiles.flatMap(
4181
+ (filePath) => methods.map(([methodName, channelName]) => ({
4182
+ channelName,
4183
+ module: {
4184
+ name: "ollama",
4185
+ versionRange: ">=0.6.0 <0.7.0",
4186
+ filePath
4187
+ },
4188
+ functionQuery: {
4189
+ className: "Ollama",
4190
+ methodName,
4191
+ kind: "Async"
4192
+ }
4193
+ }))
4194
+ )
4195
+ ];
4196
+
3442
4197
  // src/instrumentation/plugins/openai-agents-channels.ts
3443
4198
  var openAIAgentsCoreChannels = defineChannels(
3444
4199
  "@openai/agents-core",
@@ -3848,6 +4603,19 @@ var openRouterConfigs = [
3848
4603
  kind: "Async"
3849
4604
  }
3850
4605
  },
4606
+ {
4607
+ channelName: openRouterChannels.betaResponsesSend.channelName,
4608
+ module: {
4609
+ name: "@openrouter/sdk",
4610
+ versionRange: ">=1.1.2 <2.0.0",
4611
+ filePath: "esm/sdk/betaresponses.js"
4612
+ },
4613
+ functionQuery: {
4614
+ className: "BetaResponses",
4615
+ methodName: "send",
4616
+ kind: "Async"
4617
+ }
4618
+ },
3851
4619
  {
3852
4620
  channelName: openRouterChannels.callModel.channelName,
3853
4621
  module: {
@@ -4013,6 +4781,18 @@ var defaultInstrumentationConfigGroups = [
4013
4781
  integrations: ["claudeAgentSDK"],
4014
4782
  configs: claudeAgentSDKConfigs
4015
4783
  },
4784
+ {
4785
+ integrations: ["cloudflareAIChat"],
4786
+ configs: cloudflareAIChatConfigs
4787
+ },
4788
+ {
4789
+ integrations: ["cloudflareAgents"],
4790
+ configs: cloudflareAgentsConfigs
4791
+ },
4792
+ {
4793
+ integrations: ["cloudflareThink"],
4794
+ configs: cloudflareThinkConfigs
4795
+ },
4016
4796
  { integrations: ["cursor", "cursorSDK"], configs: cursorSDKConfigs },
4017
4797
  {
4018
4798
  integrations: ["openAIAgents"],
@@ -4022,7 +4802,10 @@ var defaultInstrumentationConfigGroups = [
4022
4802
  integrations: ["google", "googleGenAI"],
4023
4803
  configs: googleGenAIConfigs
4024
4804
  },
4025
- { integrations: ["huggingface"], configs: huggingFaceConfigs },
4805
+ {
4806
+ integrations: ["huggingface"],
4807
+ configs: [...huggingFaceConfigs, ...huggingFaceTransformersConfigs]
4808
+ },
4026
4809
  {
4027
4810
  integrations: ["langchain", "langgraph"],
4028
4811
  configs: langchainConfigs
@@ -4034,6 +4817,7 @@ var defaultInstrumentationConfigGroups = [
4034
4817
  configs: openRouterAgentConfigs
4035
4818
  },
4036
4819
  { integrations: ["mistral"], configs: mistralConfigs },
4820
+ { integrations: ["ollama"], configs: ollamaConfigs },
4037
4821
  { integrations: ["googleADK"], configs: googleADKConfigs },
4038
4822
  { integrations: ["cohere"], configs: cohereConfigs },
4039
4823
  { integrations: ["groq"], configs: groqConfigs },
@@ -4276,6 +5060,9 @@ function applySpecialCasePatch(input) {
4276
5060
  if (input.packageName === "openai" && input.modulePath.includes("api-promise")) {
4277
5061
  return input.source + OPENAI_API_PROMISE_PATCH;
4278
5062
  }
5063
+ if (input.browser) {
5064
+ return null;
5065
+ }
4279
5066
  const mastraTarget = classifyMastraTarget(
4280
5067
  input.packageName,
4281
5068
  input.modulePath
@@ -4286,6 +5073,49 @@ function applySpecialCasePatch(input) {
4286
5073
  return null;
4287
5074
  }
4288
5075
 
5076
+ // src/auto-instrumentations/loader/get-package-version.ts
5077
+ var import_node_fs = require("fs");
5078
+ var import_node_path = require("path");
5079
+ var packageNames = /* @__PURE__ */ new Map();
5080
+ function readPackageJson(baseDir) {
5081
+ try {
5082
+ const packageJsonPath = (0, import_node_path.join)(baseDir, "package.json");
5083
+ const jsonFile = (0, import_node_fs.readFileSync)(packageJsonPath, "utf8");
5084
+ return JSON.parse(jsonFile);
5085
+ } catch {
5086
+ return void 0;
5087
+ }
5088
+ }
5089
+ function resolvePackageBaseDir(baseDir) {
5090
+ try {
5091
+ return (0, import_node_fs.realpathSync)(baseDir);
5092
+ } catch {
5093
+ return baseDir;
5094
+ }
5095
+ }
5096
+ function readPackageJsonWithFallback(baseDir) {
5097
+ const packageJson = readPackageJson(baseDir);
5098
+ if (packageJson) {
5099
+ return packageJson;
5100
+ }
5101
+ const resolvedBaseDir = resolvePackageBaseDir(baseDir);
5102
+ if (resolvedBaseDir === baseDir) {
5103
+ return void 0;
5104
+ }
5105
+ return readPackageJson(resolvedBaseDir);
5106
+ }
5107
+ function getPackageName(baseDir) {
5108
+ if (packageNames.has(baseDir)) {
5109
+ return packageNames.get(baseDir);
5110
+ }
5111
+ const packageJson = readPackageJsonWithFallback(baseDir);
5112
+ if (typeof packageJson?.name === "string") {
5113
+ packageNames.set(baseDir, packageJson.name);
5114
+ return packageJson.name;
5115
+ }
5116
+ return void 0;
5117
+ }
5118
+
4289
5119
  // src/auto-instrumentations/bundler/plugin.ts
4290
5120
  function getModuleVersion(basedir) {
4291
5121
  try {
@@ -4298,84 +5128,92 @@ function getModuleVersion(basedir) {
4298
5128
  }
4299
5129
  return void 0;
4300
5130
  }
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
4350
- );
4351
- if (!transformer) {
4352
- return null;
4353
- }
5131
+ var unplugin = (0, import_unplugin.createUnplugin)((options = {}) => {
5132
+ const browser = options.browser ?? options.useDiagnosticChannelCompatShim ?? false;
5133
+ const allInstrumentations = getDefaultInstrumentationConfigs({
5134
+ additionalInstrumentations: options.instrumentations
5135
+ });
5136
+ const instrumentationMatcher = create(allInstrumentations);
5137
+ return {
5138
+ name: "code-transformer",
5139
+ enforce: "pre",
5140
+ transformInclude(id) {
5141
+ const pathWithoutQuery = id.split("?", 1)[0];
5142
+ if (!pathWithoutQuery) {
5143
+ return false;
5144
+ }
5145
+ if (pathWithoutQuery.startsWith("file:")) {
4354
5146
  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;
5147
+ return (0, import_path.isAbsolute)((0, import_url.fileURLToPath)(pathWithoutQuery));
5148
+ } catch {
5149
+ return false;
4368
5150
  }
4369
5151
  }
4370
- };
4371
- }
4372
- );
5152
+ return (0, import_path.isAbsolute)(pathWithoutQuery);
5153
+ },
5154
+ transform(code, id) {
5155
+ if (!id) {
5156
+ return null;
5157
+ }
5158
+ const cleanId = id.replace(/[?#].*$/, "");
5159
+ const filePath = cleanId.startsWith("file:") ? (0, import_url.fileURLToPath)(cleanId) : cleanId;
5160
+ const ext = (0, import_path.extname)(filePath);
5161
+ let isModule = ext === ".mjs" || ext === ".ts" || ext === ".tsx";
5162
+ if (ext === ".js") {
5163
+ isModule = code.includes("export ") || code.includes("import ");
5164
+ }
5165
+ const normalizedForPlatform = filePath.split("/").join(import_path.sep);
5166
+ const moduleDetails = (0, import_module_details_from_path.default)(normalizedForPlatform);
5167
+ if (!moduleDetails) {
5168
+ return null;
5169
+ }
5170
+ const moduleName = getPackageName(moduleDetails.basedir) ?? moduleDetails.name;
5171
+ const normalizedModulePath = moduleDetails.path.replace(/\\/g, "/");
5172
+ const moduleVersion = getModuleVersion(moduleDetails.basedir);
5173
+ const patched = applySpecialCasePatch({
5174
+ packageName: moduleName,
5175
+ modulePath: normalizedModulePath,
5176
+ source: code,
5177
+ format: isModule ? "esm" : "cjs",
5178
+ browser
5179
+ });
5180
+ if (patched !== null) {
5181
+ return { code: patched, map: null };
5182
+ }
5183
+ if (!moduleVersion) {
5184
+ console.warn(
5185
+ `No 'package.json' version found for module ${moduleName} at ${moduleDetails.basedir}. Skipping transformation.`
5186
+ );
5187
+ return null;
5188
+ }
5189
+ const transformer = instrumentationMatcher.getTransformer(
5190
+ moduleName,
5191
+ moduleVersion,
5192
+ normalizedModulePath
5193
+ );
5194
+ if (!transformer) {
5195
+ return null;
5196
+ }
5197
+ try {
5198
+ const moduleType = isModule ? "esm" : "cjs";
5199
+ const result = transformer.transform(code, moduleType);
5200
+ return {
5201
+ code: result.code,
5202
+ map: result.map
5203
+ };
5204
+ } catch (error) {
5205
+ console.warn(`Code transformation failed for ${id}: ${error}`);
5206
+ return null;
5207
+ }
5208
+ }
5209
+ };
5210
+ });
4373
5211
 
4374
5212
  // src/auto-instrumentations/bundler/webpack.ts
4375
5213
  var webpackPlugin = unplugin.webpack;
4376
5214
 
4377
5215
  // src/auto-instrumentations/bundler/next.ts
4378
- var requireFromProject = (0, import_node_module.createRequire)((0, import_node_path.join)(process.cwd(), "package.json"));
5216
+ var requireFromProject = (0, import_node_module.createRequire)((0, import_node_path2.join)(process.cwd(), "package.json"));
4379
5217
  var TURBOPACK_RULE_MATCHER = "*.{js,mjs,cjs}";
4380
5218
  function wrapNextjsConfigWithBraintrust(nextConfig) {
4381
5219
  const castNextConfig = nextConfig ?? {};
@@ -4446,33 +5284,9 @@ function wrapWebpackConfig(userWebpack) {
4446
5284
  }
4447
5285
  function wrapTurbopackConfig(turbopackConfig) {
4448
5286
  const config = { ...turbopackConfig ?? {} };
4449
- const resolveAlias = config.resolveAlias && typeof config.resolveAlias === "object" && !Array.isArray(config.resolveAlias) ? config.resolveAlias : {};
4450
5287
  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
5288
  return {
4471
5289
  ...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
5290
  rules: addBraintrustTurbopackRule(rules)
4477
5291
  };
4478
5292
  }