dd-trace 6.25.0 → 6.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) 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/package.json +33 -30
  8. package/packages/datadog-esbuild/index.js +8 -15
  9. package/packages/datadog-esbuild/src/log.js +2 -29
  10. package/packages/datadog-instrumentations/src/ai.js +6 -1
  11. package/packages/datadog-instrumentations/src/cypress-config.js +20 -9
  12. package/packages/datadog-instrumentations/src/helpers/bundler-esm-exports.js +23 -1
  13. package/packages/datadog-instrumentations/src/helpers/bundler-log.js +38 -0
  14. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +9 -6
  15. package/packages/datadog-instrumentations/src/helpers/fetch.js +51 -6
  16. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +6 -0
  17. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +8 -0
  18. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-client.js +30 -0
  19. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-server.js +23 -0
  20. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +21 -0
  21. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +33 -4
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +30 -0
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +6 -0
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +122 -0
  25. package/packages/datadog-instrumentations/src/microgateway-core.js +1 -2
  26. package/packages/datadog-instrumentations/src/modelcontextprotocol-client.js +21 -0
  27. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +7 -1
  28. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +41 -0
  29. package/packages/datadog-instrumentations/src/next.js +184 -20
  30. package/packages/datadog-instrumentations/src/router.js +35 -12
  31. package/packages/datadog-instrumentations/src/vitest-main.js +10 -2
  32. package/packages/datadog-plugin-aws-lambda/src/arn.js +41 -0
  33. package/packages/datadog-plugin-aws-lambda/src/event-type-guards.js +170 -0
  34. package/packages/datadog-plugin-aws-lambda/src/trigger.js +339 -0
  35. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +7 -0
  36. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +32 -10
  37. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +10 -1
  38. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +4 -0
  39. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +3 -0
  40. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +30 -4
  41. package/packages/datadog-plugin-cypress/src/support.mjs +1353 -0
  42. package/packages/datadog-plugin-express/src/code_origin.js +2 -2
  43. package/packages/datadog-plugin-fastify/src/code_origin.js +2 -2
  44. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -0
  45. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +2 -0
  46. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +7 -0
  47. package/packages/datadog-plugin-google-cloud-pubsub/src/resource-names.js +24 -0
  48. package/packages/datadog-plugin-graphql/src/tools/transforms.js +1 -0
  49. package/packages/datadog-plugin-http/src/client.js +2 -1
  50. package/packages/datadog-plugin-http2/src/client.js +2 -1
  51. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +28 -2
  52. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +1 -0
  53. package/packages/datadog-plugin-mongodb-core/src/query.js +17 -1
  54. package/packages/datadog-plugin-postgres/src/index.js +118 -41
  55. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +18 -8
  56. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +49 -13
  57. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +34 -9
  58. package/packages/datadog-plugin-vitest/src/index.js +3 -2
  59. package/packages/datadog-plugin-ws/src/close.js +3 -5
  60. package/packages/datadog-plugin-ws/src/producer.js +1 -4
  61. package/packages/datadog-plugin-ws/src/receiver.js +3 -5
  62. package/packages/datadog-plugin-ws/src/server.js +44 -13
  63. package/packages/datadog-vite/index.js +537 -0
  64. package/packages/datadog-vite/src/log.js +5 -0
  65. package/packages/datadog-webpack/src/log.js +2 -29
  66. package/packages/dd-trace/src/aiguard/index.js +1 -1
  67. package/packages/dd-trace/src/aiguard/integrations/index.js +6 -5
  68. package/packages/dd-trace/src/appsec/blocking/index.js +17 -1
  69. package/packages/dd-trace/src/appsec/channels.js +7 -0
  70. package/packages/dd-trace/src/appsec/downstream_requests.js +105 -0
  71. package/packages/dd-trace/src/appsec/graphql.js +10 -13
  72. package/packages/dd-trace/src/appsec/handlers/auth.js +1 -3
  73. package/packages/dd-trace/src/appsec/handlers/http-request.js +60 -65
  74. package/packages/dd-trace/src/appsec/handlers/http-response.js +61 -7
  75. package/packages/dd-trace/src/appsec/handlers/payments.js +23 -27
  76. package/packages/dd-trace/src/appsec/index.js +6 -0
  77. package/packages/dd-trace/src/appsec/lambda.js +17 -17
  78. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -4
  79. package/packages/dd-trace/src/appsec/rasp/index.js +8 -1
  80. package/packages/dd-trace/src/appsec/rasp/lfi.js +2 -2
  81. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +7 -17
  82. package/packages/dd-trace/src/appsec/rasp/ssrf.js +80 -16
  83. package/packages/dd-trace/src/appsec/rasp/utils.js +33 -3
  84. package/packages/dd-trace/src/appsec/recommended.json +70 -3
  85. package/packages/dd-trace/src/appsec/reporter.js +9 -0
  86. package/packages/dd-trace/src/appsec/sdk/set_user.js +3 -3
  87. package/packages/dd-trace/src/appsec/sdk/track_event.js +4 -4
  88. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +1 -1
  89. package/packages/dd-trace/src/appsec/user_tracking.js +6 -8
  90. package/packages/dd-trace/src/appsec/waf/index.js +65 -6
  91. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +33 -38
  92. package/packages/dd-trace/src/appsec/waf/waf_manager.js +18 -2
  93. package/packages/dd-trace/src/config/generated-config-types.d.ts +4 -2
  94. package/packages/dd-trace/src/config/index.js +46 -26
  95. package/packages/dd-trace/src/config/parsers.js +35 -0
  96. package/packages/dd-trace/src/config/remote-config-layers.js +38 -0
  97. package/packages/dd-trace/src/config/remote_config.js +2 -1
  98. package/packages/dd-trace/src/config/supported-configurations.json +14 -6
  99. package/packages/dd-trace/src/datastreams/fnv.js +27 -0
  100. package/packages/dd-trace/src/datastreams/pathway.js +113 -28
  101. package/packages/dd-trace/src/datastreams/processor.js +5 -4
  102. package/packages/dd-trace/src/debugger/config.js +1 -1
  103. package/packages/dd-trace/src/debugger/devtools_client/request-options.js +7 -9
  104. package/packages/dd-trace/src/debugger/devtools_client/send.js +1 -1
  105. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  106. package/packages/dd-trace/src/debugger/devtools_client/tags.js +1 -1
  107. package/packages/dd-trace/src/debugger/index.js +2 -2
  108. package/packages/dd-trace/src/debugger/inspect-segment.js +3 -2
  109. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +4 -1
  110. package/packages/dd-trace/src/debugger/probe_sampler.js +39 -17
  111. package/packages/dd-trace/src/debugger/unsupported-runtime.js +2 -0
  112. package/packages/dd-trace/src/git_metadata.js +2 -1
  113. package/packages/dd-trace/src/index.js +6 -3
  114. package/packages/dd-trace/src/lambda/facade.js +6 -5
  115. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +54 -3
  116. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +81 -1
  117. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +3 -0
  118. package/packages/dd-trace/src/openfeature/configuration_source.js +20 -0
  119. package/packages/dd-trace/src/plugins/ci_plugin.js +104 -9
  120. package/packages/dd-trace/src/plugins/index.js +2 -0
  121. package/packages/dd-trace/src/plugins/util/ci.js +34 -0
  122. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +9 -14
  123. package/packages/dd-trace/src/plugins/util/test.js +28 -1
  124. package/packages/dd-trace/src/plugins/util/url.js +8 -5
  125. package/packages/dd-trace/src/plugins/util/user-provided-git.js +4 -4
  126. package/packages/dd-trace/src/process-tags/index.js +1 -1
  127. package/packages/dd-trace/src/profiler.js +74 -12
  128. package/packages/dd-trace/src/profiling/profiler.js +30 -2
  129. package/packages/dd-trace/src/profiling/profilers/space.js +3 -1
  130. package/packages/dd-trace/src/profiling/profilers/wall.js +4 -4
  131. package/packages/dd-trace/src/profiling/remote-config.js +354 -0
  132. package/packages/dd-trace/src/profiling/runtime-capabilities.js +11 -0
  133. package/packages/dd-trace/src/propagation-hash/index.js +7 -0
  134. package/packages/dd-trace/src/proxy.js +13 -1
  135. package/vendor/dist/@opentelemetry/core/LICENSE +11 -0
  136. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  137. package/vite.d.ts +7 -0
  138. package/vite.js +3 -0
  139. package/lambda.d.ts +0 -39
  140. package/lambda.js +0 -3
  141. package/packages/datadog-plugin-cypress/src/support.js +0 -1348
@@ -0,0 +1,537 @@
1
+ 'use strict'
2
+
3
+ const fs = require('node:fs')
4
+ const { createRequire } = require('node:module')
5
+ const path = require('node:path')
6
+
7
+ const {
8
+ createEsmResolver,
9
+ createEsmWrapper,
10
+ processModule,
11
+ } = require('../datadog-instrumentations/src/helpers/bundler-esm-exports')
12
+ const {
13
+ classify,
14
+ instrument,
15
+ packagePathPattern,
16
+ } = require('../datadog-instrumentations/src/helpers/bundler-transform')
17
+ const { getGitMetadataBanner } = require('../datadog-instrumentations/src/helpers/bundler-utils')
18
+ const { getValueFromEnvSources } = require('../dd-trace/src/config/helper')
19
+ const log = require('./src/log')
20
+
21
+ const PLUGIN_NAME = 'datadog-vite'
22
+ // Ids starting with `\0dd-trace-vite:` are reserved for the wrappers this plugin generates to intercept the exports
23
+ // of ES modules, followed by the id of the wrapped module.
24
+ const GENERATED_ID_PREFIX = '\0dd-trace-vite:'
25
+ const LOAD_ID_PATTERN = /^\0dd-trace-vite:/
26
+ // Relative, absolute and package `imports` specifiers may resolve to an instrumented file, bare specifiers only when
27
+ // they name an instrumented package.
28
+ const RESOLVE_ID_PATTERN = new RegExp(String.raw`^(?:[./#]|[A-Za-z]:[/\\])|${packagePathPattern.source}`)
29
+ const NODE_MODULES = '/node_modules/'
30
+ const TRACER_DIRECTORY = `${fs.realpathSync(path.join(__dirname, '..', '..')).replaceAll('\\', '/')}/`
31
+ // Optional dependencies of the tracer, required lazily. They must stay out of the bundle: some are native addons and
32
+ // any of them may be missing at runtime.
33
+ const OPTIONAL_DEPENDENCY_PATTERN =
34
+ /^(@datadog\/(?:libdatadog(?:-extras)?|native-appsec|native-iast-taint-tracking|native-metrics|pprof|wasm-js-rewriter)|@opentelemetry\/api(?:-logs)?|oxc-parser)(?:\/|$)/
35
+ // Pure JavaScript optional dependencies the application may import too. When installed, they are bundled, so the
36
+ // tracer and the application share one copy that does not need to be deployed next to the bundle.
37
+ const BUNDLED_WHEN_INSTALLED = ['@opentelemetry/api', '@opentelemetry/api-logs']
38
+ // Rollup leaves `require`, `__filename` and `__dirname` as free variables in ESM output, where Node.js lacks them.
39
+ // Rollup reserves these names in every chunk, so declaring them cannot collide with bundled code, and keeping them
40
+ // chunk-local resolves each chunk against its own location instead of whichever bundle loaded first.
41
+ const ESM_COMMONJS_BINDINGS = 'import { createRequire as $dd_createRequire } from \'node:module\';\n' +
42
+ 'import { fileURLToPath as $dd_fileURLToPath } from \'node:url\';\n' +
43
+ 'import { dirname as $dd_dirname } from \'node:path\';\n' +
44
+ 'const require = $dd_createRequire(import.meta.url);\n' +
45
+ 'const __filename = $dd_fileURLToPath(import.meta.url);\n' +
46
+ 'const __dirname = $dd_dirname(__filename);\n'
47
+ const ESM_FORMATS = new Set(['es', 'esm', 'module'])
48
+ const mergedFunctions = new WeakSet()
49
+
50
+ /**
51
+ * @typedef {(id: string, parentId: string | undefined, isResolved: boolean) => unknown} ExternalFunction
52
+ * @typedef {string | RegExp | ExternalFunction | Array<string | RegExp | ExternalFunction>} External
53
+ * @typedef {string | ((chunk: object) => string | Promise<string>)} Addon
54
+ * @typedef {{ format?: string, intro?: Addon, keepNames?: boolean }} OutputOptions
55
+ * @typedef {{ external?: External, output?: OutputOptions | OutputOptions[] }} BundlerOptions
56
+ * @typedef {{
57
+ * commonjsOptions?: { ignore?: string[] | ((id: string) => boolean) },
58
+ * lib?: unknown,
59
+ * minify?: boolean | string,
60
+ * rolldownOptions?: BundlerOptions,
61
+ * rollupOptions?: BundlerOptions,
62
+ * ssr?: boolean | string,
63
+ * terserOptions?: { keep_classnames?: unknown, keep_fnames?: unknown },
64
+ * }} BuildOptions
65
+ * @typedef {{
66
+ * build: BuildOptions,
67
+ * builder?: { sharedConfigBuild?: boolean },
68
+ * environments: Record<string, { build: BuildOptions, consumer: string } | undefined>,
69
+ * esbuild: false | { keepNames?: boolean },
70
+ * }} ResolvedConfig
71
+ * @typedef {{ meta?: { rolldownVersion?: string } } | undefined} HookContext
72
+ * @typedef {{ warn: (message: string) => void }} TransformContext
73
+ * @typedef {{ name: string, config: { build: BuildOptions, consumer: string } }} Environment
74
+ * @typedef {{ external?: boolean | string, id: string }} ResolvedId
75
+ * @typedef {{ isEntry?: boolean, skipSelf?: boolean }} ResolveOptions
76
+ * @typedef {{
77
+ * environment?: object,
78
+ * resolve: (source: string, importer: string | undefined, options: ResolveOptions) => Promise<ResolvedId | null>,
79
+ * warn: (message: string) => void,
80
+ * }} ResolveContext
81
+ */
82
+
83
+ /**
84
+ * Creates the Datadog plugin for Vite builds producing Node.js code.
85
+ */
86
+ function datadogVite () {
87
+ const injectGitMetadata = getValueFromEnvSources('DD_BUNDLER_INJECT_GIT_METADATA') !== false
88
+ const installed = getInstalledDependencies()
89
+ /** @type {WeakMap<object, EsmInterception>} */
90
+ const interceptions = new WeakMap()
91
+ const defaultEnvironment = {}
92
+ /** @type {string|undefined} */
93
+ let gitIntro
94
+
95
+ if (!injectGitMetadata) log.debug('Skipping git metadata injection (DD_BUNDLER_INJECT_GIT_METADATA=false)')
96
+
97
+ /**
98
+ * @param {{ environment?: object }} context
99
+ */
100
+ function getInterception (context) {
101
+ const environment = context.environment ?? defaultEnvironment
102
+ let interception = interceptions.get(environment)
103
+ if (!interception) {
104
+ interception = new EsmInterception()
105
+ interceptions.set(environment, interception)
106
+ }
107
+ return interception
108
+ }
109
+
110
+ return {
111
+ name: PLUGIN_NAME,
112
+ apply: 'build',
113
+ enforce: 'pre',
114
+
115
+ /**
116
+ * Vite has normalized each environment's defaults, but has not created its CommonJS plugins yet.
117
+ * The shared esbuild options are read later, when chunks are rendered.
118
+ *
119
+ * @this {HookContext}
120
+ * @param {ResolvedConfig} config
121
+ */
122
+ configResolved (config) {
123
+ // Older versions lack the Environment API hooks, so the build would silently miss required configuration.
124
+ if (!config.environments) throw new Error('dd-trace/vite requires Vite 6 or newer. Refusing to bundle.')
125
+ const rolldown = isRolldown(this)
126
+ for (const [name, environment] of Object.entries(config.environments)) {
127
+ if (environment && isNodeBuild(environment.consumer, environment.build)) {
128
+ configureBuild(name, environment.build, rolldown, installed)
129
+ }
130
+ }
131
+ if (rolldown || !config.esbuild || !needsEsbuildKeepNames(config)) return
132
+ config.esbuild.keepNames = true
133
+ log.debug('Enabled esbuild keepNames so minification preserves function and class names')
134
+ },
135
+
136
+ /**
137
+ * Rolldown defines its own `require` in ESM output. Every chunk gets the bindings, since free variables in one
138
+ * chunk cannot see declarations in another.
139
+ *
140
+ * @this {HookContext}
141
+ * @param {OutputOptions} output
142
+ */
143
+ outputOptions (output) {
144
+ if (isRolldown(this) || !ESM_FORMATS.has(output.format ?? 'es')) return
145
+ return { ...output, intro: prependAddon(ESM_COMMONJS_BINDINGS, output.intro) }
146
+ },
147
+
148
+ /**
149
+ * @param {Environment} environment
150
+ */
151
+ applyToEnvironment (environment) {
152
+ const { build, consumer } = environment.config
153
+ return isNodeBuild(consumer, build)
154
+ },
155
+
156
+ resolveId: {
157
+ filter: { id: RESOLVE_ID_PATTERN },
158
+ /**
159
+ * @this {ResolveContext}
160
+ * @param {string} source
161
+ * @param {string} [importer]
162
+ * @param {ResolveOptions} [options]
163
+ */
164
+ handler (source, importer, options) {
165
+ return getInterception(this).resolveId(this, source, importer, options)
166
+ },
167
+ },
168
+
169
+ load: {
170
+ filter: { id: LOAD_ID_PATTERN },
171
+ /**
172
+ * @this {ResolveContext}
173
+ * @param {string} id
174
+ */
175
+ handler (id) {
176
+ return isWrapperId(id) ? getInterception(this).load(this, id.slice(GENERATED_ID_PREFIX.length)) : undefined
177
+ },
178
+ },
179
+
180
+ /**
181
+ * @this {{ environment?: object }}
182
+ */
183
+ buildEnd () {
184
+ return interceptions.get(this.environment ?? defaultEnvironment)?.buildEnd()
185
+ },
186
+
187
+ transform: {
188
+ // Vite versions without hook filters call the handler for every module, which checks the id again.
189
+ filter: { id: packagePathPattern },
190
+ /**
191
+ * @this {TransformContext}
192
+ * @param {string} code
193
+ * @param {string} id
194
+ */
195
+ handler (code, id) {
196
+ const result = isInstrumentable(id)
197
+ ? instrument({ source: code, resourcePath: id, warn: warning => this.warn(warning.message) })
198
+ : undefined
199
+ return result && result.code !== code ? { code: result.code, map: result.map ?? null } : undefined
200
+ },
201
+ },
202
+
203
+ /**
204
+ * Runs before the chunk's own code: in CommonJS output after the strict-mode directive and before the hoisted
205
+ * `require` calls, unlike a banner, which would precede the directive.
206
+ *
207
+ * @param {{ isEntry: boolean }} chunk
208
+ */
209
+ intro (chunk) {
210
+ if (!injectGitMetadata || !chunk.isEntry) return ''
211
+ gitIntro ??= getGitMetadataBanner(log)
212
+ return gitIntro
213
+ },
214
+ }
215
+ }
216
+
217
+ /**
218
+ * @param {string} id
219
+ */
220
+ function isInstrumentable (id) {
221
+ return id.charCodeAt(0) !== 0 && !id.includes('?') && id.includes(NODE_MODULES) &&
222
+ !id.startsWith(TRACER_DIRECTORY) && packagePathPattern.test(id)
223
+ }
224
+
225
+ /**
226
+ * @param {string} id
227
+ */
228
+ function isWrapperId (id) {
229
+ return id.startsWith(GENERATED_ID_PREFIX)
230
+ }
231
+
232
+ /**
233
+ * ES module namespaces are read-only, so hooks cannot replace the exports of ES modules. Importers of ES modules that
234
+ * hooks instrument are redirected to a wrapper module re-exporting them through bindings the hooks can replace.
235
+ * Orchestrion targets are rewritten in place instead. State is kept per environment.
236
+ */
237
+ class EsmInterception {
238
+ /**
239
+ * Kept across watch mode rebuilds, which load cached modules without resolving their imports again.
240
+ *
241
+ * @type {Map<string, string>}
242
+ */
243
+ #specifiers = new Map()
244
+ /** @type {Map<string, Promise<string[] | undefined>>} */
245
+ #exports = new Map()
246
+ /** @type {Map<string, string>} */
247
+ #moduleSources = new Map()
248
+ /** @type {ReturnType<typeof createEsmResolver> | undefined} */
249
+ #resolver
250
+
251
+ /**
252
+ * @param {ResolveContext} context
253
+ * @param {string} source
254
+ * @param {string | undefined} importer
255
+ * @param {ResolveOptions | undefined} options
256
+ */
257
+ resolveId (context, source, importer, options) {
258
+ if (importer === undefined || options?.isEntry) return
259
+ if (isWrapperId(importer)) {
260
+ // Imports from generated modules resolve relative to the original. The wrapper must reach that module unwrapped.
261
+ return context.resolve(source, importer.slice(GENERATED_ID_PREFIX.length), { ...options, skipSelf: true })
262
+ }
263
+ if (!mayResolveToTarget(source, importer)) return
264
+ return context.resolve(source, importer, { ...options, skipSelf: true })
265
+ .then(resolved => this.#redirect(context, source, importer, resolved))
266
+ }
267
+
268
+ /**
269
+ * @param {ResolveContext} context
270
+ * @param {string} id The id of the wrapped module.
271
+ */
272
+ load (context, id) {
273
+ return this.#getExports(context, id).then(setters => {
274
+ if (!setters) throw new Error(`Could not analyze the exports of ${id}`)
275
+ return createEsmWrapper({
276
+ path: id,
277
+ specifier: this.#specifiers.get(id),
278
+ setters,
279
+ })
280
+ })
281
+ }
282
+
283
+ buildEnd () {
284
+ const resolver = this.#resolver
285
+ this.#exports.clear()
286
+ this.#moduleSources.clear()
287
+ this.#resolver = undefined
288
+ return resolver?.close().catch(error => {
289
+ log.debug('The ESM resolver failed: %s', error instanceof Error ? error.message : String(error))
290
+ })
291
+ }
292
+
293
+ /**
294
+ * @param {ResolveContext} context
295
+ * @param {string} source
296
+ * @param {string} importer
297
+ * @param {ResolvedId | null} resolved
298
+ */
299
+ #redirect (context, source, importer, resolved) {
300
+ // A module importing itself must not reach its wrapper, which would import it in turn.
301
+ if (!resolved || resolved.external || resolved.id === importer || !isInstrumentable(resolved.id)) return resolved
302
+ const { id } = resolved
303
+ const kind = classify({
304
+ resourcePath: id,
305
+ // Package root hooks only apply to imports of the package name.
306
+ request: isBareSpecifier(source) ? source : undefined,
307
+ warn: warning => context.warn(warning.message),
308
+ })
309
+ if (kind !== 'esm-intercept') return resolved
310
+ this.#specifiers.set(id, source)
311
+ return this.#getExports(context, id).then(setters => {
312
+ if (!setters) return resolved
313
+ // IITM registration must run even when importers only re-export the module.
314
+ return { id: GENERATED_ID_PREFIX + id, moduleSideEffects: true }
315
+ })
316
+ }
317
+
318
+ /**
319
+ * @param {ResolveContext} context
320
+ * @param {string} id
321
+ * @returns {Promise<string[] | undefined>}
322
+ */
323
+ #getExports (context, id) {
324
+ const cached = this.#exports.get(id)
325
+ if (cached) return cached
326
+ this.#resolver ??= createEsmResolver()
327
+ const exports = /** @type {Promise<string[] | undefined>} */ (processModule({
328
+ path: id,
329
+ context: { format: 'module' },
330
+ moduleSources: this.#moduleSources,
331
+ resolver: this.#resolver,
332
+ }).then(setters => [...setters.values()], error => {
333
+ context.warn(`Skipped intercepting the exports of ${id}: ${error instanceof Error ? error.message : error}`)
334
+ }))
335
+ this.#exports.set(id, exports)
336
+ return exports
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Relative specifiers can only resolve to an instrumented file when imported from an instrumented package.
342
+ *
343
+ * @param {string} source
344
+ * @param {string} importer
345
+ */
346
+ function mayResolveToTarget (source, importer) {
347
+ if (source.charCodeAt(0) === 0 || source.includes('?')) return false
348
+ return source[0] === '.' || source[0] === '#' ? isInstrumentable(importer) : packagePathPattern.test(source)
349
+ }
350
+
351
+ /**
352
+ * @param {string} source
353
+ */
354
+ function isBareSpecifier (source) {
355
+ return source[0] !== '.' && source[0] !== '/' && source[0] !== '#' && !/^[A-Za-z]:[/\\]/.test(source)
356
+ }
357
+
358
+ /**
359
+ * @param {HookContext} context
360
+ */
361
+ function isRolldown (context) {
362
+ return Boolean(context?.meta?.rolldownVersion)
363
+ }
364
+
365
+ /**
366
+ * Electron preload, renderer and other client builds are never instrumented.
367
+ *
368
+ * @param {string | undefined} consumer
369
+ * @param {BuildOptions} [build]
370
+ */
371
+ function isNodeBuild (consumer, build) {
372
+ return consumer === 'server' || Boolean(build?.ssr) || Boolean(build?.lib)
373
+ }
374
+
375
+ /**
376
+ * Whether a built environment producing Node.js code minifies with esbuild. A builder sharing the configuration
377
+ * shares the esbuild options too, so client environments built alongside such an environment keep names as well.
378
+ *
379
+ * @param {ResolvedConfig} config
380
+ */
381
+ function needsEsbuildKeepNames (config) {
382
+ if (config.esbuild && config.esbuild.keepNames !== undefined) return false
383
+ // Each environment resolves its own configuration, whose build options are the environment's.
384
+ if (!config.builder?.sharedConfigBuild) return isMinifiedByEsbuild(undefined, config.build)
385
+ return Object.values(config.environments).some(environment =>
386
+ environment && isMinifiedByEsbuild(environment.consumer, environment.build))
387
+ }
388
+
389
+ /**
390
+ * @param {string | undefined} consumer
391
+ * @param {BuildOptions} build
392
+ */
393
+ function isMinifiedByEsbuild (consumer, build) {
394
+ return isNodeBuild(consumer, build) && build.minify === 'esbuild'
395
+ }
396
+
397
+ /**
398
+ * Resolves the optional dependencies that are bundled when installed the way the bundled tracer would.
399
+ *
400
+ * @returns {Set<string>}
401
+ */
402
+ function getInstalledDependencies () {
403
+ const tracerRequire = createRequire(`${TRACER_DIRECTORY}index.js`)
404
+ const installed = new Set()
405
+ for (const name of BUNDLED_WHEN_INSTALLED) {
406
+ try {
407
+ tracerRequire.resolve(name)
408
+ installed.add(name)
409
+ } catch {
410
+ log.debug('Keeping %s external to the bundle: it is not installed', name)
411
+ }
412
+ }
413
+ return installed
414
+ }
415
+
416
+ /**
417
+ * @param {string} id
418
+ * @param {Set<string>} installed
419
+ */
420
+ function isOptionalDependency (id, installed) {
421
+ const match = OPTIONAL_DEPENDENCY_PATTERN.exec(id)
422
+ return match !== null && !installed.has(match[1])
423
+ }
424
+
425
+ /**
426
+ * @param {string | undefined} id
427
+ */
428
+ function isTracerModule (id) {
429
+ if (id === undefined) return false
430
+ const normalized = id.replaceAll('\\', '/')
431
+ return normalized.startsWith(TRACER_DIRECTORY) || normalized.includes('/node_modules/dd-trace/')
432
+ }
433
+
434
+ /**
435
+ * @param {Addon} code
436
+ * @param {Addon | undefined} addon
437
+ * @returns {Addon}
438
+ */
439
+ function prependAddon (code, addon) {
440
+ if (typeof addon === 'function') return async chunk => `${code}${await addon(chunk)}`
441
+ return addon ? `${code}${addon}` : code
442
+ }
443
+
444
+ /**
445
+ * @param {string} name
446
+ * @param {BuildOptions} build
447
+ * @param {boolean} rolldown
448
+ * @param {Set<string>} installed
449
+ */
450
+ function configureBuild (name, build, rolldown, installed) {
451
+ const { minify } = build
452
+ if (rolldown) {
453
+ // Vite 8 aliases `rollupOptions` to `rolldownOptions`; reuse whichever object the configuration already has.
454
+ const options = build.rolldownOptions ?? build.rollupOptions ?? (build.rolldownOptions = {})
455
+ options.external = mergeExternal(options.external, installed)
456
+ if (minify) enableOutputKeepNames(name, options)
457
+ } else {
458
+ // Rollup hoists external `require` calls to the top of the chunk, which would load optional dependencies eagerly
459
+ // and crash when they are missing. Ignored `require` calls stay where they are. The option only receives the
460
+ // required id, so it also applies to other bundled CommonJS modules; those dependencies are native addons or
461
+ // missing, which these modules could not bundle either.
462
+ const commonjsOptions = build.commonjsOptions ??= {}
463
+ commonjsOptions.ignore = mergeIgnore(commonjsOptions.ignore, installed)
464
+ }
465
+ if (minify === 'terser') {
466
+ const terserOptions = build.terserOptions ??= {}
467
+ terserOptions.keep_classnames ??= true
468
+ terserOptions.keep_fnames ??= true
469
+ log.debug('Enabled terser keep_classnames and keep_fnames for the %s environment', name)
470
+ }
471
+ }
472
+
473
+ /**
474
+ * @param {string} name
475
+ * @param {BundlerOptions} options
476
+ */
477
+ function enableOutputKeepNames (name, options) {
478
+ options.output ??= {}
479
+ for (const output of Array.isArray(options.output) ? options.output : [options.output]) {
480
+ if (output.keepNames !== undefined) continue
481
+ output.keepNames = true
482
+ log.debug('Enabled output keepNames for the %s environment', name)
483
+ }
484
+ }
485
+
486
+ /**
487
+ * Only imports from the tracer are externalized, so the application still bundles its own imports of these packages.
488
+ *
489
+ * @param {External | null | undefined} external
490
+ * @param {Set<string>} installed
491
+ * @returns {ExternalFunction}
492
+ */
493
+ function mergeExternal (external, installed) {
494
+ if (typeof external === 'function' && mergedFunctions.has(external)) return external
495
+ const user = external === undefined || external === null ? undefined : matchAny(external)
496
+ /** @type {ExternalFunction} */
497
+ const merged = (id, parentId, isResolved) =>
498
+ (isOptionalDependency(id, installed) && isTracerModule(parentId)) || Boolean(user?.(id, parentId, isResolved))
499
+ mergedFunctions.add(merged)
500
+ return merged
501
+ }
502
+
503
+ /**
504
+ * Vite concatenates arrays when merging configurations, so a function returned by one plugin or the user can end up
505
+ * in an array, which the bundler rejects.
506
+ *
507
+ * @param {External} external
508
+ * @returns {ExternalFunction}
509
+ */
510
+ function matchAny (external) {
511
+ if (typeof external === 'function') return external
512
+ const externals = Array.isArray(external) ? external : [external]
513
+ return (id, parentId, isResolved) => externals.some(entry => {
514
+ if (typeof entry === 'function') return entry(id, parentId, isResolved)
515
+ return typeof entry === 'string' ? entry === id : entry.test(id)
516
+ })
517
+ }
518
+
519
+ /**
520
+ * @param {string[] | ((id: string) => boolean) | undefined} ignore
521
+ * @param {Set<string>} installed
522
+ * @returns {(id: string) => boolean}
523
+ */
524
+ function mergeIgnore (ignore, installed) {
525
+ if (typeof ignore === 'function' && mergedFunctions.has(ignore)) return ignore
526
+ let merged
527
+ if (typeof ignore === 'function') {
528
+ merged = (/** @type {string} */ id) => isOptionalDependency(id, installed) || ignore(id)
529
+ } else {
530
+ const ids = new Set(ignore)
531
+ merged = (/** @type {string} */ id) => isOptionalDependency(id, installed) || ids.has(id)
532
+ }
533
+ mergedFunctions.add(merged)
534
+ return merged
535
+ }
536
+
537
+ module.exports = { datadogVite }
@@ -0,0 +1,5 @@
1
+ 'use strict'
2
+
3
+ const createBundlerLog = require('../../datadog-instrumentations/src/helpers/bundler-log')
4
+
5
+ module.exports = createBundlerLog('vite')
@@ -1,32 +1,5 @@
1
1
  'use strict'
2
2
 
3
- const { format } = require('util')
3
+ const createBundlerLog = require('../../datadog-instrumentations/src/helpers/bundler-log')
4
4
 
5
- // eslint-disable-next-line eslint-rules/eslint-process-env
6
- const DD_TRACE_DEBUG = (process.env.DD_TRACE_DEBUG || '').trim().toLowerCase()
7
- const DEBUG = DD_TRACE_DEBUG === 'true' || DD_TRACE_DEBUG === '1'
8
-
9
- const noop = () => {}
10
-
11
- const formatWithLogPrefix = (prefix, str, ...args) => {
12
- if (typeof str === 'string') {
13
- return format(`${prefix} ${str}`, ...args)
14
- }
15
- return format(prefix, str, ...args)
16
- }
17
-
18
- module.exports = DEBUG
19
- ? {
20
- debug (...args) {
21
- // eslint-disable-next-line no-console
22
- console.log(formatWithLogPrefix('[dd-trace/webpack]', ...args))
23
- },
24
- warn (...args) {
25
- // eslint-disable-next-line no-console
26
- console.warn(formatWithLogPrefix('[dd-trace/webpack] Warning:', ...args))
27
- },
28
- }
29
- : {
30
- debug: noop,
31
- warn: noop,
32
- }
5
+ module.exports = createBundlerLog('webpack')
@@ -21,7 +21,7 @@ function enable (tracer, config) {
21
21
  const analyzeStreamResponses = config.aiguard.DD_AI_GUARD_ANALYZE_STREAM_RESPONSES_ENABLED
22
22
 
23
23
  incomingHttpRequestStart.subscribe(onIncomingHttpRequestStart)
24
- integrations.enable(aiguard, block, analyzeStreamResponses)
24
+ integrations.enable(aiguard, block, analyzeStreamResponses, config.aiguard.DD_AI_GUARD_DISABLED_INTEGRATIONS)
25
25
 
26
26
  isEnabled = true
27
27
  } catch (err) {
@@ -7,18 +7,19 @@ const vercelAi = require('./vercel-ai')
7
7
  let isEnabled = false
8
8
 
9
9
  /**
10
- * Enables all AI Guard provider integrations.
10
+ * Enables AI Guard provider integrations except those explicitly disabled.
11
11
  *
12
12
  * @param {object} aiguard
13
13
  * @param {boolean} block
14
14
  * @param {boolean} analyzeStreamResponses
15
+ * @param {string[]} [disabledIntegrations]
15
16
  */
16
- function enable (aiguard, block, analyzeStreamResponses) {
17
+ function enable (aiguard, block, analyzeStreamResponses, disabledIntegrations = []) {
17
18
  if (isEnabled) return
18
19
 
19
- anthropic.enable(aiguard, block, analyzeStreamResponses)
20
- openai.enable(aiguard, block, analyzeStreamResponses)
21
- vercelAi.enable(aiguard, block, analyzeStreamResponses)
20
+ if (!disabledIntegrations.includes('anthropic')) anthropic.enable(aiguard, block, analyzeStreamResponses)
21
+ if (!disabledIntegrations.includes('openai')) openai.enable(aiguard, block, analyzeStreamResponses)
22
+ if (!disabledIntegrations.includes('ai')) vercelAi.enable(aiguard, block, analyzeStreamResponses)
22
23
 
23
24
  isEnabled = true
24
25
  }
@@ -40,6 +40,14 @@ const responseBlockedSet = new WeakSet()
40
40
 
41
41
  const blockDelegations = new WeakMap()
42
42
 
43
+ // Abort reason for instrumentations that must reject an operation the application awaits.
44
+ class BlockedRequestError extends Error {
45
+ constructor () {
46
+ super('Request blocked by Datadog App and API Protection')
47
+ this.name = 'BlockedRequestError'
48
+ }
49
+ }
50
+
43
51
  const specificBlockingTypes = {
44
52
  GRAPHQL: 'graphqlJson',
45
53
  }
@@ -128,6 +136,14 @@ function block (req, res, rootSpan, abortController, actionParameters = defaultB
128
136
  throw new Error('Headers have already been sent')
129
137
  }
130
138
 
139
+ // A destroyed response accepts the writes without sending anything to the client.
140
+ if (res.destroyed) {
141
+ log.warn('[ASM] Cannot send blocking response when the response has been destroyed')
142
+ abortController?.abort(new BlockedRequestError())
143
+
144
+ throw new Error('Response has been destroyed')
145
+ }
146
+
131
147
  const { body, headers, statusCode } = getBlockingData(req, null, actionParameters)
132
148
 
133
149
  for (const headerName of res.getHeaderNames()) {
@@ -146,7 +162,7 @@ function block (req, res, rootSpan, abortController, actionParameters = defaultB
146
162
  // The blocking response is final, but frameworks may keep running and rewrite the status (Next.js restores it).
147
163
  Object.defineProperty(res, 'statusCode', { configurable: true, enumerable: true, get: () => statusCode, set () {} })
148
164
 
149
- abortController?.abort()
165
+ abortController?.abort(new BlockedRequestError())
150
166
 
151
167
  return true
152
168
  } catch (err) {
@@ -20,8 +20,11 @@ module.exports = {
20
20
  fastifyPathParams: dc.channel('datadog:fastify:path-params:finish'),
21
21
  fastifyQueryParams: dc.channel('datadog:fastify:query-params:finish'),
22
22
  fastifyResponseChannel: dc.channel('datadog:fastify:response:finish'),
23
+ fetchRequestStart: dc.channel('tracing:apm:fetch:request:start'),
23
24
  fsOperationStart: dc.channel('apm:fs:operation:start'),
24
25
  graphqlMiddlewareChannel: dc.tracingChannel('datadog:apollo:middleware'),
26
+ httpClientRequestFinish: dc.channel('apm:http:client:request:finish'),
27
+ httpClientRequestError: dc.channel('apm:http:client:request:error'),
25
28
  httpClientRequestStart: dc.channel('apm:http:client:request:start'),
26
29
  httpClientResponseStart: dc.channel('apm:http:client:response:start'),
27
30
  httpClientResponseFinish: dc.channel('apm:http:client:response:finish'),
@@ -34,6 +37,10 @@ module.exports = {
34
37
  mysql2OuterQueryStart: dc.channel('datadog:mysql2:outerquery:start'),
35
38
  nextBodyParsed: dc.channel('apm:next:body-parsed'),
36
39
  nextQueryParsed: dc.channel('apm:next:query-parsed'),
40
+ nextRequestStart: dc.channel('apm:next:request:start'),
41
+ nextResponseBody: dc.channel('tracing:orchestrion:next:responseBody:start'),
42
+ nextJsonResponse: dc.channel('apm:next:response:json'),
43
+ nextAppRouteResponse: dc.channel('tracing:orchestrion:next:appRouteResponse:asyncEnd'),
37
44
  passportUser: dc.channel('datadog:passport:deserializeUser:finish'),
38
45
  passportVerify: dc.channel('datadog:passport:verify:finish'),
39
46
  pgPoolQueryStart: dc.channel('datadog:pg:pool:query:start'),