dd-trace 6.25.0 → 6.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 (190) hide show
  1. package/README.md +3 -0
  2. package/ci/cypress/support.js +2 -1
  3. package/ci/vitest-no-worker-init-node-setup.mjs +2 -1
  4. package/ci/vitest-no-worker-init-runner-setup.mjs +2 -1
  5. package/ci/vitest-no-worker-init-setup.mjs +729 -724
  6. package/ci/vitest-no-worker-init-v5-setup.mjs +2 -1
  7. package/index.d.ts +58 -1
  8. package/initialize.mjs +5 -3
  9. package/package.json +36 -32
  10. package/packages/datadog-esbuild/index.js +8 -15
  11. package/packages/datadog-esbuild/src/log.js +2 -29
  12. package/packages/datadog-instrumentations/src/ai.js +88 -122
  13. package/packages/datadog-instrumentations/src/aws-lambda.js +9 -0
  14. package/packages/datadog-instrumentations/src/cypress-config.js +20 -9
  15. package/packages/datadog-instrumentations/src/helpers/bundler-esm-exports.js +23 -1
  16. package/packages/datadog-instrumentations/src/helpers/bundler-log.js +38 -0
  17. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +9 -6
  18. package/packages/datadog-instrumentations/src/helpers/fetch.js +51 -6
  19. package/packages/datadog-instrumentations/src/helpers/hooks.js +0 -1
  20. package/packages/datadog-instrumentations/src/helpers/instrument.js +1 -3
  21. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +6 -0
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +12 -1
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/ai.js +2 -0
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +5 -3
  25. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-client.js +30 -0
  26. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-server.js +23 -0
  27. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +21 -0
  28. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +33 -4
  29. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +30 -0
  30. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +6 -0
  31. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +122 -0
  32. package/packages/datadog-instrumentations/src/microgateway-core.js +1 -2
  33. package/packages/datadog-instrumentations/src/modelcontextprotocol-client.js +21 -0
  34. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +32 -2
  35. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +43 -0
  36. package/packages/datadog-instrumentations/src/next.js +184 -20
  37. package/packages/datadog-instrumentations/src/path-to-regexp.js +11 -11
  38. package/packages/datadog-instrumentations/src/router.js +52 -13
  39. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +1 -1
  40. package/packages/datadog-instrumentations/src/vitest-main.js +10 -2
  41. package/packages/datadog-plugin-aws-lambda/src/arn.js +41 -0
  42. package/packages/datadog-plugin-aws-lambda/src/context/events.js +167 -0
  43. package/packages/datadog-plugin-aws-lambda/src/context/extractor.js +153 -0
  44. package/packages/datadog-plugin-aws-lambda/src/context/http.js +50 -0
  45. package/packages/datadog-plugin-aws-lambda/src/context/span-context.js +26 -0
  46. package/packages/datadog-plugin-aws-lambda/src/context/step-functions.js +142 -0
  47. package/packages/datadog-plugin-aws-lambda/src/context/types.d.ts +17 -0
  48. package/packages/datadog-plugin-aws-lambda/src/context/xray.js +67 -0
  49. package/packages/datadog-plugin-aws-lambda/src/event-type-guards.js +170 -0
  50. package/packages/datadog-plugin-aws-lambda/src/index.js +52 -4
  51. package/packages/datadog-plugin-aws-lambda/src/trigger.js +339 -0
  52. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +7 -0
  53. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +32 -10
  54. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +10 -1
  55. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +4 -0
  56. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +3 -0
  57. package/packages/datadog-plugin-azure-functions/src/index.js +68 -12
  58. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +30 -4
  59. package/packages/datadog-plugin-cypress/src/support.mjs +1353 -0
  60. package/packages/datadog-plugin-express/src/code_origin.js +2 -2
  61. package/packages/datadog-plugin-fastify/src/code_origin.js +2 -2
  62. package/packages/datadog-plugin-fetch/src/index.js +7 -0
  63. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -0
  64. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +2 -0
  65. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +7 -0
  66. package/packages/datadog-plugin-google-cloud-pubsub/src/resource-names.js +24 -0
  67. package/packages/datadog-plugin-graphql/src/tools/transforms.js +1 -0
  68. package/packages/datadog-plugin-http/src/client.js +14 -1
  69. package/packages/datadog-plugin-http/src/server.js +18 -4
  70. package/packages/datadog-plugin-http2/src/client.js +2 -1
  71. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +28 -2
  72. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +1 -0
  73. package/packages/datadog-plugin-mongodb-core/src/query.js +17 -1
  74. package/packages/datadog-plugin-postgres/src/index.js +118 -41
  75. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +18 -8
  76. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +49 -13
  77. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +34 -9
  78. package/packages/datadog-plugin-vitest/src/index.js +3 -2
  79. package/packages/datadog-plugin-ws/src/close.js +3 -5
  80. package/packages/datadog-plugin-ws/src/producer.js +1 -4
  81. package/packages/datadog-plugin-ws/src/receiver.js +3 -5
  82. package/packages/datadog-plugin-ws/src/server.js +44 -13
  83. package/packages/datadog-vite/index.js +537 -0
  84. package/packages/datadog-vite/src/log.js +5 -0
  85. package/packages/datadog-webpack/src/log.js +2 -29
  86. package/packages/dd-trace/src/aiguard/client.js +7 -9
  87. package/packages/dd-trace/src/aiguard/evaluation.js +7 -2
  88. package/packages/dd-trace/src/aiguard/index.js +1 -1
  89. package/packages/dd-trace/src/aiguard/integrations/index.js +6 -5
  90. package/packages/dd-trace/src/aiguard/messages/utils.js +2 -2
  91. package/packages/dd-trace/src/aiguard/sdk.js +7 -2
  92. package/packages/dd-trace/src/appsec/api_security/normalized-route.js +273 -167
  93. package/packages/dd-trace/src/appsec/blocking/index.js +17 -1
  94. package/packages/dd-trace/src/appsec/channels.js +8 -0
  95. package/packages/dd-trace/src/appsec/downstream_requests.js +105 -0
  96. package/packages/dd-trace/src/appsec/graphql.js +10 -13
  97. package/packages/dd-trace/src/appsec/handlers/auth.js +1 -3
  98. package/packages/dd-trace/src/appsec/handlers/http-request.js +60 -65
  99. package/packages/dd-trace/src/appsec/handlers/http-response.js +61 -7
  100. package/packages/dd-trace/src/appsec/handlers/payments.js +23 -27
  101. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugin.js +21 -14
  102. package/packages/dd-trace/src/appsec/index.js +9 -0
  103. package/packages/dd-trace/src/appsec/lambda.js +17 -17
  104. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -4
  105. package/packages/dd-trace/src/appsec/rasp/index.js +64 -3
  106. package/packages/dd-trace/src/appsec/rasp/lfi.js +2 -2
  107. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +7 -17
  108. package/packages/dd-trace/src/appsec/rasp/ssrf.js +80 -16
  109. package/packages/dd-trace/src/appsec/rasp/utils.js +47 -3
  110. package/packages/dd-trace/src/appsec/recommended.json +70 -3
  111. package/packages/dd-trace/src/appsec/reporter.js +9 -0
  112. package/packages/dd-trace/src/appsec/sdk/set_user.js +3 -3
  113. package/packages/dd-trace/src/appsec/sdk/track_event.js +4 -4
  114. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +1 -1
  115. package/packages/dd-trace/src/appsec/user_tracking.js +6 -8
  116. package/packages/dd-trace/src/appsec/waf/index.js +65 -6
  117. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +33 -38
  118. package/packages/dd-trace/src/appsec/waf/waf_manager.js +18 -2
  119. package/packages/dd-trace/src/carrier.js +7 -1
  120. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/index.js +4 -2
  121. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +31 -19
  122. package/packages/dd-trace/src/config/generated-config-types.d.ts +14 -5
  123. package/packages/dd-trace/src/config/index.js +73 -27
  124. package/packages/dd-trace/src/config/parsers.js +60 -0
  125. package/packages/dd-trace/src/config/remote-config-layers.js +38 -0
  126. package/packages/dd-trace/src/config/remote_config.js +2 -1
  127. package/packages/dd-trace/src/config/supported-configurations.json +41 -13
  128. package/packages/dd-trace/src/datastreams/fnv.js +27 -0
  129. package/packages/dd-trace/src/datastreams/http.js +57 -0
  130. package/packages/dd-trace/src/datastreams/index.js +24 -0
  131. package/packages/dd-trace/src/datastreams/pathway.js +142 -28
  132. package/packages/dd-trace/src/datastreams/processor.js +27 -7
  133. package/packages/dd-trace/src/debugger/config.js +1 -1
  134. package/packages/dd-trace/src/debugger/devtools_client/request-options.js +7 -9
  135. package/packages/dd-trace/src/debugger/devtools_client/send.js +1 -1
  136. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  137. package/packages/dd-trace/src/debugger/devtools_client/tags.js +1 -1
  138. package/packages/dd-trace/src/debugger/index.js +2 -2
  139. package/packages/dd-trace/src/debugger/inspect-segment.js +3 -2
  140. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +4 -1
  141. package/packages/dd-trace/src/debugger/probe_sampler.js +39 -17
  142. package/packages/dd-trace/src/debugger/unsupported-runtime.js +2 -0
  143. package/packages/dd-trace/src/git_metadata.js +2 -1
  144. package/packages/dd-trace/src/index.js +6 -3
  145. package/packages/dd-trace/src/lambda/facade.js +6 -5
  146. package/packages/dd-trace/src/lambda/handler-paths.js +1 -1
  147. package/packages/dd-trace/src/llmobs/constants/tags.js +1 -0
  148. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +86 -3
  149. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +182 -1
  150. package/packages/dd-trace/src/llmobs/span_processor.js +3 -0
  151. package/packages/dd-trace/src/llmobs/tagger.js +9 -0
  152. package/packages/dd-trace/src/noop/span.js +0 -4
  153. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +3 -0
  154. package/packages/dd-trace/src/openfeature/configuration_source.js +20 -0
  155. package/packages/dd-trace/src/openfeature/flagging_provider.js +17 -0
  156. package/packages/dd-trace/src/opentelemetry/logs/otlp_transformer.js +2 -1
  157. package/packages/dd-trace/src/opentelemetry/metrics/otlp_transformer.js +2 -1
  158. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +16 -1
  159. package/packages/dd-trace/src/opentelemetry/trace/index.js +5 -4
  160. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +10 -6
  161. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +42 -26
  162. package/packages/dd-trace/src/opentracing/propagation/text_map.js +4 -4
  163. package/packages/dd-trace/src/plugin_manager.js +2 -0
  164. package/packages/dd-trace/src/plugins/ci_plugin.js +104 -9
  165. package/packages/dd-trace/src/plugins/index.js +2 -0
  166. package/packages/dd-trace/src/plugins/util/ci.js +34 -0
  167. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +9 -14
  168. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +3 -5
  169. package/packages/dd-trace/src/plugins/util/test.js +28 -1
  170. package/packages/dd-trace/src/plugins/util/url.js +9 -6
  171. package/packages/dd-trace/src/plugins/util/user-provided-git.js +4 -4
  172. package/packages/dd-trace/src/process-tags/index.js +1 -1
  173. package/packages/dd-trace/src/profiler.js +74 -12
  174. package/packages/dd-trace/src/profiling/profiler.js +30 -2
  175. package/packages/dd-trace/src/profiling/profilers/space.js +3 -1
  176. package/packages/dd-trace/src/profiling/profilers/wall.js +4 -4
  177. package/packages/dd-trace/src/profiling/remote-config.js +354 -0
  178. package/packages/dd-trace/src/profiling/runtime-capabilities.js +11 -0
  179. package/packages/dd-trace/src/propagation-hash/index.js +7 -0
  180. package/packages/dd-trace/src/proxy.js +13 -1
  181. package/packages/dd-trace/src/register-loader.js +43 -0
  182. package/register.js +10 -44
  183. package/register.mjs +27 -0
  184. package/vendor/dist/@opentelemetry/core/LICENSE +11 -0
  185. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  186. package/vite.d.ts +7 -0
  187. package/vite.js +3 -0
  188. package/lambda.d.ts +0 -39
  189. package/lambda.js +0 -3
  190. package/packages/datadog-plugin-cypress/src/support.js +0 -1348
@@ -14,6 +14,7 @@ const {
14
14
  // same marker. The value is the wrapper itself, so a second wrap of the same handler returns the
15
15
  // instrumented function rather than the raw one.
16
16
  const WRAPPED = Symbol.for('dd-trace.lambda.wrapped')
17
+ const prepareChannel = dc.channel('datadog:aws-lambda:invocation:prepare')
17
18
  const invocationChannel = dc.tracingChannel('datadog:aws-lambda:invoke')
18
19
 
19
20
  /**
@@ -46,6 +47,14 @@ function wrapHandler (handler, config, monitor) {
46
47
 
47
48
  // The shim awaits its startup listeners before calling the adapter. Preserve that boundary so
48
49
  // legacy RIC captures native context completion methods before the adapter replaces them.
50
+ // Resolve parent context before the invocation span starts. Diagnostic-channel publishing is synchronous,
51
+ // so the plugin supplies `preparation` when extraction must be awaited.
52
+ if (prepareChannel.hasSubscribers) prepareChannel.publish(invocationContext)
53
+ if (invocationContext.preparation) {
54
+ return invocationContext.preparation.then(() => invocationChannel.tracePromise(
55
+ () => Promise.resolve().then(() => Reflect.apply(invoke, this, args)), invocationContext
56
+ ))
57
+ }
49
58
  return invocationChannel.tracePromise(
50
59
  () => Promise.resolve().then(() => Reflect.apply(invoke, this, args)),
51
60
  invocationContext
@@ -301,14 +301,19 @@ function getRelativeImportPath (fromDirectory, importedFile) {
301
301
  * @param {string} browserHooksSource Datadog browser-side support hooks
302
302
  * @param {boolean} deferLifecycle whether manual support owns lifecycle registration
303
303
  * @param {string} lifecycleOwnerSource browser lifecycle ownership detection
304
+ * @param {string} [localBrowserHooks] browser hooks module inside the project
304
305
  * @returns {string[]} generated files
305
306
  */
306
307
  function createSupportWrapper (
307
- directory, originalSupportFile, browserHooksSource, deferLifecycle, lifecycleOwnerSource
308
+ directory, originalSupportFile, browserHooksSource, deferLifecycle, lifecycleOwnerSource, localBrowserHooks
308
309
  ) {
309
310
  const suffix = `${process.pid}-${randomUUID()}`
310
- const browserHooksFile = path.join(directory, `dd-cypress-support-hooks-${suffix}.mjs`)
311
- const wrapperFile = path.join(directory, `dd-cypress-support-${suffix}.mjs`)
311
+ // Stay on the project's TypeScript preprocessor instead of loading Babel for an injected .mjs entry.
312
+ const extension = /\.tsx?$/.test(originalSupportFile) ? path.extname(originalSupportFile) : '.mjs'
313
+ // These generated entries contain JavaScript; leave type checking to the user's support file.
314
+ const typeCheckDirective = extension === '.mjs' ? '' : '// @ts-nocheck\n'
315
+ const browserHooksFile = path.join(directory, `dd-cypress-support-hooks-${suffix}${extension}`)
316
+ const wrapperFile = path.join(directory, `dd-cypress-support-${suffix}${extension}`)
312
317
  const wrapperImports = [
313
318
  `import ${JSON.stringify(getRelativeImportPath(directory, browserHooksFile))}`,
314
319
  ]
@@ -319,7 +324,10 @@ function createSupportWrapper (
319
324
 
320
325
  const generatedFiles = []
321
326
  try {
322
- const guardedSource = `const ddSupportRoot = Cypress.mocha.getRootSuite()
327
+ const initializer = localBrowserHooks
328
+ ? `import initializeBrowserSupport from ${JSON.stringify(getRelativeImportPath(directory, localBrowserHooks))}\n`
329
+ : `${browserHooksSource}\n`
330
+ const guardedSource = `${initializer}const ddSupportRoot = Cypress.mocha.getRootSuite()
323
331
  const ddSupportKey = Symbol.for('dd-trace.cypress.support-installed')
324
332
  const ddHasLifecycle = (() => {
325
333
  const module = { exports: {} }
@@ -334,11 +342,11 @@ for (const key of ['_beforeAll', '_beforeEach', '_afterAll', '_afterEach']) {
334
342
  }
335
343
  ddSupportRoot[Symbol.for('dd-trace.cypress.lifecycle-positions')] = positions
336
344
  ddSupportRoot[Symbol.for('dd-trace.cypress.defer-lifecycle')] = ${deferLifecycle}
337
- ${browserHooksSource}
345
+ initializeBrowserSupport()
338
346
  ddSupportRoot[ddSupportKey] = true
339
347
  }
340
348
  `
341
- writeExclusiveFile(browserHooksFile, guardedSource)
349
+ writeExclusiveFile(browserHooksFile, `${typeCheckDirective}${guardedSource}`)
342
350
  generatedFiles.push(browserHooksFile)
343
351
  const finalize = `const root = Cypress.mocha.getRootSuite()
344
352
  const install = root[Symbol.for('dd-trace.cypress.install-lifecycle')]
@@ -359,7 +367,7 @@ if (typeof install === 'function' && (!hasLifecycle || !hasLifecycle(root))) {
359
367
  }
360
368
  }
361
369
  `
362
- writeExclusiveFile(wrapperFile, `${wrapperImports.join('\n')}\n${finalize}`)
370
+ writeExclusiveFile(wrapperFile, `${typeCheckDirective}${wrapperImports.join('\n')}\n${finalize}`)
363
371
  generatedFiles.push(wrapperFile)
364
372
  } catch (error) {
365
373
  for (const generatedFile of generatedFiles) removeGeneratedFile(generatedFile)
@@ -410,7 +418,7 @@ function injectSupportFile (config, manualLifecycle = false) {
410
418
  let browserHooksPath
411
419
  let lifecycleOwnerSource
412
420
  try {
413
- browserHooksPath = require.resolve('../../datadog-plugin-cypress/src/support')
421
+ browserHooksPath = require.resolve('../../datadog-plugin-cypress/src/support.mjs')
414
422
  browserHooksSource = fs.readFileSync(browserHooksPath, 'utf8')
415
423
  lifecycleOwnerSource = fs.readFileSync(require.resolve('../../datadog-plugin-cypress/src/lifecycle-owner'), 'utf8')
416
424
  } catch (error) {
@@ -423,6 +431,9 @@ function injectSupportFile (config, manualLifecycle = false) {
423
431
  }
424
432
 
425
433
  const projectRoot = config.projectRoot
434
+ // Local imports share one bundled module with manual support. External action
435
+ // preloads still need a project-local copy for Vite's filesystem boundary.
436
+ const localBrowserHooks = projectRoot && isPathInside(projectRoot, browserHooksPath) ? browserHooksPath : undefined
426
437
  const candidateDirectories = []
427
438
  if (originalSupportFile) candidateDirectories.push(path.dirname(originalSupportFile))
428
439
  if (projectRoot) candidateDirectories.push(projectRoot)
@@ -432,7 +443,7 @@ function injectSupportFile (config, manualLifecycle = false) {
432
443
  if (projectRoot && !isPathInside(projectRoot, directory)) continue
433
444
  try {
434
445
  const generatedFiles = createSupportWrapper(
435
- directory, originalSupportFile, browserHooksSource, !!deferLifecycle, lifecycleOwnerSource
446
+ directory, originalSupportFile, browserHooksSource, !!deferLifecycle, lifecycleOwnerSource, localBrowserHooks
436
447
  )
437
448
  config.supportFile = generatedFiles[1]
438
449
  // Shared across SDK copies, but scoped to this exact generated support path.
@@ -557,4 +557,26 @@ async function processModuleWithResolver (
557
557
  return setters
558
558
  }
559
559
 
560
- module.exports = { createEsmResolver, driveGetExportsGenerator, processModule }
560
+ /**
561
+ * Generates the IITM registration wrapper used by bundlers. Export bindings come from processModule; IITM owns the
562
+ * export proxy and hook semantics, just as it does for modules wrapped by its Node.js loader.
563
+ *
564
+ * @param {{ path: string, internal?: boolean, specifier?: string, setters: Iterable<string> }} options
565
+ */
566
+ function createEsmWrapper ({ path, internal, specifier, setters }) {
567
+ const iitmPath = require.resolve('import-in-the-middle/lib/register.js')
568
+ const toRegister = internal ? path : pathToFileURL(path)
569
+ return `
570
+ import { register } from ${JSON.stringify(iitmPath)};
571
+ import * as namespace from ${JSON.stringify(path)};
572
+ const _ = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
573
+ const set = {};
574
+ const get = {};
575
+
576
+ ${[...setters].join(';\n')};
577
+
578
+ register(${JSON.stringify(toRegister)}, _, set, get, ${JSON.stringify(specifier)});
579
+ `
580
+ }
581
+
582
+ module.exports = { createEsmResolver, createEsmWrapper, driveGetExportsGenerator, processModule }
@@ -0,0 +1,38 @@
1
+ 'use strict'
2
+
3
+ const { format } = require('node:util')
4
+
5
+ const noop = () => {}
6
+
7
+ /**
8
+ * @param {string} name
9
+ * @returns {import('./bundler-utils').BundlerLog}
10
+ */
11
+ function createBundlerLog (name) {
12
+ // eslint-disable-next-line eslint-rules/eslint-process-env
13
+ const debug = (process.env.DD_TRACE_DEBUG || '').trim().toLowerCase()
14
+ if (debug !== 'true' && debug !== '1') return { debug: noop, warn: noop }
15
+
16
+ const prefix = `[dd-trace/${name}]`
17
+ return {
18
+ debug (...args) {
19
+ // eslint-disable-next-line no-console
20
+ console.log(formatWithLogPrefix(prefix, ...args))
21
+ },
22
+ warn (...args) {
23
+ // eslint-disable-next-line no-console
24
+ console.warn(formatWithLogPrefix(`${prefix} Warning:`, ...args))
25
+ },
26
+ }
27
+ }
28
+
29
+ /**
30
+ * @param {string} prefix
31
+ * @param {unknown} [str]
32
+ * @param {...unknown} args
33
+ */
34
+ function formatWithLogPrefix (prefix, str, ...args) {
35
+ return typeof str === 'string' ? format(`${prefix} ${str}`, ...args) : format(prefix, str, ...args)
36
+ }
37
+
38
+ module.exports = createBundlerLog
@@ -89,7 +89,10 @@ function instrument ({ source, resourcePath, inputSourceMap, warn }) {
89
89
  const target = getTarget(resourcePath, false)
90
90
  if (!target || target.kind === 'none') return undefined
91
91
 
92
- const { nativeResourcePath, packageInfo, publications, rewriteTarget } = target
92
+ // Bundlers resolve the injected import from the module ID they passed in, which may be a symlink
93
+ // (for example with preserveSymlinks) whose realpath sits at a different directory depth.
94
+ const importerPath = resourcePath
95
+ const { packageInfo, publications, rewriteTarget } = target
93
96
  resourcePath = target.resourcePath
94
97
  const esm = packageInfo.esm
95
98
  if (publications.length > 0 && hasUnsafeCommonJsBindings(source)) {
@@ -97,7 +100,7 @@ function instrument ({ source, resourcePath, inputSourceMap, warn }) {
97
100
  return undefined
98
101
  }
99
102
 
100
- const dcModule = getDcModule(nativeResourcePath)
103
+ const dcModule = getDcModule(importerPath)
101
104
  let code = source
102
105
  let sourceMap = inputSourceMap
103
106
  let rewritten = false
@@ -559,12 +562,12 @@ function escapeRegExp (value) {
559
562
  }
560
563
 
561
564
  /**
562
- * @param {string} nativeResourcePath
565
+ * @param {string} importerPath
563
566
  */
564
- function getDcModule (nativeResourcePath) {
565
- let value = path.relative(path.dirname(nativeResourcePath), require.resolve('dc-polyfill')).replaceAll('\\', '/')
567
+ function getDcModule (importerPath) {
568
+ let value = path.relative(path.dirname(importerPath), require.resolve('dc-polyfill')).replaceAll('\\', '/')
566
569
  if (path.isAbsolute(value) || path.win32.isAbsolute(value)) {
567
- throw new Error(`Cannot create a relative diagnostic-channel import from ${nativeResourcePath}`)
570
+ throw new Error(`Cannot create a relative diagnostic-channel import from ${importerPath}`)
568
571
  }
569
572
  if (!value.startsWith('./') && !value.startsWith('../')) value = `./${value}`
570
573
  return value
@@ -1,6 +1,46 @@
1
1
  'use strict'
2
2
 
3
+ function noop () {}
4
+
3
5
  exports.createWrapFetch = function createWrapFetch (Request, ch, onLoad) {
6
+ /**
7
+ * Rejects an aborted request with the abort reason, once the body it would send is cancelled.
8
+ * @param {Request} req request to send.
9
+ * @param {import('undici-types').RequestInit | undefined} init options that fetch applies over `req`.
10
+ * @param {unknown} reason abort reason.
11
+ * @returns {Promise<never>}
12
+ */
13
+ function rejectAborted (req, init, reason) {
14
+ try {
15
+ // The request is built only to find the body to cancel.
16
+ const request = init === undefined ? req : new Request(req, init)
17
+ request.body?.cancel(reason).catch(noop)
18
+ } catch {
19
+ // The abort takes precedence over argument errors that fetch would raise, as in the other instrumentations
20
+ // that can abort: the request is not attempted.
21
+ }
22
+
23
+ return Promise.reject(reason)
24
+ }
25
+
26
+ /**
27
+ * @param {Function} fetch fetch implementation to call.
28
+ * @param {unknown} thisArg receiver of the fetch call.
29
+ * @param {Request} req request to send, published to subscribers.
30
+ * @param {import('undici-types').RequestInit | undefined} init options that fetch applies over `req`.
31
+ * @param {import('undici-types').RequestInit | undefined} options second argument of the fetch call.
32
+ */
33
+ function traceFetch (fetch, thisArg, req, init, options) {
34
+ const abortController = new AbortController()
35
+
36
+ return ch.tracePromise(() => {
37
+ const { signal } = abortController
38
+ if (signal.aborted) return rejectAborted(req, init, signal.reason)
39
+
40
+ return fetch.call(thisArg, req, options)
41
+ }, { req, init, abortController })
42
+ }
43
+
4
44
  return function wrapFetch (fetch) {
5
45
  if (typeof fetch !== 'function') return fetch
6
46
 
@@ -13,18 +53,23 @@ exports.createWrapFetch = function createWrapFetch (Request, ch, onLoad) {
13
53
  if (!ch.start.hasSubscribers) return fetch.apply(this, arguments)
14
54
 
15
55
  if (input instanceof Request) {
16
- const ctx = { req: input }
17
-
18
- return ch.tracePromise(() => fetch.call(this, input, init), ctx)
56
+ // `init` is left for fetch to read once: it can hold one-shot values such as iterators and streams. It can
57
+ // override the method, headers and body of `input`, but not its URL.
58
+ return traceFetch(fetch, this, input, init, init)
59
+ }
60
+ let req
61
+ try {
62
+ req = new Request(input, init)
63
+ } catch (error) {
64
+ // fetch rejects the arguments it can't build a request from, rather than throwing them synchronously
65
+ return Promise.reject(error)
19
66
  }
20
- const req = new Request(input, init)
21
- const ctx = { req }
22
67
  const signal = init?.signal
23
68
 
24
69
  // The signal of `req` only weakly follows `init.signal` and is collected once `req` is unreachable, which
25
70
  // stops aborts from reaching the in-flight request. Passing it again lets `fetch` follow it directly.
26
71
  const options = signal ? { signal, referrer: req.referrer, referrerPolicy: req.referrerPolicy } : undefined
27
- return ch.tracePromise(() => fetch.call(this, req, options), ctx)
72
+ return traceFetch(fetch, this, req, undefined, options)
28
73
  }
29
74
  }
30
75
  }
@@ -58,7 +58,6 @@ module.exports = {
58
58
  '@smithy/smithy-client': () => require('../aws-sdk'),
59
59
  '@vitest/runner': { esmFirst: true, fn: () => require('../vitest') },
60
60
  aerospike: () => require('../aerospike'),
61
- ai: () => require('../ai'),
62
61
  amqp10: () => require('../amqp10'),
63
62
  amqplib: () => require('../amqplib'),
64
63
  avsc: () => require('../avsc'),
@@ -88,9 +88,7 @@ exports.getHooks = function getHooks (names) {
88
88
  for (const { module } of rewriterInstrumentations) {
89
89
  if (!requested.has(module.name)) continue
90
90
  // Fresh objects, including the versions array: callers may adjust a hook
91
- // for their own registration (the ai and
92
- // aws-durable-execution-sdk-js plugins set `hook.file = null`), which must
93
- // not leak into any other call.
91
+ // for their own registration, which must not leak into any other call.
94
92
  const hook = { name: module.name, versions: [module.versionRange], file: module.filePath }
95
93
  sourceRewritePaths.set(hook, module.filePath)
96
94
  hooks.set(`${module.name}|${module.versionRange}|${module.filePath}`, hook)
@@ -199,6 +199,9 @@ function createMatcher (dcModule) {
199
199
  waitForAsyncEnd,
200
200
  } = require('./transforms')
201
201
  const {
202
+ postgresNativeCopy,
203
+ postgresNativePreparation,
204
+ postgresNativeTransactionEnd,
202
205
  postgresQueryAcquire,
203
206
  postgresQueryHandlers,
204
207
  postgresQueryLifecycle,
@@ -216,6 +219,9 @@ function createMatcher (dcModule) {
216
219
  matcher.addTransform('configureGraphqlJitRuntime', configureGraphqlJitRuntime)
217
220
  matcher.addTransform('configureMercuriusRequest', configureMercuriusRequest)
218
221
  matcher.addTransform('publishDurableOrchestrationFailure', publishDurableOrchestrationFailure)
222
+ matcher.addTransform('postgresNativeCopy', postgresNativeCopy)
223
+ matcher.addTransform('postgresNativePreparation', postgresNativePreparation)
224
+ matcher.addTransform('postgresNativeTransactionEnd', postgresNativeTransactionEnd)
219
225
  matcher.addTransform('postgresQueryAcquire', postgresQueryAcquire)
220
226
  matcher.addTransform('publishTrpcRequestInfo', publishTrpcRequestInfo)
221
227
  matcher.addTransform('postgresQueryHandlers', postgresQueryHandlers)
@@ -22,7 +22,10 @@
22
22
 
23
23
  /** @satisfies {InstrumentationRegistryEntry[]} */
24
24
  const registry = [
25
- { instrumentations: require('./instrumentations/ai') },
25
+ {
26
+ activate: { setup: () => require('../../ai') },
27
+ instrumentations: require('./instrumentations/ai'),
28
+ },
26
29
  { activate: true, instrumentations: require('./instrumentations/async-mutex') },
27
30
  { activate: true, instrumentations: require('./instrumentations/azure-cosmos') },
28
31
  { instrumentations: require('./instrumentations/azure-durable-functions') },
@@ -42,6 +45,14 @@ const registry = [
42
45
  { activate: true, instrumentations: require('./instrumentations/langgraph') },
43
46
  { activate: true, instrumentations: require('./instrumentations/mercurius') },
44
47
  { instrumentations: require('./instrumentations/modelcontextprotocol-sdk') },
48
+ {
49
+ activate: { setup: () => require('../../modelcontextprotocol-client') },
50
+ instrumentations: require('./instrumentations/modelcontextprotocol-client'),
51
+ },
52
+ {
53
+ activate: { setup: () => require('../../modelcontextprotocol-server') },
54
+ instrumentations: require('./instrumentations/modelcontextprotocol-server'),
55
+ },
45
56
  { instrumentations: require('./instrumentations/next') },
46
57
  { instrumentations: require('./instrumentations/openai-agents') },
47
58
  {
@@ -1,5 +1,7 @@
1
1
  'use strict'
2
2
 
3
+ // v4–6 publish separate CommonJS (.js) and ESM (.mjs) builds. v7 is ESM-only and uses
4
+ // dist/index.js for both import and require, so that file must still be rewritten for setup to run.
3
5
  module.exports = [
4
6
  // getTracer - for patching tracer
5
7
  {
@@ -1,7 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  // Match the private closure only while its captured identifiers retain the verified
4
- // 0.7–0.9 contract. A future rewrite then misses safely instead of injecting stale names.
4
+ // compiler contract. A future rewrite then misses safely instead of injecting stale names.
5
5
  const CREATE_BOUND_QUERY = 'FunctionDeclaration[id.name="createBoundQuery"]' +
6
6
  '[params.0.name="compilationContext"][params.1.name="document"][params.4.name="operationName"]'
7
7
  const WRAP_QUERY = `${CREATE_BOUND_QUERY} ` +
@@ -78,7 +78,9 @@ addInstrumentations('>=0.7.0 <0.8.5 || >=0.8.7 <0.9.0', 'dist/execution.js')
78
78
  addInstrumentations('>=0.8.5 <0.8.7', 'dist/cjs/execution.js')
79
79
  addInstrumentations('>=0.8.5 <0.8.7', 'dist/esm/execution.js')
80
80
  addInstrumentations('>=0.8.7 <0.9.0', 'dist/execution.mjs')
81
- addInstrumentations('>=0.9.1 <0.10.0', 'dist/cjs/execution.js')
82
- addInstrumentations('>=0.9.1 <0.10.0', 'dist/esm/execution.js')
81
+ for (const versionRange of ['>=0.9.1 <0.10.0', '>=0.10.0 <0.11.0']) {
82
+ addInstrumentations(versionRange, 'dist/cjs/execution.js')
83
+ addInstrumentations(versionRange, 'dist/esm/execution.js')
84
+ }
83
85
 
84
86
  module.exports = instrumentations
@@ -0,0 +1,30 @@
1
+ 'use strict'
2
+
3
+ // SDK 2.x bundles Client into `dist/index` up to 2.3, and into a `public-<hash>` chunk from 2.4.
4
+ const CLIENT_FILES = [
5
+ { versionRange: '>=2 <2.4.0', filePath: /^dist\/index\.[cm]js$/ },
6
+ { versionRange: '>=2.4.0', filePath: /^dist\/public-[\w-]+\.[cm]js$/ },
7
+ ]
8
+
9
+ const CLIENT_METHODS = [
10
+ 'callTool',
11
+ 'listTools',
12
+ 'listResources',
13
+ 'readResource',
14
+ 'listPrompts',
15
+ 'getPrompt',
16
+ ]
17
+
18
+ module.exports = [
19
+ ...CLIENT_FILES.flatMap(({ versionRange, filePath }) => CLIENT_METHODS.map(methodName => ({
20
+ module: { name: '@modelcontextprotocol/client', versionRange, filePath },
21
+ functionQuery: { methodName, className: 'Client', kind: 'Async' },
22
+ channelName: `Client_${methodName}`,
23
+ }))),
24
+ // Every 2.x release bundles Protocol into a `src-<hash>` chunk.
25
+ {
26
+ module: { name: '@modelcontextprotocol/client', versionRange: '>=2', filePath: /^dist\/src-[\w-]+\.[cm]js$/ },
27
+ functionQuery: { methodName: 'request', className: 'Protocol', kind: 'Sync' },
28
+ channelName: 'Protocol_request',
29
+ },
30
+ ]
@@ -0,0 +1,23 @@
1
+ 'use strict'
2
+
3
+ // SDK 2.x bundles Server and McpServer into an `mcp-<hash>` chunk whose hash changes between releases.
4
+ const filePath = /^dist\/mcp-[\w-]+\.[cm]js$/
5
+
6
+ /**
7
+ * @param {string} className
8
+ * @param {string} methodName
9
+ * @param {'Sync'|'Async'} kind
10
+ */
11
+ function entry (className, methodName, kind) {
12
+ return {
13
+ module: { name: '@modelcontextprotocol/server', versionRange: '>=2', filePath },
14
+ functionQuery: { methodName, className, kind },
15
+ channelName: `${className}_${methodName}`,
16
+ }
17
+ }
18
+
19
+ module.exports = [
20
+ entry('Server', '_wrapHandler', 'Sync'),
21
+ entry('McpServer', 'registerTool', 'Sync'),
22
+ entry('McpServer', 'executeToolHandler', 'Async'),
23
+ ]
@@ -7,6 +7,27 @@ const astQuery = 'MethodDefinition[key.name="handleNextImageRequest"] > Function
7
7
  ' > Property[key.name="fn"] > ArrowFunctionExpression'
8
8
 
9
9
  module.exports = [
10
+ ...[
11
+ 'dist/server/future/route-handler-managers/route-handler-manager.js',
12
+ /^dist\/compiled\/next-server\/app-route[\w-]*\.runtime\.(?:dev|prod)\.js$/,
13
+ ].map(filePath => ({
14
+ module: { name: 'next', versionRange: '>=13.3', filePath },
15
+ functionQuery: { methodName: 'handle', kind: 'Async' },
16
+ channelName: 'appRouteResponse',
17
+ })),
18
+ ...[
19
+ 'dist/next-server/server/api-utils.js',
20
+ 'dist/server/api-utils.js',
21
+ 'dist/server/api-utils/node.js',
22
+ 'dist/server/api-utils/node/api-resolver.js',
23
+ /^dist\/compiled\/next-server\/pages-api[\w-]*\.runtime\.(?:dev|prod)\.js$/,
24
+ ].map(filePath => ({
25
+ module: { name: 'next', versionRange: '>=10.2', filePath },
26
+ // These response methods are assigned inside apiResolver, including in minified Pages runtimes.
27
+ astQuery: 'AssignmentExpression[left.property.name=/^(json|send)$/] > ArrowFunctionExpression',
28
+ functionQuery: { kind: 'Sync', index: null },
29
+ channelName: 'responseBody',
30
+ })),
10
31
  {
11
32
  module: {
12
33
  name: 'next',
@@ -6,7 +6,7 @@ for (const filePath of ['src/index.js', 'cjs/src/index.js']) {
6
6
  instrumentations.push({
7
7
  module: {
8
8
  name: 'postgres',
9
- versionRange: '>=3.0.0',
9
+ versionRange: '>=3.0.0 <4',
10
10
  filePath,
11
11
  },
12
12
  astQuery: 'Program',
@@ -19,7 +19,7 @@ for (const filePath of ['src/connection.js', 'cjs/src/connection.js']) {
19
19
  instrumentations.push({
20
20
  module: {
21
21
  name: 'postgres',
22
- versionRange: '>=3.0.0',
22
+ versionRange: '>=3.0.0 <4',
23
23
  filePath,
24
24
  },
25
25
  astQuery: 'Program',
@@ -28,7 +28,7 @@ for (const filePath of ['src/connection.js', 'cjs/src/connection.js']) {
28
28
  }, {
29
29
  module: {
30
30
  name: 'postgres',
31
- versionRange: '>=3.0.0',
31
+ versionRange: '>=3.0.0 <4',
32
32
  filePath,
33
33
  },
34
34
  astQuery: 'Program',
@@ -41,7 +41,7 @@ for (const filePath of ['src/query.js', 'cjs/src/query.js']) {
41
41
  instrumentations.push({
42
42
  module: {
43
43
  name: 'postgres',
44
- versionRange: '>=3.0.0',
44
+ versionRange: '>=3.0.0 <4',
45
45
  filePath,
46
46
  },
47
47
  astQuery: 'Program',
@@ -50,4 +50,33 @@ for (const filePath of ['src/query.js', 'cjs/src/query.js']) {
50
50
  })
51
51
  }
52
52
 
53
+ instrumentations.push({
54
+ module: {
55
+ name: 'postgres',
56
+ versionRange: '>=4.0.0',
57
+ filePath: 'src/pool.js',
58
+ },
59
+ astQuery: 'Program',
60
+ transform: 'postgresNativePreparation',
61
+ channelName: 'query:prepare',
62
+ }, {
63
+ module: {
64
+ name: 'postgres',
65
+ versionRange: '>=4.0.0',
66
+ filePath: 'src/connection.js',
67
+ },
68
+ astQuery: 'Program',
69
+ transform: 'postgresNativeTransactionEnd',
70
+ channelName: 'query:prepare',
71
+ }, {
72
+ module: {
73
+ name: 'postgres',
74
+ versionRange: '>=4.0.0',
75
+ filePath: 'src/connection.js',
76
+ },
77
+ astQuery: 'Program',
78
+ transform: 'postgresNativeCopy',
79
+ channelName: 'query:copy',
80
+ })
81
+
53
82
  module.exports = instrumentations
@@ -1,4 +1,34 @@
1
1
  [
2
+ {
3
+ "name": "@modelcontextprotocol/client",
4
+ "source": "^dist\\/index\\.[cm]js$",
5
+ "flags": ""
6
+ },
7
+ {
8
+ "name": "@modelcontextprotocol/client",
9
+ "source": "^dist\\/public-[\\w-]+\\.[cm]js$",
10
+ "flags": ""
11
+ },
12
+ {
13
+ "name": "@modelcontextprotocol/client",
14
+ "source": "^dist\\/src-[\\w-]+\\.[cm]js$",
15
+ "flags": ""
16
+ },
17
+ {
18
+ "name": "@modelcontextprotocol/server",
19
+ "source": "^dist\\/mcp-[\\w-]+\\.[cm]js$",
20
+ "flags": ""
21
+ },
22
+ {
23
+ "name": "next",
24
+ "source": "^dist\\/compiled\\/next-server\\/app-route[\\w-]*\\.runtime\\.(?:dev|prod)\\.js$",
25
+ "flags": ""
26
+ },
27
+ {
28
+ "name": "next",
29
+ "source": "^dist\\/compiled\\/next-server\\/pages-api[\\w-]*\\.runtime\\.(?:dev|prod)\\.js$",
30
+ "flags": ""
31
+ },
2
32
  {
3
33
  "name": "react-router",
4
34
  "source": "^dist\\/(?:development|production)\\/chunk-[A-Z0-9]+\\.mjs$",
@@ -96,7 +96,12 @@
96
96
  "jest-runner/build/runTest.js": "jest-runner",
97
97
  "jest-runner/build/testWorker.js": "jest-runner",
98
98
  "mercurius/index.js": "mercurius",
99
+ "next/dist/next-server/server/api-utils.js": "next",
99
100
  "next/dist/next-server/server/next-server.js": "next",
101
+ "next/dist/server/api-utils.js": "next",
102
+ "next/dist/server/api-utils/node.js": "next",
103
+ "next/dist/server/api-utils/node/api-resolver.js": "next",
104
+ "next/dist/server/future/route-handler-managers/route-handler-manager.js": "next",
100
105
  "next/dist/server/next-server.js": "next",
101
106
  "playwright-core/lib/coreBundle.js": "playwright-core",
102
107
  "playwright/lib/common/config.js": "playwright",
@@ -110,6 +115,7 @@
110
115
  "postgres/cjs/src/query.js": "postgres",
111
116
  "postgres/src/connection.js": "postgres",
112
117
  "postgres/src/index.js": "postgres",
118
+ "postgres/src/pool.js": "postgres",
113
119
  "postgres/src/query.js": "postgres",
114
120
  "react-router/dist/development/index.js": "react-router",
115
121
  "react-router/dist/development/lib/server-runtime/routeMatching.js": "react-router",