braintrust 3.20.0 → 3.21.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 (88) hide show
  1. package/NOTICE +20 -0
  2. package/README.md +2 -0
  3. package/dev/dist/index.d.mts +309 -199
  4. package/dev/dist/index.d.ts +309 -199
  5. package/dev/dist/index.js +2826 -983
  6. package/dev/dist/index.mjs +2286 -443
  7. package/dist/apply-auto-instrumentation.js +781 -199
  8. package/dist/apply-auto-instrumentation.mjs +588 -6
  9. package/dist/auto-instrumentations/bundler/esbuild.cjs +594 -2
  10. package/dist/auto-instrumentations/bundler/esbuild.d.mts +2 -2
  11. package/dist/auto-instrumentations/bundler/esbuild.d.ts +2 -2
  12. package/dist/auto-instrumentations/bundler/esbuild.mjs +3 -3
  13. package/dist/auto-instrumentations/bundler/next.cjs +594 -2
  14. package/dist/auto-instrumentations/bundler/next.mjs +4 -4
  15. package/dist/auto-instrumentations/bundler/rollup.cjs +594 -2
  16. package/dist/auto-instrumentations/bundler/rollup.d.mts +2 -2
  17. package/dist/auto-instrumentations/bundler/rollup.d.ts +2 -2
  18. package/dist/auto-instrumentations/bundler/rollup.mjs +3 -3
  19. package/dist/auto-instrumentations/bundler/vite.cjs +594 -2
  20. package/dist/auto-instrumentations/bundler/vite.d.mts +2 -2
  21. package/dist/auto-instrumentations/bundler/vite.d.ts +2 -2
  22. package/dist/auto-instrumentations/bundler/vite.mjs +3 -3
  23. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +593 -9
  24. package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +68 -1
  25. package/dist/auto-instrumentations/bundler/webpack.cjs +594 -2
  26. package/dist/auto-instrumentations/bundler/webpack.d.mts +2 -2
  27. package/dist/auto-instrumentations/bundler/webpack.d.ts +2 -2
  28. package/dist/auto-instrumentations/bundler/webpack.mjs +4 -4
  29. package/dist/auto-instrumentations/{chunk-W4E36GIW.mjs → chunk-BRQX23KL.mjs} +16 -0
  30. package/dist/auto-instrumentations/chunk-M6DLIJ2Z.mjs +784 -0
  31. package/dist/auto-instrumentations/{chunk-K74TZGGM.mjs → chunk-T6J4C7LX.mjs} +1 -1
  32. package/dist/auto-instrumentations/{chunk-S4374IP6.mjs → chunk-TKRPRPGD.mjs} +4 -6
  33. package/dist/auto-instrumentations/chunk-VT6DDNKM.mjs +856 -0
  34. package/dist/auto-instrumentations/hook.mjs +749 -45
  35. package/dist/auto-instrumentations/index.cjs +16 -0
  36. package/dist/auto-instrumentations/index.d.mts +2 -3
  37. package/dist/auto-instrumentations/index.d.ts +2 -3
  38. package/dist/auto-instrumentations/index.mjs +1 -1
  39. package/dist/auto-instrumentations/loader/cjs-patch.cjs +578 -4
  40. package/dist/auto-instrumentations/loader/cjs-patch.d.mts +1 -1
  41. package/dist/auto-instrumentations/loader/cjs-patch.d.ts +1 -1
  42. package/dist/auto-instrumentations/loader/cjs-patch.mjs +3 -7
  43. package/dist/auto-instrumentations/loader/esm-hook.mjs +2 -6
  44. package/dist/auto-instrumentations/{plugin-D7nDswtC.d.mts → plugin-D0KHwSJv.d.mts} +1 -1
  45. package/dist/auto-instrumentations/{plugin-D7nDswtC.d.ts → plugin-G6fgxk1b.d.ts} +1 -1
  46. package/dist/auto-instrumentations/types-RNPaKi9o.d.mts +70 -0
  47. package/dist/auto-instrumentations/types-RNPaKi9o.d.ts +70 -0
  48. package/dist/browser.d.mts +1357 -847
  49. package/dist/browser.d.ts +1357 -847
  50. package/dist/browser.js +2726 -469
  51. package/dist/browser.mjs +2726 -469
  52. package/dist/{chunk-LPC4W2WX.js → chunk-BFGIH2ZJ.js} +4 -0
  53. package/dist/{chunk-POCCIJAL.js → chunk-FY7DAKA5.js} +3141 -1269
  54. package/dist/{chunk-Y7W7WP6H.mjs → chunk-KMGUTPB7.mjs} +4 -0
  55. package/dist/{chunk-F73OMF66.mjs → chunk-O2P765XK.mjs} +2391 -519
  56. package/dist/cli.js +2260 -408
  57. package/dist/edge-light.d.mts +1 -1
  58. package/dist/edge-light.d.ts +1 -1
  59. package/dist/edge-light.js +2726 -469
  60. package/dist/edge-light.mjs +2726 -469
  61. package/dist/index.d.mts +1837 -1327
  62. package/dist/index.d.ts +1837 -1327
  63. package/dist/index.js +752 -353
  64. package/dist/index.mjs +445 -46
  65. package/dist/instrumentation/index.d.mts +107 -19
  66. package/dist/instrumentation/index.d.ts +107 -19
  67. package/dist/instrumentation/index.js +2337 -509
  68. package/dist/instrumentation/index.mjs +2337 -509
  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 +2726 -469
  74. package/dist/workerd.mjs +2726 -469
  75. package/licenses/import-in-the-middle/LICENSE +201 -0
  76. package/licenses/import-in-the-middle/LICENSE-3rdparty.csv +4 -0
  77. package/licenses/import-in-the-middle/NOTICE +34 -0
  78. package/licenses/orchestrion-js/LICENSE +202 -0
  79. package/licenses/orchestrion-js/LICENSE-3rdparty.csv +8 -0
  80. package/licenses/orchestrion-js/NOTICE +3 -0
  81. package/licenses/require-in-the-middle/LICENSE +23 -0
  82. package/package.json +13 -4
  83. package/util/dist/index.d.mts +1 -0
  84. package/util/dist/index.d.ts +1 -0
  85. package/util/dist/index.js +4 -4
  86. package/util/dist/index.mjs +2 -2
  87. package/dist/auto-instrumentations/chunk-J57YF7WS.mjs +0 -208
  88. package/dist/auto-instrumentations/chunk-QFMACSOL.mjs +0 -280
@@ -28,7 +28,7 @@ import {
28
28
  smithyClientChannels,
29
29
  smithyCoreChannels,
30
30
  strandsAgentSDKChannels
31
- } from "./chunk-Y7W7WP6H.mjs";
31
+ } from "./chunk-KMGUTPB7.mjs";
32
32
 
33
33
  // src/node/apply-auto-instrumentation-entry.ts
34
34
  import * as diagnostics_channel from "node:diagnostics_channel";
@@ -227,6 +227,18 @@ var aiSDKConfigs = [
227
227
  kind: "Sync"
228
228
  }
229
229
  },
230
+ {
231
+ channelName: aiSDKChannels.v7CreateTelemetryDispatcher.channelName,
232
+ module: {
233
+ name: "ai",
234
+ versionRange: ">=7.0.0-0 <8.0.0",
235
+ filePath: "dist/internal/index.js"
236
+ },
237
+ functionQuery: {
238
+ functionName: "createTelemetryDispatcher",
239
+ kind: "Sync"
240
+ }
241
+ },
230
242
  // streamObject - async function (v3 only, before the sync refactor in v4)
231
243
  {
232
244
  channelName: aiSDKChannels.streamObject.channelName,
@@ -2548,10 +2560,582 @@ function getDefaultAutoInstrumentationConfigs() {
2548
2560
  });
2549
2561
  }
2550
2562
 
2563
+ // src/auto-instrumentations/orchestrion-js/matcher.ts
2564
+ import semifies from "semifies";
2565
+
2566
+ // src/auto-instrumentations/orchestrion-js/transformer.ts
2567
+ import esquery2 from "esquery";
2568
+ import { generate } from "astring";
2569
+ import { parse as parse2 } from "meriyah";
2570
+ import { SourceMapGenerator } from "source-map";
2571
+
2572
+ // src/auto-instrumentations/orchestrion-js/transforms.ts
2573
+ import esquery from "esquery";
2574
+ import { parse } from "meriyah";
2575
+ var tracingChannelPredicate = (node) => node.declarations?.[0]?.id?.properties?.[0]?.value?.name === "tr_ch_apm_tracingChannel";
2576
+ var CHANNEL_REGEX = /[^\w]/g;
2577
+ function formatChannelVariable(channelName) {
2578
+ return `tr_ch_apm$${channelName.replace(CHANNEL_REGEX, "_")}`;
2579
+ }
2580
+ var transforms = {
2581
+ tracingChannelImport({ dcModule, moduleType }, node) {
2582
+ if (node.body.some(tracingChannelPredicate)) {
2583
+ return;
2584
+ }
2585
+ const options = { module: moduleType === "esm" };
2586
+ const index = node.body.findIndex(
2587
+ (child) => child.directive === "use strict"
2588
+ );
2589
+ const dc = moduleType === "esm" ? `import tr_ch_apm_dc from "${dcModule}"` : `const tr_ch_apm_dc = ${"require"}("${dcModule}")`;
2590
+ const tracingChannel2 = "const { tracingChannel: tr_ch_apm_tracingChannel } = tr_ch_apm_dc";
2591
+ const hasSubscribers = `const tr_ch_apm_hasSubscribers = ch => ch.start.hasSubscribers
2592
+ || ch.end.hasSubscribers
2593
+ || ch.asyncStart.hasSubscribers
2594
+ || ch.asyncEnd.hasSubscribers
2595
+ || ch.error.hasSubscribers`;
2596
+ node.body.splice(
2597
+ index + 1,
2598
+ 0,
2599
+ parse(dc, options).body[0],
2600
+ parse(tracingChannel2, options).body[0],
2601
+ parse(hasSubscribers, options).body[0]
2602
+ );
2603
+ },
2604
+ tracingChannelDeclaration(state2, node) {
2605
+ const {
2606
+ channelName,
2607
+ module: { name }
2608
+ } = state2;
2609
+ const channelVariable = formatChannelVariable(channelName);
2610
+ if (node.body.some(
2611
+ (child) => child.declarations?.[0]?.id?.name === channelVariable
2612
+ )) {
2613
+ return;
2614
+ }
2615
+ transforms.tracingChannelImport(state2, node, null, []);
2616
+ const index = node.body.findIndex(tracingChannelPredicate);
2617
+ const code = `
2618
+ const ${channelVariable} = tr_ch_apm_tracingChannel("orchestrion:${name}:${channelName}")
2619
+ `;
2620
+ node.body.splice(index + 1, 0, parse(code).body[0]);
2621
+ },
2622
+ traceCallback: traceAny,
2623
+ tracePromise: traceAny,
2624
+ traceSync: traceAny
2625
+ };
2626
+ function traceAny(state2, node, _parent, ancestry) {
2627
+ const program = ancestry[ancestry.length - 1];
2628
+ if (node.type === "ClassDeclaration" || node.type === "ClassExpression") {
2629
+ traceInstanceMethod(state2, node, program);
2630
+ } else {
2631
+ traceFunction(state2, node, program);
2632
+ }
2633
+ }
2634
+ function traceFunction(state2, node, program) {
2635
+ transforms.tracingChannelDeclaration(state2, program, null, []);
2636
+ const { functionQuery } = state2;
2637
+ const methodName = "methodName" in functionQuery ? functionQuery.methodName : void 0;
2638
+ const privateMethodName = "privateMethodName" in functionQuery ? functionQuery.privateMethodName : void 0;
2639
+ const functionName = "functionName" in functionQuery ? functionQuery.functionName : void 0;
2640
+ const isConstructor = methodName === "constructor" || !methodName && !privateMethodName && !functionName;
2641
+ const type = isConstructor ? "ArrowFunctionExpression" : "FunctionExpression";
2642
+ node.body = wrap(
2643
+ state2,
2644
+ {
2645
+ type,
2646
+ params: node.params,
2647
+ body: node.body,
2648
+ async: node.async,
2649
+ expression: false,
2650
+ generator: node.generator
2651
+ },
2652
+ program
2653
+ );
2654
+ node.generator = false;
2655
+ node.async = false;
2656
+ wrapSuper(node);
2657
+ }
2658
+ function traceInstanceMethod(state2, node, program) {
2659
+ const { functionQuery, operator } = state2;
2660
+ const { methodName } = functionQuery;
2661
+ if (!methodName) {
2662
+ return;
2663
+ }
2664
+ const classBody = node.body;
2665
+ if (classBody.body.some(({ key }) => key.name === methodName)) {
2666
+ return;
2667
+ }
2668
+ let ctor = classBody.body.find(({ kind }) => kind === "constructor");
2669
+ transforms.tracingChannelDeclaration(state2, program, null, []);
2670
+ if (!ctor) {
2671
+ ctor = parse(
2672
+ node.superClass ? "class A extends Object { constructor (...args) { super(...args) } }" : "class A { constructor () {} }"
2673
+ ).body[0].body.body[0];
2674
+ classBody.body.unshift(ctor);
2675
+ }
2676
+ const ctorBody = parse(`
2677
+ const __apm$${methodName} = this["${methodName}"]
2678
+ this["${methodName}"] = function () {}
2679
+ `).body;
2680
+ const fn = ctorBody[1].expression.right;
2681
+ fn.async = operator === "tracePromise";
2682
+ fn.body = wrap(
2683
+ state2,
2684
+ { type: "Identifier", name: `__apm$${methodName}` },
2685
+ program
2686
+ );
2687
+ wrapSuper(fn);
2688
+ ctor.value.body.body.push(...ctorBody);
2689
+ }
2690
+ function wrap(state2, node, program) {
2691
+ const { operator, moduleVersion } = state2;
2692
+ const wrapper = operator === "traceCallback" ? wrapCallback(state2) : operator === "tracePromise" ? wrapPromise(state2) : wrapSync(state2);
2693
+ const block = wrapper.body[0].body;
2694
+ const common = parse(
2695
+ node.type === "ArrowFunctionExpression" ? `
2696
+ const __apm$ctx = {
2697
+ arguments,
2698
+ moduleVersion: ${JSON.stringify(moduleVersion)}
2699
+ };
2700
+ const __apm$traced = () => {
2701
+ const __apm$wrapped = () => {};
2702
+ return __apm$wrapped(...arguments);
2703
+ };
2704
+ ` : `
2705
+ const __apm$ctx = {
2706
+ arguments,
2707
+ self: this,
2708
+ moduleVersion: ${JSON.stringify(moduleVersion)}
2709
+ };
2710
+ const __apm$traced = () => {
2711
+ const __apm$wrapped = () => {};
2712
+ return __apm$wrapped.apply(this, arguments);
2713
+ };
2714
+ `
2715
+ ).body;
2716
+ block.body.unshift(...common);
2717
+ esquery.query(block, "[id.name=__apm$wrapped]")[0].init = node;
2718
+ return block;
2719
+ }
2720
+ function wrapSuper(node) {
2721
+ const members = /* @__PURE__ */ new Set();
2722
+ esquery.traverse(
2723
+ node.body,
2724
+ esquery.parse("[object.type=Super]"),
2725
+ (node2, parent) => {
2726
+ const { name } = node2.property;
2727
+ let child;
2728
+ if (parent.callee) {
2729
+ const { expression } = parse(`__apm$super['${name}'].call(this)`).body[0];
2730
+ parent.callee = child = expression.callee;
2731
+ parent.arguments.unshift(...expression.arguments);
2732
+ } else {
2733
+ parent.expression = child = parse(`__apm$super['${name}']`).body[0];
2734
+ }
2735
+ child.computed = parent.callee.computed;
2736
+ child.optional = parent.callee.optional;
2737
+ members.add(name);
2738
+ }
2739
+ );
2740
+ for (const name of members) {
2741
+ const member = parse(`
2742
+ class Wrapper {
2743
+ wrapper () {
2744
+ __apm$super['${name}'] = super['${name}']
2745
+ }
2746
+ }
2747
+ `).body[0].body.body[0].value.body.body[0];
2748
+ node.body.body.unshift(member);
2749
+ }
2750
+ if (members.size > 0) {
2751
+ node.body.body.unshift(parse("const __apm$super = {}").body[0]);
2752
+ }
2753
+ }
2754
+ function wrapCallback(state2) {
2755
+ const {
2756
+ channelName,
2757
+ functionQuery: { callbackIndex = -1 }
2758
+ } = state2;
2759
+ const channelVariable = formatChannelVariable(channelName);
2760
+ return parse(`
2761
+ function wrapper () {
2762
+ const __apm$cb = Array.prototype.at.call(arguments, ${callbackIndex});
2763
+
2764
+ if (!${channelVariable}.start.hasSubscribers) return __apm$traced();
2765
+
2766
+ function __apm$wrappedCb(err, res) {
2767
+ if (err) {
2768
+ __apm$ctx.error = err;
2769
+ ${channelVariable}.error.publish(__apm$ctx);
2770
+ } else {
2771
+ __apm$ctx.result = res;
2772
+ }
2773
+
2774
+ ${channelVariable}.asyncStart.runStores(__apm$ctx, () => {
2775
+ try {
2776
+ if (__apm$cb) {
2777
+ return __apm$cb.apply(this, arguments);
2778
+ }
2779
+ } finally {
2780
+ ${channelVariable}.asyncEnd.publish(__apm$ctx);
2781
+ }
2782
+ });
2783
+ }
2784
+
2785
+ if (typeof __apm$cb !== 'function') {
2786
+ return __apm$traced();
2787
+ }
2788
+ Array.prototype.splice.call(arguments, ${callbackIndex}, 1, __apm$wrappedCb);
2789
+
2790
+ return ${channelVariable}.start.runStores(__apm$ctx, () => {
2791
+ try {
2792
+ return __apm$traced();
2793
+ } catch (err) {
2794
+ __apm$ctx.error = err;
2795
+ ${channelVariable}.error.publish(__apm$ctx);
2796
+ throw err;
2797
+ } finally {
2798
+ __apm$ctx.self ??= this;
2799
+ ${channelVariable}.end.publish(__apm$ctx);
2800
+ }
2801
+ });
2802
+ }
2803
+ `);
2804
+ }
2805
+ function wrapPromise(state2) {
2806
+ const { channelName } = state2;
2807
+ const channelVariable = formatChannelVariable(channelName);
2808
+ return parse(`
2809
+ function wrapper () {
2810
+ if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
2811
+
2812
+ return ${channelVariable}.start.runStores(__apm$ctx, () => {
2813
+ try {
2814
+ let promise = __apm$traced();
2815
+ if (typeof promise?.then !== 'function') {
2816
+ __apm$ctx.result = promise;
2817
+ return promise;
2818
+ }
2819
+ // Mirror Node.js core diagnostics_channel behaviour: for native Promise
2820
+ // instances, chain normally (safe since there is no subclass API to
2821
+ // preserve). For Promise subclasses and other thenables, side-chain the
2822
+ // callbacks for event publishing and return the original so that any
2823
+ // subclass-specific methods (e.g. APIPromise.withResponse()) remain
2824
+ // accessible to the caller.
2825
+ if (promise instanceof Promise && promise.constructor === Promise) {
2826
+ return promise.then(
2827
+ result => {
2828
+ __apm$ctx.result = result;
2829
+ ${channelVariable}.asyncStart.publish(__apm$ctx);
2830
+ ${channelVariable}.asyncEnd.publish(__apm$ctx);
2831
+ return result;
2832
+ },
2833
+ err => {
2834
+ __apm$ctx.error = err;
2835
+ ${channelVariable}.error.publish(__apm$ctx);
2836
+ ${channelVariable}.asyncStart.publish(__apm$ctx);
2837
+ ${channelVariable}.asyncEnd.publish(__apm$ctx);
2838
+ throw err;
2839
+ }
2840
+ );
2841
+ }
2842
+ promise.then(
2843
+ result => {
2844
+ __apm$ctx.result = result;
2845
+ ${channelVariable}.asyncStart.publish(__apm$ctx);
2846
+ ${channelVariable}.asyncEnd.publish(__apm$ctx);
2847
+ },
2848
+ err => {
2849
+ __apm$ctx.error = err;
2850
+ ${channelVariable}.error.publish(__apm$ctx);
2851
+ ${channelVariable}.asyncStart.publish(__apm$ctx);
2852
+ ${channelVariable}.asyncEnd.publish(__apm$ctx);
2853
+ }
2854
+ );
2855
+ return promise;
2856
+ } catch (err) {
2857
+ __apm$ctx.error = err;
2858
+ ${channelVariable}.error.publish(__apm$ctx);
2859
+ throw err;
2860
+ } finally {
2861
+ __apm$ctx.self ??= this;
2862
+ ${channelVariable}.end.publish(__apm$ctx);
2863
+ }
2864
+ });
2865
+ }
2866
+ `);
2867
+ }
2868
+ function wrapSync(state2) {
2869
+ const { channelName } = state2;
2870
+ const channelVariable = formatChannelVariable(channelName);
2871
+ return parse(`
2872
+ function wrapper () {
2873
+ if (!tr_ch_apm_hasSubscribers(${channelVariable})) return __apm$traced();
2874
+
2875
+ return ${channelVariable}.start.runStores(__apm$ctx, () => {
2876
+ try {
2877
+ const result = __apm$traced();
2878
+ __apm$ctx.result = result;
2879
+ return result;
2880
+ } catch (err) {
2881
+ __apm$ctx.error = err;
2882
+ ${channelVariable}.error.publish(__apm$ctx);
2883
+ throw err;
2884
+ } finally {
2885
+ __apm$ctx.self ??= this;
2886
+ ${channelVariable}.end.publish(__apm$ctx);
2887
+ }
2888
+ });
2889
+ }
2890
+ `);
2891
+ }
2892
+
2893
+ // src/auto-instrumentations/orchestrion-js/transformer.ts
2894
+ var Transformer = class {
2895
+ moduleName;
2896
+ version;
2897
+ filePath;
2898
+ configs = [];
2899
+ dcModule;
2900
+ constructor(moduleName, version, filePath, configs, dcModule) {
2901
+ this.moduleName = moduleName;
2902
+ this.version = version;
2903
+ this.filePath = filePath;
2904
+ this.configs = configs;
2905
+ this.dcModule = dcModule;
2906
+ }
2907
+ /**
2908
+ * Instruments `code` by injecting diagnostics_channel tracing around the
2909
+ * target functions defined by this transformer's configs.
2910
+ */
2911
+ transform(code, moduleType) {
2912
+ if (Buffer.isBuffer(code)) {
2913
+ code = code.toString();
2914
+ }
2915
+ if (!code) {
2916
+ return { code };
2917
+ }
2918
+ let ast;
2919
+ let aliases = {};
2920
+ let injectionCount = 0;
2921
+ for (const config of this.configs) {
2922
+ const { astQuery, functionQuery } = config;
2923
+ if (!ast) {
2924
+ const options = {
2925
+ loc: true,
2926
+ ranges: true,
2927
+ raw: true,
2928
+ module: moduleType === "esm"
2929
+ };
2930
+ try {
2931
+ ast = parse2(code, options);
2932
+ } catch {
2933
+ ast = parse2(code, { ...options, module: !options.module });
2934
+ }
2935
+ if (moduleType === "esm") {
2936
+ aliases = this.collectExportAliases(ast);
2937
+ }
2938
+ }
2939
+ const resolvedFunctionQuery = this.resolveExportAlias(
2940
+ functionQuery,
2941
+ aliases
2942
+ );
2943
+ const query = astQuery || this.fromFunctionQuery(resolvedFunctionQuery);
2944
+ const state2 = {
2945
+ ...config,
2946
+ dcModule: this.dcModule,
2947
+ moduleType,
2948
+ moduleVersion: this.version,
2949
+ functionQuery: resolvedFunctionQuery,
2950
+ operator: this.getOperator(resolvedFunctionQuery.kind)
2951
+ };
2952
+ esquery2.traverse(ast, esquery2.parse(query), (...args) => {
2953
+ injectionCount++;
2954
+ this.visit(state2, ...args);
2955
+ });
2956
+ }
2957
+ if (injectionCount === 0 && this.configs.length > 0) {
2958
+ const names = this.configs.map(({ astQuery, functionQuery }) => {
2959
+ const resolvedQuery = this.resolveExportAlias(functionQuery, aliases);
2960
+ const queryName = (q) => q.methodName || q.privateMethodName || q.functionName || q.propertyName || astQuery || "unknown";
2961
+ const originalName = queryName(functionQuery);
2962
+ const originalAlias = functionQuery.className || functionQuery.functionName;
2963
+ const resolvedAlias = resolvedQuery.className || resolvedQuery.functionName;
2964
+ if (originalAlias && originalAlias !== resolvedAlias) {
2965
+ return `${originalAlias} (local name: ${resolvedAlias})`;
2966
+ }
2967
+ return originalName;
2968
+ });
2969
+ throw new Error(
2970
+ `Failed to find injection points for: ${JSON.stringify(names)}`
2971
+ );
2972
+ }
2973
+ if (ast) {
2974
+ const file = `${this.moduleName}/${this.filePath}`;
2975
+ const sourceMap = new SourceMapGenerator({ file });
2976
+ const transformedCode = generate(ast, { sourceMap });
2977
+ const map = sourceMap.toString();
2978
+ return { code: transformedCode, map };
2979
+ }
2980
+ return { code };
2981
+ }
2982
+ free() {
2983
+ }
2984
+ visit(state2, ...args) {
2985
+ const transform = transforms[state2.operator];
2986
+ const { index = 0 } = state2.functionQuery;
2987
+ const [node] = args;
2988
+ const type = node.init?.type || node.type;
2989
+ if (type !== "ClassDeclaration" && type !== "ClassExpression") {
2990
+ if (node.type === "VariableDeclarator") {
2991
+ return;
2992
+ }
2993
+ state2.functionIndex = state2.functionIndex === void 0 ? 0 : state2.functionIndex + 1;
2994
+ if (index !== null && index !== state2.functionIndex) {
2995
+ return;
2996
+ }
2997
+ }
2998
+ transform(state2, ...args);
2999
+ }
3000
+ getOperator(kind) {
3001
+ switch (kind) {
3002
+ case "Async":
3003
+ return "tracePromise";
3004
+ case "Callback":
3005
+ return "traceCallback";
3006
+ case "Sync":
3007
+ return "traceSync";
3008
+ }
3009
+ }
3010
+ collectExportAliases(ast) {
3011
+ const aliases = {};
3012
+ for (const node of ast.body) {
3013
+ if (node.type === "ExportNamedDeclaration" && !node.source) {
3014
+ for (const spec of node.specifiers) {
3015
+ if (spec.exported && spec.local) {
3016
+ const exportedName = spec.exported.name ?? spec.exported.value;
3017
+ const localName = spec.local.name ?? spec.local.value;
3018
+ if (exportedName && localName) {
3019
+ aliases[exportedName] = localName;
3020
+ }
3021
+ }
3022
+ }
3023
+ }
3024
+ }
3025
+ return aliases;
3026
+ }
3027
+ resolveExportAlias(functionQuery, aliases) {
3028
+ if (!("isExportAlias" in functionQuery) || !functionQuery.isExportAlias) {
3029
+ return functionQuery;
3030
+ }
3031
+ if ("className" in functionQuery && aliases[functionQuery.className]) {
3032
+ return {
3033
+ ...functionQuery,
3034
+ className: aliases[functionQuery.className]
3035
+ };
3036
+ }
3037
+ if ("functionName" in functionQuery && aliases[functionQuery.functionName]) {
3038
+ return {
3039
+ ...functionQuery,
3040
+ functionName: aliases[functionQuery.functionName]
3041
+ };
3042
+ }
3043
+ return functionQuery;
3044
+ }
3045
+ functionQueryLabel(functionQuery) {
3046
+ if ("methodName" in functionQuery) {
3047
+ return functionQuery.methodName;
3048
+ }
3049
+ if ("privateMethodName" in functionQuery) {
3050
+ return functionQuery.privateMethodName;
3051
+ }
3052
+ if ("functionName" in functionQuery) {
3053
+ return functionQuery.functionName;
3054
+ }
3055
+ if ("propertyName" in functionQuery) {
3056
+ return functionQuery.propertyName;
3057
+ }
3058
+ return "unknown";
3059
+ }
3060
+ fromFunctionQuery(functionQuery) {
3061
+ const queries = [];
3062
+ if ("className" in functionQuery) {
3063
+ const { className } = functionQuery;
3064
+ const methodName = this.functionQueryLabel(functionQuery);
3065
+ const keyType = "privateMethodName" in functionQuery ? "PrivateIdentifier" : "Identifier";
3066
+ queries.push(
3067
+ `[id.name="${className}"]`,
3068
+ `[id.name="${className}"] > ClassExpression`,
3069
+ `[id.name="${className}"] > ClassBody > [key.name="${methodName}"][key.type=${keyType}] > [async]`,
3070
+ `[id.name="${className}"] > ClassExpression > ClassBody > [key.name="${methodName}"][key.type=${keyType}] > [async]`
3071
+ );
3072
+ } else if ("methodName" in functionQuery) {
3073
+ const { methodName } = functionQuery;
3074
+ queries.push(
3075
+ `ClassBody > [key.name="${methodName}"][key.type=Identifier] > [async]`,
3076
+ `Property[key.name="${methodName}"][key.type=Identifier] > [async]`
3077
+ );
3078
+ }
3079
+ if ("functionName" in functionQuery) {
3080
+ const { functionName } = functionQuery;
3081
+ queries.push(`FunctionDeclaration[id.name="${functionName}"][async]`);
3082
+ }
3083
+ if ("objectName" in functionQuery) {
3084
+ const { objectName, propertyName } = functionQuery;
3085
+ const objectSelector = objectName === "this" ? "left.object.type=ThisExpression" : `left.object.name="${objectName}"`;
3086
+ queries.push(
3087
+ `AssignmentExpression[${objectSelector}][left.property.name="${propertyName}"] > [async]`
3088
+ );
3089
+ }
3090
+ return queries.join(", ");
3091
+ }
3092
+ };
3093
+
3094
+ // src/auto-instrumentations/orchestrion-js/matcher.ts
3095
+ var InstrumentationMatcher = class {
3096
+ configs = [];
3097
+ dcModule;
3098
+ transformers = {};
3099
+ constructor(configs, dcModule) {
3100
+ this.configs = configs;
3101
+ this.dcModule = dcModule || "diagnostics_channel";
3102
+ }
3103
+ /**
3104
+ * Returns a Transformer for the given module/file/version, or undefined if no
3105
+ * registered config matches.
3106
+ */
3107
+ getTransformer(moduleName, version, filePath) {
3108
+ filePath = filePath.replace(/\\/g, "/");
3109
+ const id = `${moduleName}/${filePath}@${version}`;
3110
+ if (this.transformers[id]) {
3111
+ return this.transformers[id];
3112
+ }
3113
+ const configs = this.configs.filter(
3114
+ ({ module: mod }) => mod.name === moduleName && mod.filePath === filePath && semifies(version, mod.versionRange)
3115
+ );
3116
+ if (configs.length === 0) {
3117
+ return void 0;
3118
+ }
3119
+ this.transformers[id] = new Transformer(
3120
+ moduleName,
3121
+ version,
3122
+ filePath,
3123
+ configs,
3124
+ this.dcModule
3125
+ );
3126
+ return this.transformers[id];
3127
+ }
3128
+ free() {
3129
+ this.transformers = {};
3130
+ }
3131
+ };
3132
+
3133
+ // src/auto-instrumentations/orchestrion-js/index.ts
3134
+ function create(configs, dcModule) {
3135
+ return new InstrumentationMatcher(configs, dcModule);
3136
+ }
3137
+
2551
3138
  // src/auto-instrumentations/loader/cjs-patch.ts
2552
- import {
2553
- create
2554
- } from "@apm-js-collab/code-transformer";
2555
3139
  import * as NodeModule from "node:module";
2556
3140
  import { sep } from "node:path";
2557
3141
  import moduleDetailsFromPath from "module-details-from-path";
@@ -2701,8 +3285,6 @@ var ModulePatch = class {
2701
3285
  args[0] = transformedCode?.code;
2702
3286
  } catch (error) {
2703
3287
  console.warn(`Error transforming module ${filename}:`, error);
2704
- } finally {
2705
- transformer.free();
2706
3288
  }
2707
3289
  }
2708
3290
  }