dd-trace 6.23.0 → 6.24.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 (168) hide show
  1. package/LICENSE-3rdparty.csv +0 -1
  2. package/ci/cypress/support.js +15 -1
  3. package/ci/diagnose.js +4 -4
  4. package/ci/test-annotations.d.ts +5 -0
  5. package/ci/test-annotations.js +5 -0
  6. package/ci/test-optimization-validation/approval-artifacts.js +2 -2
  7. package/ci/test-optimization-validation/approval.js +2 -2
  8. package/ci/test-optimization-validation/artifact-id.js +2 -3
  9. package/ci/test-optimization-validation/ci-package-scripts.js +1 -1
  10. package/ci/test-optimization-validation/cli.js +1 -1
  11. package/ci/test-optimization-validation/command-runner.js +2 -3
  12. package/ci/test-optimization-validation/executable.js +1 -1
  13. package/ci/test-optimization-validation/framework-adapters/cucumber.js +1 -1
  14. package/ci/test-optimization-validation/literal-environment.js +2 -2
  15. package/ci/test-optimization-validation/manifest-scaffold.js +1 -1
  16. package/ci/test-optimization-validation/offline-fixtures.js +1 -1
  17. package/ci/test-optimization-validation/redaction.js +3 -3
  18. package/ci/test-optimization-validation/runner-contract.js +10 -10
  19. package/ci/test-optimization-validation/scenarios/ci-wiring.js +1 -1
  20. package/ci/vitest-no-worker-init-annotations.mjs +4 -0
  21. package/ci/vitest-no-worker-init-node-setup.mjs +22 -0
  22. package/ci/vitest-no-worker-init-runner-setup.mjs +7 -32
  23. package/ci/vitest-no-worker-init-setup.mjs +34 -12
  24. package/ci/vitest-no-worker-init-v5-setup.mjs +6 -0
  25. package/ext/exporters.js +1 -0
  26. package/index.d.ts +19 -0
  27. package/loader-hook.mjs +53 -0
  28. package/openfeature/exposure-hook.d.ts +66 -0
  29. package/openfeature/exposure-hook.js +5 -0
  30. package/package.json +11 -9
  31. package/packages/datadog-core/src/storage.js +1 -1
  32. package/packages/datadog-esbuild/index.js +70 -7
  33. package/packages/datadog-instrumentations/src/cucumber.js +53 -19
  34. package/packages/datadog-instrumentations/src/cypress-config.js +163 -15
  35. package/packages/datadog-instrumentations/src/graphql.js +9 -3
  36. package/packages/datadog-instrumentations/src/grpc/server.js +23 -6
  37. package/packages/datadog-instrumentations/src/helpers/fetch.js +5 -1
  38. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +30 -8
  39. package/packages/datadog-instrumentations/src/helpers/hooks.js +1 -1
  40. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +16 -6
  41. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +8 -0
  42. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +3 -1
  43. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/react-router.js +49 -0
  44. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/typesafe.js +23 -0
  45. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/webdriverio.js +12 -0
  46. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +8 -0
  47. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.js +19 -2
  48. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +8 -0
  49. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +1 -1
  50. package/packages/datadog-instrumentations/src/jest.js +265 -82
  51. package/packages/datadog-instrumentations/src/mariadb-bundle.js +69 -11
  52. package/packages/datadog-instrumentations/src/mariadb.js +13 -6
  53. package/packages/datadog-instrumentations/src/mocha/common.js +89 -8
  54. package/packages/datadog-instrumentations/src/mocha/main.js +11 -2
  55. package/packages/datadog-instrumentations/src/mocha/utils.js +58 -12
  56. package/packages/datadog-instrumentations/src/mocha/worker.js +1 -1
  57. package/packages/datadog-instrumentations/src/oracledb.js +33 -0
  58. package/packages/datadog-instrumentations/src/pg.js +2 -1
  59. package/packages/datadog-instrumentations/src/playwright.js +81 -28
  60. package/packages/datadog-instrumentations/src/react-router.js +106 -0
  61. package/packages/datadog-instrumentations/src/typesafe.js +89 -0
  62. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +84 -48
  63. package/packages/datadog-instrumentations/src/vitest-main.js +26 -0
  64. package/packages/datadog-instrumentations/src/vitest-test-annotations.js +20 -0
  65. package/packages/datadog-instrumentations/src/vitest-worker.js +39 -17
  66. package/packages/datadog-instrumentations/src/vitest.js +10 -8
  67. package/packages/datadog-plugin-cucumber/src/index.js +5 -0
  68. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +274 -44
  69. package/packages/datadog-plugin-cypress/src/index.js +1 -1
  70. package/packages/datadog-plugin-cypress/src/lifecycle-owner.js +20 -0
  71. package/packages/datadog-plugin-cypress/src/plugin.js +10 -0
  72. package/packages/datadog-plugin-cypress/src/retry-config-observer.js +281 -0
  73. package/packages/datadog-plugin-cypress/src/setup-handoff.js +125 -0
  74. package/packages/datadog-plugin-cypress/src/support.js +1217 -439
  75. package/packages/datadog-plugin-graphql/src/execute.js +2 -2
  76. package/packages/datadog-plugin-graphql/src/utils.js +5 -5
  77. package/packages/datadog-plugin-jest/src/index.js +25 -3
  78. package/packages/datadog-plugin-mocha/src/index.js +47 -6
  79. package/packages/datadog-plugin-oracledb/src/connection-parser.js +21 -11
  80. package/packages/datadog-plugin-playwright/src/index.js +4 -0
  81. package/packages/datadog-plugin-react-router/src/index.js +118 -0
  82. package/packages/datadog-plugin-typesafe/src/index.js +17 -0
  83. package/packages/datadog-plugin-typesafe/src/tracing.js +31 -0
  84. package/packages/datadog-plugin-vitest/src/index.js +8 -0
  85. package/packages/dd-trace/src/agent/info.js +2 -1
  86. package/packages/dd-trace/src/aiguard/sdk.js +0 -11
  87. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +9 -16
  88. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +4 -2
  89. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +9 -16
  90. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +9 -14
  91. package/packages/dd-trace/src/ci-visibility/requests/route.js +44 -0
  92. package/packages/dd-trace/src/ci-visibility/telemetry-logs.js +5 -0
  93. package/packages/dd-trace/src/ci-visibility/test-annotations.js +72 -0
  94. package/packages/dd-trace/src/ci-visibility/test-declaration-annotations.js +170 -0
  95. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +9 -16
  96. package/packages/dd-trace/src/config/defaults.js +4 -3
  97. package/packages/dd-trace/src/config/generated-config-types.d.ts +4 -0
  98. package/packages/dd-trace/src/config/index.js +95 -39
  99. package/packages/dd-trace/src/config/parsers.js +9 -1
  100. package/packages/dd-trace/src/config/supported-configurations.json +16 -0
  101. package/packages/dd-trace/src/debugger/probe_sampler.js +6 -6
  102. package/packages/dd-trace/src/encode/0.4.js +2 -2
  103. package/packages/dd-trace/src/esm-module-load.js +58 -0
  104. package/packages/dd-trace/src/exporter.js +25 -6
  105. package/packages/dd-trace/src/exporters/agent/index.js +3 -1
  106. package/packages/dd-trace/src/exporters/agentless/index.js +3 -1
  107. package/packages/dd-trace/src/exporters/common/request.js +4 -4
  108. package/packages/dd-trace/src/exporters/llmobs/index.js +135 -0
  109. package/packages/dd-trace/src/exporters/log/index.js +4 -3
  110. package/packages/dd-trace/src/llmobs/constants/tags.js +1 -0
  111. package/packages/dd-trace/src/llmobs/experiments/index.js +2 -3
  112. package/packages/dd-trace/src/llmobs/experiments/noop.js +5 -2
  113. package/packages/dd-trace/src/llmobs/index.js +13 -2
  114. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +1 -1
  115. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +1 -1
  116. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +8 -4
  117. package/packages/dd-trace/src/llmobs/plugins/typesafe/index.js +102 -0
  118. package/packages/dd-trace/src/llmobs/prompts/cache.js +3 -1
  119. package/packages/dd-trace/src/llmobs/sdk.js +2 -1
  120. package/packages/dd-trace/src/llmobs/span_processor.js +210 -12
  121. package/packages/dd-trace/src/llmobs/tagger.js +3 -0
  122. package/packages/dd-trace/src/llmobs/writers/util.js +3 -3
  123. package/packages/dd-trace/src/log/writer.js +7 -1
  124. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +64 -6
  125. package/packages/dd-trace/src/openfeature/configuration_source.js +18 -2
  126. package/packages/dd-trace/src/openfeature/debug-logging-hook.js +66 -3
  127. package/packages/dd-trace/src/openfeature/exposure-hook.js +185 -0
  128. package/packages/dd-trace/src/openfeature/flagging_provider.js +39 -13
  129. package/packages/dd-trace/src/openfeature/remote_config.js +16 -3
  130. package/packages/dd-trace/src/openfeature/writers/base.js +62 -27
  131. package/packages/dd-trace/src/openfeature/writers/exposures.js +161 -1
  132. package/packages/dd-trace/src/openfeature/writers/flag-eval-evp-hook.js +5 -0
  133. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-aggregation.js +9 -4
  134. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-payload.js +2 -0
  135. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-pii.js +2 -0
  136. package/packages/dd-trace/src/openfeature/writers/split-features.js +25 -0
  137. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +2 -2
  138. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +5 -1
  139. package/packages/dd-trace/src/opentracing/tracer.js +9 -13
  140. package/packages/dd-trace/src/otel-thread-ctx.js +47 -21
  141. package/packages/dd-trace/src/plugins/ci_plugin.js +4 -4
  142. package/packages/dd-trace/src/plugins/index.js +3 -0
  143. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  144. package/packages/dd-trace/src/plugins/util/git.js +11 -5
  145. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +2 -4
  146. package/packages/dd-trace/src/plugins/util/test.js +26 -6
  147. package/packages/dd-trace/src/plugins/util/web.js +16 -0
  148. package/packages/dd-trace/src/process-tags/index.js +1 -1
  149. package/packages/dd-trace/src/profiling/config.js +6 -3
  150. package/packages/dd-trace/src/proxy.js +15 -4
  151. package/packages/dd-trace/src/serverless.js +3 -2
  152. package/packages/dd-trace/src/span_processor.js +21 -9
  153. package/packages/dd-trace/src/span_stats.js +28 -2
  154. package/packages/dd-trace/src/startup-log.js +2 -1
  155. package/packages/dd-trace/src/tagger.js +7 -5
  156. package/packages/dd-trace/src/telemetry/dependencies.js +4 -0
  157. package/packages/dd-trace/src/telemetry/index.js +3 -0
  158. package/packages/dd-trace/src/telemetry/logs/index.js +21 -2
  159. package/packages/dd-trace/src/telemetry/logs/log-collector.js +1 -0
  160. package/packages/dd-trace/src/telemetry/telemetry.js +10 -3
  161. package/packages/dd-trace/src/util.js +1 -1
  162. package/register.js +2 -1
  163. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
  164. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.d.ts +78 -0
  165. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.js +1 -1
  166. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  167. package/vendor/dist/@opentelemetry/resources/LICENSE +0 -201
  168. package/vendor/dist/@opentelemetry/resources/index.js +0 -1
@@ -15,6 +15,7 @@ const {
15
15
  const { channel } = require('./helpers/instrument')
16
16
 
17
17
  const DD_CONFIG_WRAPPED = Symbol.for('dd-trace.cypress.config.wrapped')
18
+ const DD_SUPPORT_OWNER = Symbol.for('dd-trace.cypress.support-owner')
18
19
  const DD_CYPRESS_AFTER_SPEC_HANDLER = Symbol.for('dd-trace.cypress.after-spec.handler')
19
20
  const DD_CYPRESS_AFTER_RUN_HANDLER = Symbol.for('dd-trace.cypress.after-run.handler')
20
21
  const DD_CYPRESS_TASK_HANDLER = Symbol.for('dd-trace.cypress.task.handler')
@@ -25,6 +26,7 @@ const CONFIG_INSTRUMENTATION_NOT_INSTALLED =
25
26
  'Cypress configurations that cannot be intercepted through cypress.defineConfig were not auto-instrumented.'
26
27
  const generatedFilesForExitCleanup = new Set()
27
28
  let exitCleanupRegistered = false
29
+ let stopManualSupportSetup
28
30
 
29
31
  const setupNodeEventsCh = channel('ci:cypress:setup-node-events')
30
32
 
@@ -39,6 +41,7 @@ if (loadCh.hasSubscribers) {
39
41
 
40
42
  const noopTask = {
41
43
  'dd:testSuiteStart': () => null,
44
+ 'dd:testDeclarations': () => null,
42
45
  'dd:beforeEach': () => ({}),
43
46
  'dd:afterEach': () => null,
44
47
  'dd:addTags': () => null,
@@ -250,13 +253,20 @@ function mergeReturnedConfig (config, updatedConfig) {
250
253
  }
251
254
 
252
255
  const mergedConfig = { ...config }
253
-
254
- for (const [key, value] of Object.entries(updatedConfig)) {
255
- mergedConfig[key] = isPlainObject(value) && isPlainObject(mergedConfig[key])
256
- ? mergeReturnedConfig(mergedConfig[key], value)
257
- : value
256
+ // Retain the values already read for the reply, rather than invoking user getters again at IPC.
257
+ const returnedConfig = Object.fromEntries(Object.entries(updatedConfig))
258
+
259
+ for (const [key, value] of Object.entries(returnedConfig)) {
260
+ if (isPlainObject(value) && isPlainObject(mergedConfig[key]) && value !== mergedConfig[key]) {
261
+ mergedConfig[key] = mergeReturnedConfig(mergedConfig[key], value)
262
+ // Keep only the returned overrides, using values already read by the recursive merge.
263
+ returnedConfig[key] = mergedConfig[key][Symbol.for('dd-trace.cypress.returned-config')]
264
+ } else {
265
+ mergedConfig[key] = value
266
+ }
258
267
  }
259
268
 
269
+ Object.defineProperty(mergedConfig, Symbol.for('dd-trace.cypress.returned-config'), { value: returnedConfig })
260
270
  return mergedConfig
261
271
  }
262
272
 
@@ -289,9 +299,13 @@ function getRelativeImportPath (fromDirectory, importedFile) {
289
299
  * @param {string} directory writable directory inside the Cypress project
290
300
  * @param {string|false|undefined} originalSupportFile user's support file
291
301
  * @param {string} browserHooksSource Datadog browser-side support hooks
302
+ * @param {boolean} deferLifecycle whether manual support owns lifecycle registration
303
+ * @param {string} lifecycleOwnerSource browser lifecycle ownership detection
292
304
  * @returns {string[]} generated files
293
305
  */
294
- function createSupportWrapper (directory, originalSupportFile, browserHooksSource) {
306
+ function createSupportWrapper (
307
+ directory, originalSupportFile, browserHooksSource, deferLifecycle, lifecycleOwnerSource
308
+ ) {
295
309
  const suffix = `${process.pid}-${randomUUID()}`
296
310
  const browserHooksFile = path.join(directory, `dd-cypress-support-hooks-${suffix}.mjs`)
297
311
  const wrapperFile = path.join(directory, `dd-cypress-support-${suffix}.mjs`)
@@ -305,9 +319,47 @@ function createSupportWrapper (directory, originalSupportFile, browserHooksSourc
305
319
 
306
320
  const generatedFiles = []
307
321
  try {
308
- writeExclusiveFile(browserHooksFile, browserHooksSource)
322
+ const guardedSource = `const ddSupportRoot = Cypress.mocha.getRootSuite()
323
+ const ddSupportKey = Symbol.for('dd-trace.cypress.support-installed')
324
+ const ddHasLifecycle = (() => {
325
+ const module = { exports: {} }
326
+ ${lifecycleOwnerSource}
327
+ return module.exports
328
+ })()
329
+ ddSupportRoot[Symbol.for('dd-trace.cypress.has-lifecycle')] = ddHasLifecycle
330
+ if (!ddSupportRoot[ddSupportKey] && !ddHasLifecycle(ddSupportRoot)) {
331
+ const positions = {}
332
+ for (const key of ['_beforeAll', '_beforeEach', '_afterAll', '_afterEach']) {
333
+ positions[key] = Array.isArray(ddSupportRoot[key]) ? ddSupportRoot[key].length : 0
334
+ }
335
+ ddSupportRoot[Symbol.for('dd-trace.cypress.lifecycle-positions')] = positions
336
+ ddSupportRoot[Symbol.for('dd-trace.cypress.defer-lifecycle')] = ${deferLifecycle}
337
+ ${browserHooksSource}
338
+ ddSupportRoot[ddSupportKey] = true
339
+ }
340
+ `
341
+ writeExclusiveFile(browserHooksFile, guardedSource)
309
342
  generatedFiles.push(browserHooksFile)
310
- writeExclusiveFile(wrapperFile, `${wrapperImports.join('\n')}\n`)
343
+ const finalize = `const root = Cypress.mocha.getRootSuite()
344
+ const install = root[Symbol.for('dd-trace.cypress.install-lifecycle')]
345
+ const hasLifecycle = root[Symbol.for('dd-trace.cypress.has-lifecycle')]
346
+ if (typeof install === 'function' && (!hasLifecycle || !hasLifecycle(root))) {
347
+ const phases = ['_beforeAll', '_beforeEach', '_afterAll', '_afterEach']
348
+ const lengths = {}
349
+ for (const key of phases) lengths[key] = Array.isArray(root[key]) ? root[key].length : 0
350
+ install()
351
+ // A Node-only manual plugin needs automatic browser hooks before user hooks.
352
+ // Move only the hooks just installed; an actual manual owner never enters here.
353
+ const positions = root[Symbol.for('dd-trace.cypress.lifecycle-positions')]
354
+ for (const key of phases) {
355
+ if (positions && Array.isArray(root[key])) {
356
+ const added = root[key].splice(lengths[key])
357
+ root[key].splice(positions[key], 0, ...added)
358
+ }
359
+ }
360
+ }
361
+ `
362
+ writeExclusiveFile(wrapperFile, `${wrapperImports.join('\n')}\n${finalize}`)
311
363
  generatedFiles.push(wrapperFile)
312
364
  } catch (error) {
313
365
  for (const generatedFile of generatedFiles) removeGeneratedFile(generatedFile)
@@ -323,21 +375,26 @@ function createSupportWrapper (directory, originalSupportFile, browserHooksSourc
323
375
  * generated paths for cleanup, or undefined if injection was skipped.
324
376
  *
325
377
  * @param {object} config Cypress resolved config object
378
+ * @param {boolean} [manualLifecycle] whether the manual entry point owns lifecycle registration
326
379
  * @returns {string[]|undefined} generated file paths, or undefined if skipped
327
380
  */
328
- function injectSupportFile (config) {
381
+ function injectSupportFile (config, manualLifecycle = false) {
329
382
  const originalSupportFile = config.supportFile
330
383
 
384
+ const supportOwner = config[DD_SUPPORT_OWNER]
385
+ if (generatedFilesForExitCleanup.has(originalSupportFile) &&
386
+ (!manualLifecycle || (supportOwner?.path === originalSupportFile && supportOwner.deferLifecycle))) return
387
+ let deferLifecycle = manualLifecycle ||
388
+ (supportOwner && supportOwner.path === originalSupportFile && supportOwner.deferLifecycle)
389
+
331
390
  if (originalSupportFile) {
332
391
  try {
333
392
  const content = fs.readFileSync(originalSupportFile, 'utf8')
334
- // Naive check: skip lines starting with // or * to avoid matching commented-out imports.
335
- const hasActiveDdTraceImport = content.split('\n').some(line => {
393
+ deferLifecycle ||= content.split('\n').some(line => {
336
394
  const trimmed = line.trim()
337
395
  return trimmed.includes('dd-trace/ci/cypress/support') &&
338
396
  !trimmed.startsWith('//') && !trimmed.startsWith('*')
339
397
  })
340
- if (hasActiveDdTraceImport) return
341
398
  } catch (error) {
342
399
  logBrowserInstrumentationError(
343
400
  'Datadog could not read the Cypress support file %s: %s. %s',
@@ -351,9 +408,11 @@ function injectSupportFile (config) {
351
408
 
352
409
  let browserHooksSource
353
410
  let browserHooksPath
411
+ let lifecycleOwnerSource
354
412
  try {
355
413
  browserHooksPath = require.resolve('../../datadog-plugin-cypress/src/support')
356
414
  browserHooksSource = fs.readFileSync(browserHooksPath, 'utf8')
415
+ lifecycleOwnerSource = fs.readFileSync(require.resolve('../../datadog-plugin-cypress/src/lifecycle-owner'), 'utf8')
357
416
  } catch (error) {
358
417
  logBrowserInstrumentationError(
359
418
  'Datadog could not read its Cypress browser support hooks: %s. %s',
@@ -372,8 +431,12 @@ function injectSupportFile (config) {
372
431
  for (const directory of new Set(candidateDirectories)) {
373
432
  if (projectRoot && !isPathInside(projectRoot, directory)) continue
374
433
  try {
375
- const generatedFiles = createSupportWrapper(directory, originalSupportFile, browserHooksSource)
434
+ const generatedFiles = createSupportWrapper(
435
+ directory, originalSupportFile, browserHooksSource, !!deferLifecycle, lifecycleOwnerSource
436
+ )
376
437
  config.supportFile = generatedFiles[1]
438
+ // Shared across SDK copies, but scoped to this exact generated support path.
439
+ config[DD_SUPPORT_OWNER] = { path: config.supportFile, deferLifecycle: !!deferLifecycle }
377
440
  return generatedFiles
378
441
  } catch (error) {
379
442
  failures.push({ directory, error })
@@ -396,6 +459,90 @@ function injectSupportFile (config) {
396
459
  }
397
460
  }
398
461
 
462
+ /**
463
+ * Installs browser hooks before user support, including manual SDK imports.
464
+ *
465
+ * @param {object} config Cypress resolved config object
466
+ * @param {boolean} [manualLifecycle] whether the manual entry point owns lifecycle registration
467
+ * @returns {string[]|undefined} generated files owned until cleanup or process exit
468
+ */
469
+ function installSupportFile (config, manualLifecycle = false) {
470
+ const files = injectSupportFile(config, manualLifecycle)
471
+ if (files) registerGeneratedFilesForExitCleanup(files)
472
+ return files
473
+ }
474
+
475
+ /**
476
+ * Keeps early browser instrumentation in the actual manual setup return value.
477
+ *
478
+ * @param {object} config Cypress resolved config object
479
+ * @returns {(() => void)|undefined} cleanup for the one-shot setup observer
480
+ */
481
+ function installManualSupportFile (config) {
482
+ stopManualSupportSetup?.()
483
+ installSupportFile(config, true)
484
+ const originalSend = process.send
485
+ if (typeof originalSend !== 'function') return
486
+
487
+ let active = true
488
+ const stop = () => {
489
+ active = false
490
+ if (process.send === send) process.send = originalSend
491
+ if (stopManualSupportSetup === stop) stopManualSupportSetup = undefined
492
+ }
493
+ const send = function (message) {
494
+ let forwarded = message
495
+ if (active && (message?.event === 'setupTestingType:reply' || message?.event === 'setupTestingType:error')) {
496
+ try {
497
+ const reply = message.event === 'setupTestingType:reply' && message.args?.[0]
498
+ const supplied = reply?.setupConfig
499
+ if (reply && (supplied == null || (supplied && typeof supplied === 'object' && !Array.isArray(supplied)))) {
500
+ // Snapshot own enumerable values once, as native IPC serialization would.
501
+ const returnedConfig = Object.fromEntries(Object.entries(supplied ?? {}))
502
+ const supportOwner = supplied && Object.getOwnPropertyDescriptor(supplied, DD_SUPPORT_OWNER)
503
+ if (supportOwner && 'value' in supportOwner) {
504
+ Object.defineProperty(returnedConfig, DD_SUPPORT_OWNER, supportOwner)
505
+ }
506
+ const projectRoot = returnedConfig.projectRoot ?? config.projectRoot
507
+ const supportFile = returnedConfig.supportFile === undefined ? config.supportFile : returnedConfig.supportFile
508
+ // Leave invalid user configuration for Cypress's native validator.
509
+ if (typeof projectRoot === 'string' &&
510
+ (supportFile === undefined || supportFile === false || typeof supportFile === 'string')) {
511
+ const supportConfig = {
512
+ projectRoot,
513
+ supportFile: typeof supportFile === 'string' ? path.resolve(projectRoot, supportFile) : supportFile,
514
+ [DD_SUPPORT_OWNER]: returnedConfig[DD_SUPPORT_OWNER] ?? config[DD_SUPPORT_OWNER],
515
+ }
516
+ installSupportFile(supportConfig, true)
517
+ if (generatedFilesForExitCleanup.has(supportConfig.supportFile)) {
518
+ const args = [...message.args]
519
+ args[0] = {
520
+ ...reply,
521
+ setupConfig: {
522
+ ...returnedConfig,
523
+ supportFile: supportConfig.supportFile,
524
+ [DD_SUPPORT_OWNER]: supportConfig[DD_SUPPORT_OWNER],
525
+ },
526
+ }
527
+ forwarded = { ...message, args }
528
+ }
529
+ }
530
+ }
531
+ } catch (error) {
532
+ log.warn('Datadog could not retain the Cypress support wrapper in the setup reply: %s.', error)
533
+ } finally {
534
+ stop()
535
+ }
536
+ }
537
+ const args = [...arguments]
538
+ args[0] = forwarded
539
+ return originalSend.apply(this, args)
540
+ }
541
+ stopManualSupportSetup = stop
542
+ process.send = send
543
+ return stop
544
+ }
545
+
399
546
  /**
400
547
  * Registers screenshot handlers collected from a manual plugin call. User
401
548
  * handlers run first so a renamed screenshot path reaches the Datadog handler.
@@ -515,8 +662,7 @@ function registerDdTraceHooks (
515
662
  userAfterScreenshotHandlers,
516
663
  manualPlugin
517
664
  ) {
518
- const generatedSupportFiles = injectSupportFile(config)
519
- if (generatedSupportFiles) registerGeneratedFilesForExitCleanup(generatedSupportFiles)
665
+ const generatedSupportFiles = installSupportFile(config, manualPlugin.detected)
520
666
 
521
667
  const cleanupWrapper = () => {
522
668
  // Open mode reuses this support file across runs, including failed setup attempts.
@@ -930,6 +1076,8 @@ function wrapCliConfigFileOptions (options) {
930
1076
  }
931
1077
 
932
1078
  module.exports = {
1079
+ installManualSupportFile,
1080
+ installSupportFile,
933
1081
  wrapCliConfigFileOptions,
934
1082
  wrapConfig,
935
1083
  }
@@ -11,10 +11,16 @@ const { addHook, getHooks } = require('./helpers/instrument')
11
11
  * @param {string} name
12
12
  */
13
13
  function addRewriterHooks (name) {
14
- const files = new Set()
14
+ const hooks = new Map()
15
15
  for (const hook of getHooks(name).values()) {
16
- if (files.has(hook.file)) continue
17
- files.add(hook.file)
16
+ const existing = hooks.get(hook.file)
17
+ if (existing) {
18
+ existing.versions.push(...hook.versions)
19
+ } else {
20
+ hooks.set(hook.file, hook)
21
+ }
22
+ }
23
+ for (const hook of hooks.values()) {
18
24
  addHook(hook, exports => exports)
19
25
  }
20
26
  }
@@ -23,6 +23,16 @@ const isValid = (server, args) => {
23
23
  (server.type === 'unary' ? typeof args[1] === 'function' : isEmitter(args[0])))
24
24
  }
25
25
 
26
+ // A call can end through several paths (cancellation, error, handler callback);
27
+ // only the first one may finish the span and set its status. Later terminal
28
+ // events must not publish errors or status updates either: the span can still
29
+ // be buffered by an unfinished child, so they would overwrite the final tags.
30
+ function finish (ctx) {
31
+ if (ctx.finished) return
32
+ ctx.finished = true
33
+ finishChannel.publish(ctx)
34
+ }
35
+
26
36
  function wrapHandler (func, name) {
27
37
  return function (call, callback) {
28
38
  if (!isValid(this, arguments)) return func.apply(this, arguments)
@@ -37,7 +47,7 @@ function wrapHandler (func, name) {
37
47
  try {
38
48
  const onCancel = () => {
39
49
  ctx.code = CANCELLED
40
- finishChannel.publish(ctx)
50
+ finish(ctx)
41
51
  }
42
52
 
43
53
  // Finish the span if the call was cancelled.
@@ -96,12 +106,14 @@ function wrapSetupHandlers (setupHandlers) {
96
106
  function createWrapEmit (call, ctx, onCancel) {
97
107
  return function wrapEmit (emit) {
98
108
  return function (event, arg1) {
109
+ if (ctx.finished) return emit.apply(this, arguments)
110
+
99
111
  switch (event) {
100
112
  case 'error':
101
113
  ctx.error = arg1
102
114
  errorChannel.publish(ctx)
103
115
  ctx.code = arg1.code
104
- finishChannel.publish(ctx)
116
+ finish(ctx)
105
117
  call.removeListener('cancelled', onCancel)
106
118
  break
107
119
  // Streams are always cancelled before `finish` since 1.10.0 so we have
@@ -111,7 +123,7 @@ function createWrapEmit (call, ctx, onCancel) {
111
123
  updateChannel.publish(call.status)
112
124
  }
113
125
  if (!call.status || call.status.code === 0) {
114
- finishChannel.publish(ctx)
126
+ finish(ctx)
115
127
  }
116
128
  call.removeListener('cancelled', onCancel)
117
129
  break
@@ -132,6 +144,9 @@ function wrapStream (call, ctx, onCancel) {
132
144
 
133
145
  function wrapCallback (callback = () => {}, call, ctx, onCancel) {
134
146
  return shimmer.wrapFunction(callback, callback => function (err, value, trailer, flags) {
147
+ if (ctx.finished) {
148
+ return asyncStartChannel.runStores(ctx, () => callback.apply(this, arguments))
149
+ }
135
150
  if (err) {
136
151
  ctx.error = err
137
152
  errorChannel.publish(ctx)
@@ -140,7 +155,7 @@ function wrapCallback (callback = () => {}, call, ctx, onCancel) {
140
155
  ctx.trailer = trailer
141
156
  }
142
157
 
143
- finishChannel.publish(ctx)
158
+ finish(ctx)
144
159
 
145
160
  call.removeListener('cancelled', onCancel)
146
161
 
@@ -153,8 +168,10 @@ function wrapCallback (callback = () => {}, call, ctx, onCancel) {
153
168
 
154
169
  function wrapSendStatus (sendStatus, ctx) {
155
170
  return function (status) {
156
- ctx.status = status
157
- updateChannel.publish(ctx)
171
+ if (!ctx.finished) {
172
+ ctx.status = status
173
+ updateChannel.publish(ctx)
174
+ }
158
175
 
159
176
  return sendStatus.apply(this, arguments)
160
177
  }
@@ -19,8 +19,12 @@ exports.createWrapFetch = function createWrapFetch (Request, ch, onLoad) {
19
19
  }
20
20
  const req = new Request(input, init)
21
21
  const ctx = { req }
22
+ const signal = init?.signal
22
23
 
23
- return ch.tracePromise(() => fetch.call(this, req), ctx)
24
+ // The signal of `req` only weakly follows `init.signal` and is collected once `req` is unreachable, which
25
+ // stops aborts from reaching the in-flight request. Passing it again lets `fetch` follow it directly.
26
+ const options = signal ? { signal, referrer: req.referrer, referrerPolicy: req.referrerPolicy } : undefined
27
+ return ch.tracePromise(() => fetch.call(this, req, options), ctx)
24
28
  }
25
29
  }
26
30
  }
@@ -24,6 +24,10 @@
24
24
  * missing: { path: ArgumentPath, valueNode: { name: { value: string } } }[],
25
25
  * values: Record<string, unknown>
26
26
  * }} CompiledArguments
27
+ * @typedef {(
28
+ * value: Record<string, unknown>,
29
+ * hoist: (value: unknown) => string
30
+ * ) => string} StringifyArguments
27
31
  * @typedef {{
28
32
  * baseTypeName: string,
29
33
  * resource: string,
@@ -36,6 +40,7 @@
36
40
  * collapsedPathSegments: string[],
37
41
  * staticArguments?: Record<string, unknown>,
38
42
  * hasArgumentVariables?: boolean,
43
+ * literals?: Record<string, unknown>,
39
44
  * fieldName: string,
40
45
  * fieldNode: import('graphql').FieldNode,
41
46
  * fieldNodes: [import('graphql').FieldNode, ...import('graphql').FieldNode[]],
@@ -70,7 +75,8 @@
70
75
  * ) => FieldMetadata} CreateFieldMetadata
71
76
  * @typedef {(
72
77
  * variableValues: Record<string, unknown> | undefined,
73
- * cloneValue?: (value: unknown) => unknown
78
+ * cloneValue?: (value: unknown) => unknown,
79
+ * literalContext?: JitFieldDescriptor
74
80
  * ) => Record<string, unknown>} ArgumentFactory
75
81
  * @typedef {(
76
82
  * rootCtx: object,
@@ -132,7 +138,7 @@
132
138
  * fieldNodes: [import('graphql').FieldNode, ...import('graphql').FieldNode[]],
133
139
  * originPaths: string[],
134
140
  * args: CompiledArguments,
135
- * argumentSource: string,
141
+ * stringifyArguments: StringifyArguments,
136
142
  * compiledField: string
137
143
  * ) => string,
138
144
  * finalizeCompilation: (
@@ -251,7 +257,7 @@ function createGraphqlJitRuntime ({
251
257
  * @param {[import('graphql').FieldNode, ...import('graphql').FieldNode[]]} fieldNodes
252
258
  * @param {string[]} originPaths
253
259
  * @param {CompiledArguments} args
254
- * @param {string} argumentSource
260
+ * @param {StringifyArguments} stringifyArguments
255
261
  * @param {string} compiledField
256
262
  */
257
263
  function compileDefaultField (
@@ -262,7 +268,7 @@ function createGraphqlJitRuntime ({
262
268
  fieldNodes,
263
269
  originPaths,
264
270
  args,
265
- argumentSource,
271
+ stringifyArguments,
266
272
  compiledField
267
273
  ) {
268
274
  const parentPath = originPaths.join('.')
@@ -284,7 +290,7 @@ function createGraphqlJitRuntime ({
284
290
  }, fieldNodes[0], createFieldMetadata)
285
291
  descriptor.staticArguments = args.values
286
292
  descriptor.hasArgumentVariables = args.missing.length !== 0
287
- const argumentFactory = compileArgumentFactory(context, descriptor, args.missing, argumentSource)
293
+ const argumentFactory = compileArgumentFactory(context, descriptor, args.missing, stringifyArguments)
288
294
 
289
295
  const shouldTrace = '__context.ddTrace !== undefined && ' +
290
296
  '(__context.ddTrace.jitTraceAll || ' +
@@ -354,6 +360,7 @@ function createDescriptor (context, compilerPath, input, fieldNode, createFieldM
354
360
  fieldNode,
355
361
  fieldNodes: input.fieldNodes,
356
362
  hasArgumentVariables: undefined,
363
+ literals: undefined,
357
364
  parentId: undefined,
358
365
  parentPathKey: compilerPath.parentPathKey,
359
366
  parentTypeName,
@@ -374,13 +381,20 @@ function createDescriptor (context, compilerPath, input, fieldNode, createFieldM
374
381
  * @param {ConfiguredJitCompilationContext} context
375
382
  * @param {JitFieldDescriptor} descriptor
376
383
  * @param {CompiledArguments['missing']} missing
377
- * @param {string} argumentSource
384
+ * @param {StringifyArguments} stringifyArguments
378
385
  */
379
- function compileArgumentFactory (context, descriptor, missing, argumentSource) {
386
+ function compileArgumentFactory (context, descriptor, missing, stringifyArguments) {
387
+ let literalIndex = 0
388
+ const argumentSource = stringifyArguments(descriptor.staticArguments, hoist)
380
389
  if (missing.length === 0 && argumentSource === '{}') return 'undefined'
381
390
 
382
391
  const name = `ddTraceArguments${descriptor.id}`
383
- let source = `function ${name} (variableValues, cloneValue) {\n const args = ${argumentSource}\n`
392
+ const hasLiterals = descriptor.literals !== undefined
393
+ const parameters = hasLiterals ? 'variableValues, cloneValue, __context' : 'variableValues, cloneValue'
394
+ let source = `function ${name} (${parameters}) {\n const args = `
395
+ source += hasLiterals
396
+ ? `cloneValue === undefined ? ${argumentSource} : cloneValue(${argumentSource})\n`
397
+ : `${argumentSource}\n`
384
398
  const pathsByVariable = new Map()
385
399
 
386
400
  for (const { path, valueNode } of missing) {
@@ -411,6 +425,14 @@ function compileArgumentFactory (context, descriptor, missing, argumentSource) {
411
425
  source += ' return args\n}\n'
412
426
  context.hoistedFunctions.push(source)
413
427
  return name
428
+
429
+ /** @param {unknown} value */
430
+ function hoist (value) {
431
+ const name = `literal${literalIndex++}`
432
+ descriptor.literals ??= {}
433
+ descriptor.literals[name] = value
434
+ return name
435
+ }
414
436
  }
415
437
 
416
438
  /**
@@ -86,7 +86,7 @@ module.exports = {
86
86
  'find-my-way': () => require('../find-my-way'),
87
87
  'generic-pool': () => require('../generic-pool'),
88
88
  graphql: () => require('../graphql'),
89
- 'graphql-jit': () => require('../graphql'),
89
+ 'graphql-jit': { esmFirst: true, fn: () => require('../graphql') },
90
90
  grpc: () => require('../grpc'),
91
91
  handlebars: () => require('../handlebars'),
92
92
  hapi: () => require('../hapi'),
@@ -19,7 +19,8 @@ const { getRewriteTarget } = require('./targets')
19
19
  * { code: string, map?: string|object }} transform
20
20
  *
21
21
  * @typedef {(content: string|Buffer|ArrayBuffer|Uint8Array, filename: string, format?: string,
22
- * target?: { moduleName: string, filePath: string, activate?: boolean }, sourceMap?: string|object) =>
22
+ * target?: { moduleName: string, filePath: string, activate?: boolean, sourceMatch?: string },
23
+ * sourceMap?: string|object) =>
23
24
  * { code: string|Buffer|ArrayBuffer|Uint8Array, map?: string|object }} BundlerRewriter
24
25
  */
25
26
 
@@ -62,7 +63,7 @@ function normalizeFilename (filename) {
62
63
  * @param {string|Buffer|ArrayBuffer|Uint8Array} content
63
64
  * @param {string} filename
64
65
  * @param {string} [format]
65
- * @param {{ moduleName: string, filePath: string, activate?: boolean }} [target]
66
+ * @param {{ moduleName: string, filePath: string, activate?: boolean, sourceMatch?: string }} [target]
66
67
  * @returns {string|Buffer|ArrayBuffer|Uint8Array}
67
68
  */
68
69
  function rewrite (content, filename, format, target) {
@@ -74,17 +75,20 @@ function rewrite (content, filename, format, target) {
74
75
  if (!target) return content
75
76
 
76
77
  const moduleType = format === 'module' ? 'esm' : 'cjs'
77
- const { moduleName, filePath, activate } = target
78
+ const { moduleName, filePath, activate, sourceMatch } = target
78
79
  if (disabled.has(moduleName)) return content
79
80
 
80
81
  const version = getVersion(filename, filePath)
81
82
  if (!version) return content
82
83
 
84
+ const matchedSource = sourceMatch && getSourceText(content)
85
+ if (sourceMatch && !matchedSource?.includes(sourceMatch)) return content
86
+
83
87
  const transformer = getMatcher(moduleType).getTransformer(moduleName, version, filePath)
84
88
 
85
89
  if (!transformer && !activate) return content
86
90
 
87
- const source = getSourceText(content)
91
+ const source = matchedSource ?? getSourceText(content)
88
92
 
89
93
  if (!transformer) {
90
94
  return appendOrchestrionLoad(
@@ -139,14 +143,20 @@ function createBundlerRewriter (dcModule) {
139
143
  if (!target) return { code: content, map: sourceMap }
140
144
 
141
145
  const moduleType = format === 'module' ? 'esm' : 'cjs'
142
- const { moduleName, filePath } = target
146
+ const { moduleName, filePath, sourceMatch } = target
143
147
  const version = getVersion(filename, filePath)
144
148
  if (!version) return { code: content, map: sourceMap }
145
149
 
150
+ let matchedSource
151
+ if (sourceMatch) {
152
+ matchedSource = getSourceText(content)
153
+ if (!matchedSource.includes(sourceMatch)) return { code: content, map: sourceMap }
154
+ }
155
+
146
156
  const transformer = matcher.getTransformer(moduleName, version, filePath)
147
157
  if (!transformer) return { code: content, map: sourceMap }
148
158
 
149
- return transformer.transform(getSourceText(content), moduleType, sourceMap)
159
+ return transformer.transform(matchedSource ?? getSourceText(content), moduleType, sourceMap)
150
160
  } catch (error) {
151
161
  log.error(error)
152
162
  return { code: content, map: sourceMap }
@@ -40,6 +40,10 @@ const registry = [
40
40
  { instrumentations: require('./instrumentations/openai-agents') },
41
41
  { instrumentations: require('./instrumentations/playwright') },
42
42
  { activate: true, instrumentations: require('./instrumentations/postgres') },
43
+ {
44
+ activate: /** @type {ActivationConfig} */ ({ setup: () => require('../../react-router') }),
45
+ instrumentations: require('./instrumentations/react-router'),
46
+ },
43
47
  { instrumentations: require('./instrumentations/vitest') },
44
48
  { instrumentations: require('./instrumentations/webdriverio') },
45
49
  {
@@ -47,6 +51,10 @@ const registry = [
47
51
  instrumentations: require('./instrumentations/aws-durable-execution-sdk-js'),
48
52
  },
49
53
  { activate: true, instrumentations: require('./instrumentations/supabase') },
54
+ {
55
+ activate: { setup: () => require('../../typesafe') },
56
+ instrumentations: require('./instrumentations/typesafe'),
57
+ },
50
58
  ]
51
59
 
52
60
  const activatedModules = new Set()
@@ -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.8 contract. A future rewrite then misses safely instead of injecting stale names.
4
+ // 0.7–0.9 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,5 +78,7 @@ 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
83
 
82
84
  module.exports = instrumentations
@@ -0,0 +1,49 @@
1
+ 'use strict'
2
+
3
+ const instrumentations = []
4
+
5
+ for (const filePath of ['dist/development/index.js', 'dist/production/index.js']) {
6
+ for (const functionName of ['derive', 'matchServerRoutes']) {
7
+ instrumentations.push({
8
+ module: { name: 'react-router', versionRange: '>=7.9.5 <8', filePath },
9
+ functionQuery: { functionName },
10
+ channelName: functionName,
11
+ })
12
+ }
13
+ }
14
+
15
+ const chunkFilePath = /^dist\/(?:development|production)\/chunk-[A-Z0-9]+\.mjs$/
16
+ for (const functionName of ['derive', 'matchServerRoutes']) {
17
+ instrumentations.push({
18
+ module: {
19
+ name: 'react-router',
20
+ versionRange: '>=7.9.5 <8',
21
+ filePath: chunkFilePath,
22
+ sourceMatch: 'function derive(',
23
+ },
24
+ functionQuery: { functionName },
25
+ channelName: functionName,
26
+ })
27
+ }
28
+
29
+ for (const mode of ['development', 'production']) {
30
+ instrumentations.push({
31
+ module: {
32
+ name: 'react-router',
33
+ versionRange: '>=8',
34
+ filePath: `dist/${mode}/lib/server-runtime/server.js`,
35
+ },
36
+ functionQuery: { functionName: 'derive' },
37
+ channelName: 'derive',
38
+ }, {
39
+ module: {
40
+ name: 'react-router',
41
+ versionRange: '>=8',
42
+ filePath: `dist/${mode}/lib/server-runtime/routeMatching.js`,
43
+ },
44
+ functionQuery: { functionName: 'matchServerRoutes' },
45
+ channelName: 'matchServerRoutes',
46
+ })
47
+ }
48
+
49
+ module.exports = instrumentations