dd-trace 5.136.0 → 5.138.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 +56 -0
  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
@@ -12,12 +12,134 @@ const POSTGRES_SIMPLE_DBM_QUERIES = '__ddTracePostgresSimpleDbmQueries'
12
12
  const POSTGRES_STATEMENT = 'this.string ?? (this.tagged && this.strings?.length !== 1 ? undefined : this.strings?.[0])'
13
13
 
14
14
  module.exports = {
15
+ postgresNativeCopy,
16
+ postgresNativePreparation,
17
+ postgresNativeTransactionEnd,
15
18
  postgresQueryAcquire,
16
19
  postgresQueryHandlers,
17
20
  postgresQueryLifecycle,
18
21
  postgresQueryPreparation,
19
22
  }
20
23
 
24
+ /**
25
+ * @param {object} state
26
+ * @param {import('estree').Program} program
27
+ */
28
+ function postgresNativeCopy (state, program) {
29
+ const channelVariable = injectPostgresTracingChannel(state, program)
30
+ const writable = query(program, 'FunctionDeclaration[id.name="writable"] Property[key.name="destroy"]')
31
+ const abandoned = query(program, 'FunctionDeclaration[id.name="abandoned"] > BlockStatement > ReturnStatement')
32
+ assert(writable.length === 1 && abandoned.length <= 1, 'postgresNativeCopy: stream destruction changed')
33
+
34
+ const publish = `
35
+ if (item.trace && ${channelVariable}.start.hasSubscribers) {
36
+ ${channelVariable}.start.publish({ query: item.trace, error });
37
+ }
38
+ `
39
+ writable[0].value.body.body.unshift(...parse(publish).body)
40
+
41
+ if (abandoned.length) {
42
+ abandoned[0].argument.body.body.unshift(...parse(publish).body)
43
+ } else {
44
+ const streams = query(program, 'FunctionDeclaration[id.name="CopyOutResponse"] NewExpression')
45
+ assert(streams.length === 1, 'postgresNativeCopy: readable construction changed')
46
+ streams[0].arguments[0].properties.push(...parse(`({
47
+ destroy(error, callback) {
48
+ ${publish}
49
+ callback(error);
50
+ }
51
+ })`).body[0].expression.properties)
52
+ }
53
+ }
54
+
55
+ /**
56
+ * @param {object} state
57
+ * @param {import('estree').Program} program
58
+ */
59
+ function postgresNativeTransactionEnd (state, program) {
60
+ // Leading DBM comments must not hide transaction endings from the cursor fence.
61
+ for (const name of ['send', 'simple', 'batch']) {
62
+ const functions = query(program, `FunctionDeclaration[id.name="${name}"]`)
63
+ if (name === 'batch' && functions.length === 0) continue
64
+ assert(functions.length === 1, 'postgresNativeTransactionEnd: connection method changed')
65
+ const tests = query(functions[0], 'CallExpression[callee.object.name="ending"][callee.property.name="test"]')
66
+ assert(tests.length === 1, 'postgresNativeTransactionEnd: transaction classifier changed')
67
+ const original = name === 'batch' ? 'part.built.text' : 'query.built?.text'
68
+ const text = parse(original).body[0].expression
69
+ tests[0].arguments[0] = name === 'batch'
70
+ ? text
71
+ : {
72
+ type: 'LogicalExpression',
73
+ operator: '??',
74
+ left: text,
75
+ right: tests[0].arguments[0],
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * @param {object} state
82
+ * @param {import('estree').Program} program
83
+ */
84
+ function postgresNativePreparation (state, program) {
85
+ const channelVariable = injectPostgresTracingChannel(state, program)
86
+ const pools = query(program, 'FunctionDeclaration[id.name="Pool"]')
87
+ const queries = query(program, 'FunctionDeclaration[id.name="query"]')
88
+ assert(pools.length === 1 && queries.length === 1, 'postgresNativePreparation: pool query changed')
89
+
90
+ const body = queries[0].body.body
91
+ const buildIndex = body.findIndex(statement => statement.type === 'TryStatement')
92
+ assert(buildIndex !== -1, 'postgresNativePreparation: query build changed')
93
+ body.splice(buildIndex + 1, 0, ...parse(`
94
+ if (q.trace && ${channelVariable}.start.hasSubscribers) {
95
+ built = __ddTracePostgresPrepare(q.trace, built,
96
+ Boolean(options.prepare && q.options.prepare !== false && !(q.options.simple && !built.values.length)));
97
+ }
98
+ `).body)
99
+
100
+ pools[0].body.body.push(...parse(`
101
+ function __ddTracePostgresPrepare(trace, built, prepared, resource) {
102
+ const singleHost = options.host.length === 1 && !options.path;
103
+ const ctx = {
104
+ query: trace,
105
+ statement: built.text,
106
+ resource: resource ?? built.text,
107
+ prepared,
108
+ host: singleHost ? options.host[0] : undefined,
109
+ port: singleHost ? options.port[0] : undefined
110
+ };
111
+ ${channelVariable}.start.publish(ctx);
112
+ if (ctx.statement === built.text) return built;
113
+ return { ...built, text: ctx.statement, dynamic: true };
114
+ }
115
+ `).body)
116
+
117
+ const batches = query(program, 'FunctionDeclaration[id.name="batch"]')
118
+ assert(batches.length <= 1, 'postgresNativePreparation: batch changed')
119
+ if (batches.length === 0) return
120
+
121
+ const loops = query(batches[0], 'CallExpression[callee.object.name="parts"][callee.property.name="forEach"]')
122
+ assert(loops.length === 1, 'postgresNativePreparation: batch preparation changed')
123
+ const callback = loops[0].arguments[0]
124
+ const declaration = callback.body.body[0]
125
+ assert(declaration.type === 'VariableDeclaration' && declaration.declarations[0].id.name === 'built',
126
+ 'postgresNativePreparation: batch build changed')
127
+ declaration.kind = 'let'
128
+ callback.body.body.splice(1, 0, ...parse(`
129
+ if (q.trace && ${channelVariable}.start.hasSubscribers) {
130
+ built = __ddTracePostgresPrepare(q.trace, built,
131
+ Boolean(options.prepare && x.options.prepare !== false), q.trace.query);
132
+ }
133
+ `).body)
134
+ const batchBody = batches[0].body.body
135
+ const loopIndex = batchBody.findIndex(statement => statement.type === 'ExpressionStatement' &&
136
+ statement.expression === loops[0])
137
+ assert(loopIndex !== -1, 'postgresNativePreparation: batch loop changed')
138
+ batchBody.splice(loopIndex, 0, ...parse(`
139
+ if (q.trace) q.trace.query = parts.map(part => part.built.text).join('; ');
140
+ `).body)
141
+ }
142
+
21
143
  /**
22
144
  * @param {object} state
23
145
  * @param {import('estree').Program} program
@@ -9,8 +9,7 @@ const errorChannel = channel('apm:microgateway-core:request:error')
9
9
 
10
10
  const name = 'microgateway-core'
11
11
 
12
- // TODO Remove " <=3.0.0" when "volos-util-apigee" module is fixed
13
- const versions = ['>=2.1 <=3.0.0']
12
+ const versions = ['>=2.1']
14
13
  const requestContexts = new WeakMap()
15
14
 
16
15
  function wrapConfigProxyFactory (configProxyFactory) {
@@ -0,0 +1,21 @@
1
+ 'use strict'
2
+
3
+ const { channel, tracingChannel } = require('dc-polyfill')
4
+
5
+ const { addTraceContextToRequest } = require('./modelcontextprotocol-sdk')
6
+
7
+ const requestCh = tracingChannel('orchestrion:@modelcontextprotocol/client:Protocol_request')
8
+ const clientRequestInjectCh = channel('apm:mcp:client:request:inject')
9
+
10
+ const TRACED_METHOD_PREFIX = /^(?:tools|resources|prompts)\//
11
+
12
+ // Replacing the request argument before Protocol.request runs puts the trace context in `_meta`, so out-of-process MCP
13
+ // servers can parent their spans to the client span.
14
+ requestCh.start.subscribe(ctx => {
15
+ const request = ctx.arguments?.[0]
16
+ if (!clientRequestInjectCh.hasSubscribers || !TRACED_METHOD_PREFIX.test(request?.method)) return
17
+
18
+ const injectCtx = {}
19
+ clientRequestInjectCh.publish(injectCtx)
20
+ if (injectCtx.traceContext) ctx.arguments[0] = addTraceContextToRequest(request, injectCtx.traceContext)
21
+ })
@@ -49,6 +49,30 @@ function finishServerRequest (protocol, requestId) {
49
49
  serverRequestCh.asyncEnd.publish(ctx)
50
50
  }
51
51
 
52
+ /**
53
+ * Plugins can replace the request a handler gets and the result the SDK sends. A failing transform keeps the result.
54
+ *
55
+ * @param {{ request: object, transformResult?: (result: unknown) => unknown }} ctx
56
+ * @param {Function} handler
57
+ * @param {object} thisArg
58
+ * @param {unknown[]} args
59
+ */
60
+ function callRequestHandler (ctx, handler, thisArg, args) {
61
+ const result = args[0] === ctx.request
62
+ ? handler.apply(thisArg, args)
63
+ : handler.call(thisArg, ctx.request, ...Array.prototype.slice.call(args, 1))
64
+ const { transformResult } = ctx
65
+ if (!transformResult) return result
66
+
67
+ return Promise.resolve(result).then(value => {
68
+ try {
69
+ return transformResult(value)
70
+ } catch {
71
+ return value
72
+ }
73
+ })
74
+ }
75
+
52
76
  function wrapRequestHandler (protocol, handler) {
53
77
  if (wrappedRequestHandlers.has(handler)) return handler
54
78
 
@@ -58,7 +82,7 @@ function wrapRequestHandler (protocol, handler) {
58
82
 
59
83
  let result
60
84
  try {
61
- result = handler.apply(this, arguments)
85
+ result = callRequestHandler(ctx, handler, this, arguments)
62
86
  } catch (err) {
63
87
  ctx.error = err
64
88
  throw err
@@ -147,7 +171,7 @@ function wrapProtocol (Protocol) {
147
171
  }
148
172
 
149
173
  wrapAbortControllers(this)
150
- const ctx = { request, extra }
174
+ const ctx = { request, extra, server: this }
151
175
  serverRequestCh.start.runStores(ctx, () => {
152
176
  let pending = pendingContexts.get(this)
153
177
  if (!pending) {
@@ -162,6 +186,10 @@ function wrapProtocol (Protocol) {
162
186
  ctx.error = err
163
187
  finishServerRequest(this, request.id)
164
188
  throw err
189
+ } finally {
190
+ // runStores restores only the APM store. `end` lets the LLM Obs plugin restore its own store. The handler
191
+ // keeps the server span because the SDK schedules it before `_onrequest` returns.
192
+ serverRequestCh.end.publish(ctx)
165
193
  }
166
194
 
167
195
  // The SDK registers an AbortController only when it actually dispatches a handler.
@@ -252,3 +280,5 @@ addHook({
252
280
  wrapMcpServer(exports.McpServer)
253
281
  return exports
254
282
  })
283
+
284
+ module.exports = { addTraceContextToRequest, callRequestHandler }
@@ -0,0 +1,43 @@
1
+ 'use strict'
2
+
3
+ const { channel, tracingChannel } = require('dc-polyfill')
4
+
5
+ const shimmer = require('../../datadog-shimmer')
6
+ const { callRequestHandler } = require('./modelcontextprotocol-sdk')
7
+
8
+ const wrapHandlerCh = tracingChannel('orchestrion:@modelcontextprotocol/server:Server__wrapHandler')
9
+ const registerToolCh = tracingChannel('orchestrion:@modelcontextprotocol/server:McpServer_registerTool')
10
+ const serverRequestCh = tracingChannel('apm:mcp:server:request')
11
+ const serverToolRegisteredCh = channel('apm:mcp:server:tool:registered')
12
+
13
+ const TRACED_METHOD_PREFIX = /^(?:tools|resources|prompts)\//
14
+
15
+ // The SDK builds each request handler at runtime, so the handler that Server._wrapHandler returns is replaced to trace
16
+ // every call. The SDK runs it in the async context of the incoming request.
17
+ wrapHandlerCh.end.subscribe(ctx => {
18
+ const handler = ctx.result
19
+ if (typeof handler !== 'function' || !TRACED_METHOD_PREFIX.test(ctx.arguments?.[0])) return
20
+
21
+ const server = ctx.self
22
+ ctx.result = shimmer.wrapFunction(handler, handler => function tracedRequestHandler (request, extra) {
23
+ if (!serverRequestCh.hasSubscribers) return handler.apply(this, arguments)
24
+
25
+ const requestCtx = { request, extra, server }
26
+ return serverRequestCh.tracePromise(callRequestHandler, requestCtx, undefined, requestCtx, handler, this, arguments)
27
+ })
28
+ })
29
+
30
+ // Tool objects are created at runtime, so their `update` method is wrapped to follow renames.
31
+ registerToolCh.end.subscribe(ctx => {
32
+ const tool = ctx.result
33
+ if (!tool || !serverToolRegisteredCh.hasSubscribers) return
34
+
35
+ serverToolRegisteredCh.publish({ tool, name: ctx.arguments[0] })
36
+ shimmer.wrap(tool, 'update', update => function updateWithTrace (updates) {
37
+ const result = update.apply(this, arguments)
38
+ if (updates && Object.hasOwn(updates, 'name')) {
39
+ serverToolRegisteredCh.publish({ tool, name: updates.name || undefined })
40
+ }
41
+ return result
42
+ })
43
+ })
@@ -11,6 +11,7 @@ const {
11
11
  setInstrumentationHttpResource,
12
12
  } = require('../../dd-trace/src/plugins/util/http-otel-semantics')
13
13
  const { RESOURCE_NAME } = require('../../../ext/tags')
14
+ const satisfies = require('../../../vendor/dist/semifies')
14
15
  const { channel, addHook } = require('./helpers/instrument')
15
16
 
16
17
  const startChannel = channel('apm:next:request:start')
@@ -18,6 +19,7 @@ const finishChannel = channel('apm:next:request:finish')
18
19
  const errorChannel = channel('apm:next:request:error')
19
20
  const pageLoadChannel = channel('apm:next:page:load')
20
21
  const bodyParsedChannel = channel('apm:next:body-parsed')
22
+ const responseJsonChannel = channel('apm:next:response:json')
21
23
  const queryParsedChannel = channel('apm:next:query-parsed')
22
24
  const backgroundRevalidationChannel = channel('apm:next:request:background-revalidation')
23
25
 
@@ -42,6 +44,7 @@ const backgroundRevalidationChannel = channel('apm:next:request:background-reval
42
44
  * @property {boolean} [responseFinished]
43
45
  * @property {unknown} [error]
44
46
  * @property {NextRequest} [nextRequest]
47
+ * @property {(error: object) => void} ignoreError
45
48
  *
46
49
  * @typedef {object} ResponseGeneratorContext
47
50
  * @property {boolean} [hasResolved]
@@ -55,6 +58,7 @@ const backgroundRevalidationChannel = channel('apm:next:request:background-reval
55
58
  */
56
59
 
57
60
  const requests = new WeakSet()
61
+ const responseConstructors = new WeakSet()
58
62
  const nodeNextRequestsToNextRequests = new WeakMap()
59
63
  const noFallbackErrorPrototypes = new WeakSet()
60
64
  // Next.js <= 14.2.6
@@ -65,6 +69,19 @@ const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta')
65
69
  const META_IS_MIDDLEWARE = 'middlewareInvoke'
66
70
  const encounteredMiddleware = new WeakSet()
67
71
 
72
+ const abortReasons = new WeakSet()
73
+ const incomingRequests = new WeakSet()
74
+ const blockableApiModules = new WeakMap()
75
+
76
+ /**
77
+ * Keeps an error a subscriber raised to stop the request, such as a blocked request, out of the request errors.
78
+ *
79
+ * @param {object} error
80
+ */
81
+ function ignoreError (error) {
82
+ abortReasons.add(error)
83
+ }
84
+
68
85
  // `next.span_type` value Next.js sets on its own OTel root request span; the whole detection surface.
69
86
  const NEXT_BASE_SERVER_HANDLE_REQUEST = 'BaseServer.handleRequest'
70
87
 
@@ -204,7 +221,7 @@ function getRequestMeta (req, key) {
204
221
  * @param {(ctx: NextRequestContext) => Promise<T>} handler
205
222
  * @param {unknown} [error]
206
223
  * @param {boolean} [finishOnResponse]
207
- * @returns {Promise<T>}
224
+ * @returns {Promise<T | undefined>}
208
225
  */
209
226
  function instrument (req, res, handler, error, finishOnResponse = false) {
210
227
  req = req.originalRequest || req
@@ -214,7 +231,7 @@ function instrument (req, res, handler, error, finishOnResponse = false) {
214
231
  const isMiddleware = req.headers[MIDDLEWARE_HEADER] || getRequestMeta(req, META_IS_MIDDLEWARE)
215
232
  if ((isMiddleware && !encounteredMiddleware.has(req)) || requests.has(req)) {
216
233
  encounteredMiddleware.add(req)
217
- if (error) {
234
+ if (error && !isIgnoredError(error)) {
218
235
  errorChannel.publish({ error })
219
236
  }
220
237
  return handler()
@@ -222,7 +239,7 @@ function instrument (req, res, handler, error, finishOnResponse = false) {
222
239
 
223
240
  requests.add(req)
224
241
 
225
- const ctx = finishOnResponse ? { req, res, finishOnResponse } : { req, res }
242
+ const ctx = finishOnResponse ? { req, res, finishOnResponse, ignoreError } : { req, res, ignoreError }
226
243
  if (finishOnResponse) {
227
244
  const onResponseFinish = () => {
228
245
  res.removeListener('finish', onResponseFinish)
@@ -237,14 +254,20 @@ function instrument (req, res, handler, error, finishOnResponse = false) {
237
254
  const queryIndex = req.url.indexOf('?')
238
255
  if (queryIndex !== -1) {
239
256
  const searchParams = new URLSearchParams(req.url.slice(queryIndex + 1))
240
- const query = {}
241
- for (const key of searchParams.keys()) {
242
- if (!query[key]) {
243
- query[key] = searchParams.getAll(key)
257
+ /** @type {Record<string, string[]>} */
258
+ const query = Object.create(null)
259
+ for (const [key, value] of searchParams) {
260
+ const values = query[key]
261
+ if (values === undefined) {
262
+ query[key] = [value]
263
+ } else {
264
+ values.push(value)
244
265
  }
245
266
  }
246
267
 
247
- queryParsedChannel.publish({ query })
268
+ const abortController = new AbortController()
269
+ queryParsedChannel.publish({ req, res, query, abortController })
270
+ if (abortController.signal.aborted) return /** @type {Promise<undefined>} */ (Promise.resolve())
248
271
  }
249
272
  }
250
273
 
@@ -294,7 +317,7 @@ function publishFinish (ctx, error) {
294
317
  function finish (ctx, result, error) {
295
318
  if (ctx.finishOnResponse) {
296
319
  ctx.handlerFinished = true
297
- if (error && !isNoFallbackError(error)) ctx.error = error
320
+ if (error && !isIgnoredError(error)) ctx.error = error
298
321
  if (!ctx.responseFinished) return
299
322
  }
300
323
 
@@ -306,13 +329,27 @@ function isNoFallbackError (error) {
306
329
  return isNativeError(error) && noFallbackErrorPrototypes.has(Object.getPrototypeOf(error))
307
330
  }
308
331
 
332
+ /**
333
+ * An error that keeps an abort reason as its own `cause`, whether it is a native error or not, comes from the same
334
+ * stop. Reading the own data property runs no getter of the application.
335
+ *
336
+ * @param {unknown} error
337
+ */
338
+ function isIgnoredError (error) {
339
+ if (typeof error !== 'object' || error === null) return false
340
+
341
+ return abortReasons.has(error) ||
342
+ abortReasons.has(Object.getOwnPropertyDescriptor(error, 'cause')?.value) ||
343
+ isNoFallbackError(error)
344
+ }
345
+
309
346
  /**
310
347
  * @param {NextNodeRequest} req
311
348
  * @param {NextRequestContext | undefined} ctx
312
349
  * @param {unknown} error
313
350
  */
314
351
  function publishError (req, ctx, error) {
315
- if (!error || isNoFallbackError(error)) return
352
+ if (!error || isIgnoredError(error)) return
316
353
 
317
354
  if (ctx) {
318
355
  ctx.error = error
@@ -335,6 +372,7 @@ addHook({
335
372
  return function (nodeNextRequest) {
336
373
  const nextRequest = fromNodeNextRequest.apply(this, arguments)
337
374
  nodeNextRequestsToNextRequests.set(nodeNextRequest.originalRequest, nextRequest)
375
+ if (bodyParsedChannel.hasSubscribers) incomingRequests.add(nextRequest)
338
376
  return nextRequest
339
377
  }
340
378
  })
@@ -402,6 +440,7 @@ function wrapAppRouteHandle (handle) {
402
440
  nodeNextRequestsToNextRequests.set(nodeRequest, req)
403
441
  }
404
442
  }
443
+ if (bodyParsedChannel.hasSubscribers) incomingRequests.add(req)
405
444
 
406
445
  return handle.apply(this, arguments)
407
446
  }
@@ -546,9 +585,13 @@ function wrapPagesApiRender (render) {
546
585
  }
547
586
  }
548
587
 
549
- function instrumentPagesApiRuntime (runtime) {
588
+ // Pages API routes run through the compiled runtime from Next.js 13.5, which inlines the body parser and apiResolver.
589
+ function instrumentPagesApiRuntime (runtime, version) {
550
590
  const PagesAPIRouteModule = runtime.PagesAPIRouteModule || runtime.default
551
- instrumentRouteModule(PagesAPIRouteModule, [['render', wrapPagesApiRender]], false)
591
+ const wrappers = [['render', wrapPagesApiRenderBody]]
592
+ // Keep wrapPagesApiRender on its previous >=15.4.1 range; the hook is widened only for the body wrapper.
593
+ if (satisfies(version, '>=15.4.1')) wrappers.push(['render', wrapPagesApiRender])
594
+ instrumentRouteModule(PagesAPIRouteModule, wrappers, false)
552
595
  return runtime
553
596
  }
554
597
 
@@ -561,18 +604,96 @@ function instrumentAppPageRuntime (runtime) {
561
604
  return runtime
562
605
  }
563
606
 
564
- for (const [runtime, instrumentRuntime] of [
565
- ['app-route', instrumentAppRouteRuntime],
566
- ['pages-api', instrumentPagesApiRuntime],
567
- ['app-page', instrumentAppPageRuntime],
568
- ]) {
607
+ for (const [runtime, instrumentRuntime, versions] of /** @type {const} */ ([
608
+ ['app-route', instrumentAppRouteRuntime, '>=15.4.1'],
609
+ ['pages-api', instrumentPagesApiRuntime, '>=13.5'],
610
+ ['app-page', instrumentAppPageRuntime, '>=15.4.1'],
611
+ ])) {
569
612
  addHook({
570
613
  name: 'next',
571
- versions: ['>=15.4.1'],
614
+ versions: [versions],
572
615
  filePattern: String.raw`${COMPILED_RUNTIME_PATH}${runtime}[\w-]*\.runtime\.(?:dev|prod)\.js$`,
573
616
  }, instrumentRuntime)
574
617
  }
575
618
 
619
+ /**
620
+ * @param {Function} handler
621
+ */
622
+ function wrapApiHandler (handler) {
623
+ return function (req, res) {
624
+ const { body } = req
625
+ if (bodyParsedChannel.hasSubscribers && body !== undefined && body !== '') {
626
+ const abortController = new AbortController()
627
+ bodyParsedChannel.publish({ req, res, body, abortController })
628
+ if (abortController.signal.aborted) return
629
+ }
630
+
631
+ return handler.apply(this, arguments)
632
+ }
633
+ }
634
+
635
+ /**
636
+ * Pages API modules expose the handler through a webpack export getter that can't be wrapped in place, so the
637
+ * module is replaced by one that inherits from it with a wrapped handler.
638
+ *
639
+ * @param {{ default?: unknown } | Function} apiModule
640
+ * @returns {{ default?: unknown } | Function}
641
+ */
642
+ function getBlockableApiModule (apiModule) {
643
+ let blockableModule = blockableApiModules.get(apiModule)
644
+ if (blockableModule) return blockableModule
645
+
646
+ const handler = apiModule?.default || apiModule
647
+ if (typeof handler !== 'function') return apiModule
648
+
649
+ blockableModule = Object.create(apiModule, { default: { value: wrapApiHandler(handler) } })
650
+ blockableApiModules.set(apiModule, blockableModule)
651
+ // wrapPagesApiRenderBody stores the replacement as `userland`, so later renders pass it back here: resolve it to
652
+ // itself instead of nesting another handler wrapper.
653
+ blockableApiModules.set(blockableModule, blockableModule)
654
+ return blockableModule
655
+ }
656
+
657
+ /**
658
+ * @param {Function} render
659
+ */
660
+ function wrapPagesApiRenderBody (render) {
661
+ /** @this {{ userland: { default?: unknown } }} */
662
+ return function () {
663
+ if (bodyParsedChannel.hasSubscribers) {
664
+ const blockableModule = getBlockableApiModule(this.userland)
665
+ if (blockableModule !== this.userland) {
666
+ // Next.js 16 exposes `userland` through a prototype getter, so shadow it instead of assigning it.
667
+ Object.defineProperty(this, 'userland', { value: blockableModule, configurable: true, writable: true })
668
+ }
669
+ }
670
+
671
+ return render.apply(this, arguments)
672
+ }
673
+ }
674
+
675
+ /**
676
+ * @param {Function} apiResolver
677
+ */
678
+ function wrapApiResolver (apiResolver) {
679
+ return function (...args) {
680
+ if (bodyParsedChannel.hasSubscribers) {
681
+ args[3] = getBlockableApiModule(args[3])
682
+ }
683
+
684
+ return Reflect.apply(apiResolver, this, args)
685
+ }
686
+ }
687
+
688
+ for (const file of ['dist/server/api-utils.js', 'dist/server/api-utils/node.js']) {
689
+ addHook({ name: 'next', versions: ['>=11.1 <13.5'], file }, apiUtils => {
690
+ const apiUtilsExports = /** @type {{ apiResolver?: Function }} */ (apiUtils)
691
+ if (typeof apiUtilsExports.apiResolver !== 'function') return apiUtils
692
+
693
+ return shimmer.wrap(apiUtilsExports, 'apiResolver', wrapApiResolver, { replaceGetter: true })
694
+ })
695
+ }
696
+
576
697
  addHook({
577
698
  name: 'next',
578
699
  versions: ['>=11.1'],
@@ -638,6 +759,23 @@ addHook({
638
759
  return nextServer
639
760
  })
640
761
 
762
+ /**
763
+ * @param {Request} request
764
+ * @param {unknown} body
765
+ */
766
+ function publishBodyParsed (request, body) {
767
+ if (!bodyParsedChannel.hasSubscribers) return
768
+
769
+ const abortController = incomingRequests.has(request) ? new AbortController() : undefined
770
+ bodyParsedChannel.publish({ body, abortController })
771
+
772
+ if (abortController?.signal.aborted) {
773
+ const { reason } = abortController.signal
774
+ abortReasons.add(reason)
775
+ throw reason
776
+ }
777
+ }
778
+
641
779
  addHook({
642
780
  name: 'next',
643
781
  versions: ['>=13'],
@@ -645,11 +783,25 @@ addHook({
645
783
  }, request => {
646
784
  const requestProto = Object.getPrototypeOf(request.NextRequest.prototype)
647
785
 
786
+ // Next bundles copies of NextResponse, but each delegates JSON serialization to the runtime's native/polyfill
787
+ // Response constructor. That constructor is selected at runtime and has no Next.js source function to rewrite.
788
+ const Response = globalThis.Response
789
+ if (typeof Response?.json === 'function' && !responseConstructors.has(Response)) {
790
+ responseConstructors.add(Response)
791
+ shimmer.wrap(Response, 'json', json => function (body) {
792
+ const response = json.apply(this, arguments)
793
+ if (responseJsonChannel.hasSubscribers) {
794
+ responseJsonChannel.publish({ body, stream: response.body })
795
+ }
796
+ return response
797
+ })
798
+ }
799
+
648
800
  shimmer.massWrap(requestProto, ['text', 'json'], function (originalMethod) {
649
801
  return async function wrappedJson () {
650
802
  const body = await originalMethod.apply(this, arguments)
651
803
 
652
- bodyParsedChannel.publish({ body })
804
+ publishBodyParsed(this, body)
653
805
 
654
806
  return body
655
807
  }
@@ -663,11 +815,23 @@ addHook({
663
815
  if (typeof body.entries === 'function') {
664
816
  normalizedBody = Object.fromEntries(body.entries())
665
817
  }
666
- bodyParsedChannel.publish({ body: normalizedBody })
818
+ publishBodyParsed(this, normalizedBody)
667
819
 
668
820
  return body
669
821
  }
670
822
  })
671
823
 
824
+ shimmer.wrap(requestProto, 'clone', function (originalClone) {
825
+ return function wrappedClone () {
826
+ const clone = originalClone.apply(this, arguments)
827
+
828
+ if (bodyParsedChannel.hasSubscribers && incomingRequests.has(this)) {
829
+ incomingRequests.add(clone)
830
+ }
831
+
832
+ return clone
833
+ }
834
+ })
835
+
672
836
  return request
673
837
  })
@@ -8,7 +8,7 @@ let compileToRegexp
8
8
  /** @type {((pattern: string) => { tokens: object[] } | undefined) | undefined} */
9
9
  let parseTokens
10
10
 
11
- /** @type {((route: string) => ((url: string) => object | undefined) | undefined) | undefined} */
11
+ /** @type {((tokens: object[], options?: object) => ((url: string) => object | undefined) | undefined) | undefined} */
12
12
  let makeMatcher
13
13
 
14
14
  addHook({ name: 'path-to-regexp', versions: ['*'] }, moduleExports => {
@@ -39,9 +39,9 @@ addHook({ name: 'path-to-regexp', versions: ['*'] }, moduleExports => {
39
39
  // `{ tokens }` too, yet its tokens are bare strings rather than typed nodes. Gating on the version
40
40
  // keeps those from installing adapters the consumers would misread.
41
41
  addHook({ name: 'path-to-regexp', versions: ['>=8'] }, moduleExports => {
42
- const { parse, match } = moduleExports
42
+ const { parse, match, TokenData } = moduleExports
43
43
 
44
- if (typeof parse === 'function' && typeof match === 'function') {
44
+ if (typeof parse === 'function' && typeof match === 'function' && typeof TokenData === 'function') {
45
45
  parseTokens = pattern => {
46
46
  let result
47
47
  try {
@@ -52,12 +52,12 @@ addHook({ name: 'path-to-regexp', versions: ['>=8'] }, moduleExports => {
52
52
  if (Array.isArray(result?.tokens)) return result
53
53
  }
54
54
 
55
- makeMatcher = route => {
55
+ makeMatcher = (tokens, options) => {
56
56
  let matcher
57
57
  try {
58
- // Callers read which params matched, never their values: skipping decode is faster and
58
+ // Callers read raw param values only: skipping decode is faster and
59
59
  // stops a malformed escape ('%ZZ') from throwing URIError, which would read as "no match".
60
- matcher = match(route, { decode: false })
60
+ matcher = match(new TokenData(tokens), { ...options, decode: false })
61
61
  } catch {
62
62
  return
63
63
  }
@@ -68,7 +68,7 @@ addHook({ name: 'path-to-regexp', versions: ['>=8'] }, moduleExports => {
68
68
  } catch {
69
69
  return
70
70
  }
71
- return result ? result.params : undefined
71
+ return result || undefined
72
72
  }
73
73
  }
74
74
  }
@@ -98,10 +98,10 @@ function getParse () {
98
98
  }
99
99
 
100
100
  /**
101
- * Returns the host's path-to-regexp 8.x `match` adapter: a factory `route => (url => params)` that
102
- * compiles a route once and returns a matcher yielding the captured params (or undefined on no
103
- * match / unusable route). `undefined` when the host has not loaded an 8.x path-to-regexp.
104
- * @returns {((route: string) => ((url: string) => object | undefined) | undefined) | undefined}
101
+ * Returns the host's path-to-regexp 8.x `match` adapter: a factory `(tokens, options) => (url => match)`
102
+ * that compiles a token sequence once and returns a matcher yielding the matched `{ path, params }` (or
103
+ * undefined on no match / unusable route). `undefined` when the host has not loaded an 8.x path-to-regexp.
104
+ * @returns {((tokens: object[], options?: object) => ((url: string) => object | undefined) | undefined) | undefined}
105
105
  */
106
106
  function getMatch () {
107
107
  return makeMatcher