dd-trace 5.134.0 → 5.136.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 (353) hide show
  1. package/LICENSE-3rdparty.csv +0 -1
  2. package/ci/cypress/support.js +15 -1
  3. package/ci/init.js +2 -22
  4. package/ci/test-annotations.d.ts +5 -0
  5. package/ci/test-annotations.js +5 -0
  6. package/ci/vitest-no-worker-init-annotations.mjs +4 -0
  7. package/ci/vitest-no-worker-init-node-setup.mjs +22 -0
  8. package/ci/vitest-no-worker-init-runner-setup.mjs +7 -32
  9. package/ci/vitest-no-worker-init-setup.mjs +34 -12
  10. package/ci/vitest-no-worker-init-v5-setup.mjs +6 -0
  11. package/ext/exporters.js +1 -1
  12. package/index.d.ts +124 -5
  13. package/initialize.mjs +5 -2
  14. package/lambda.d.ts +39 -0
  15. package/lambda.js +3 -0
  16. package/loader-hook.mjs +53 -0
  17. package/openfeature/exposure-hook.d.ts +66 -0
  18. package/openfeature/exposure-hook.js +5 -0
  19. package/package.json +19 -15
  20. package/packages/datadog-core/src/storage.js +1 -1
  21. package/packages/datadog-esbuild/index.js +78 -62
  22. package/packages/datadog-instrumentations/src/aws-lambda.js +88 -0
  23. package/packages/datadog-instrumentations/src/cucumber.js +56 -19
  24. package/packages/datadog-instrumentations/src/cypress-config.js +163 -15
  25. package/packages/datadog-instrumentations/src/elevenlabs/activity.js +114 -0
  26. package/packages/datadog-instrumentations/src/elevenlabs/audio.js +104 -0
  27. package/packages/datadog-instrumentations/src/elevenlabs/index.js +288 -0
  28. package/packages/datadog-instrumentations/src/elevenlabs/session.js +444 -0
  29. package/packages/datadog-instrumentations/src/graphql.js +29 -20
  30. package/packages/datadog-instrumentations/src/grpc/server.js +23 -6
  31. package/packages/{datadog-esbuild/src/utils.js → datadog-instrumentations/src/helpers/bundler-esm-exports.js} +282 -40
  32. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +573 -0
  33. package/packages/datadog-instrumentations/src/helpers/bundler-utils.js +104 -0
  34. package/packages/datadog-instrumentations/src/helpers/fetch.js +5 -1
  35. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +30 -8
  36. package/packages/datadog-instrumentations/src/helpers/hook.js +29 -1
  37. package/packages/datadog-instrumentations/src/helpers/hooks.js +4 -8
  38. package/packages/datadog-instrumentations/src/helpers/lambda-handler.js +189 -0
  39. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +18 -6
  40. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +26 -1
  41. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/async-mutex.js +41 -0
  42. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/elevenlabs.js +25 -0
  43. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +3 -1
  44. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +0 -36
  45. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +40 -0
  46. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/openai-agents-realtime.js +23 -0
  47. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/react-router.js +49 -0
  48. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/trpc.js +148 -0
  49. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/typesafe.js +23 -0
  50. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/webdriverio.js +12 -0
  51. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +58 -0
  52. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.js +19 -2
  53. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +25 -3
  54. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +59 -2
  55. package/packages/datadog-instrumentations/src/ioredis.js +101 -3
  56. package/packages/datadog-instrumentations/src/jest.js +265 -82
  57. package/packages/datadog-instrumentations/src/mariadb-bundle.js +69 -11
  58. package/packages/datadog-instrumentations/src/mariadb.js +13 -6
  59. package/packages/datadog-instrumentations/src/mocha/common.js +89 -8
  60. package/packages/datadog-instrumentations/src/mocha/main.js +11 -2
  61. package/packages/datadog-instrumentations/src/mocha/utils.js +58 -12
  62. package/packages/datadog-instrumentations/src/mocha/worker.js +1 -1
  63. package/packages/datadog-instrumentations/src/next.js +19 -6
  64. package/packages/datadog-instrumentations/src/openai-agents-realtime.js +149 -0
  65. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +27 -0
  66. package/packages/datadog-instrumentations/src/openai-realtime/index.js +17 -6
  67. package/packages/datadog-instrumentations/src/openai-realtime/server-playback.js +887 -0
  68. package/packages/datadog-instrumentations/src/openai-realtime/session.js +150 -25
  69. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +29 -2
  70. package/packages/datadog-instrumentations/src/oracledb.js +33 -0
  71. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +11 -9
  72. package/packages/datadog-instrumentations/src/pg.js +2 -1
  73. package/packages/datadog-instrumentations/src/playwright.js +81 -28
  74. package/packages/datadog-instrumentations/src/react-router.js +106 -0
  75. package/packages/datadog-instrumentations/src/typesafe.js +89 -0
  76. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +84 -48
  77. package/packages/datadog-instrumentations/src/vitest-main.js +26 -0
  78. package/packages/datadog-instrumentations/src/vitest-test-annotations.js +20 -0
  79. package/packages/datadog-instrumentations/src/vitest-worker.js +39 -17
  80. package/packages/datadog-instrumentations/src/vitest.js +10 -8
  81. package/packages/datadog-instrumentations/src/webdriverio.js +12 -12
  82. package/packages/datadog-plugin-async-mutex/src/index.js +50 -0
  83. package/packages/datadog-plugin-aws-lambda/src/index.js +106 -0
  84. package/packages/datadog-plugin-cucumber/src/index.js +5 -0
  85. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +296 -55
  86. package/packages/datadog-plugin-cypress/src/index.js +1 -1
  87. package/packages/datadog-plugin-cypress/src/lifecycle-owner.js +20 -0
  88. package/packages/datadog-plugin-cypress/src/plugin.js +10 -0
  89. package/packages/datadog-plugin-cypress/src/retry-config-observer.js +281 -0
  90. package/packages/datadog-plugin-cypress/src/setup-handoff.js +125 -0
  91. package/packages/datadog-plugin-cypress/src/support.js +1217 -439
  92. package/packages/datadog-plugin-elevenlabs/src/index.js +69 -0
  93. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -7
  94. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +19 -52
  95. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +4 -2
  96. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-request-context.js +25 -4
  97. package/packages/datadog-plugin-graphql/src/execute.js +2 -2
  98. package/packages/datadog-plugin-graphql/src/utils.js +5 -5
  99. package/packages/datadog-plugin-http/src/client.js +32 -9
  100. package/packages/datadog-plugin-http2/src/client.js +38 -13
  101. package/packages/datadog-plugin-jest/src/index.js +25 -3
  102. package/packages/datadog-plugin-mocha/src/index.js +47 -6
  103. package/packages/datadog-plugin-next/src/index.js +112 -14
  104. package/packages/datadog-plugin-oracledb/src/connection-parser.js +21 -11
  105. package/packages/datadog-plugin-playwright/src/index.js +4 -0
  106. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +5 -3
  107. package/packages/datadog-plugin-react-router/src/index.js +118 -0
  108. package/packages/datadog-plugin-trpc/src/index.js +15 -0
  109. package/packages/datadog-plugin-trpc/src/procedure.js +48 -0
  110. package/packages/datadog-plugin-trpc/src/request.js +81 -0
  111. package/packages/datadog-plugin-typesafe/src/index.js +17 -0
  112. package/packages/datadog-plugin-typesafe/src/tracing.js +31 -0
  113. package/packages/datadog-plugin-undici/src/index.js +22 -7
  114. package/packages/datadog-plugin-vitest/src/index.js +8 -0
  115. package/packages/datadog-turbopack/index.js +4 -28
  116. package/packages/datadog-turbopack/src/loader.js +14 -452
  117. package/packages/datadog-webpack/index.js +3 -55
  118. package/packages/dd-trace/src/agent/info.js +2 -1
  119. package/packages/dd-trace/src/aiguard/evaluation.js +62 -1
  120. package/packages/dd-trace/src/aiguard/sdk.js +8 -13
  121. package/packages/dd-trace/src/aiguard/tags.js +2 -0
  122. package/packages/dd-trace/src/appsec/blocking/index.js +4 -0
  123. package/packages/dd-trace/src/appsec/graphql.js +91 -6
  124. package/packages/dd-trace/src/appsec/recommended.json +1287 -90
  125. package/packages/dd-trace/src/before-exit.js +32 -0
  126. package/packages/dd-trace/src/bootstrap.js +5 -3
  127. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +24 -18
  128. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +16 -36
  129. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +41 -13
  130. package/packages/dd-trace/src/ci-visibility/exporters/request.js +2 -3
  131. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +10 -18
  132. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +10 -15
  133. package/packages/dd-trace/src/ci-visibility/requests/route.js +44 -0
  134. package/packages/dd-trace/src/ci-visibility/telemetry-logs.js +5 -0
  135. package/packages/dd-trace/src/ci-visibility/telemetry.js +6 -0
  136. package/packages/dd-trace/src/ci-visibility/test-annotations.js +72 -0
  137. package/packages/dd-trace/src/ci-visibility/test-declaration-annotations.js +170 -0
  138. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +10 -17
  139. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +9 -134
  140. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +11 -156
  141. package/packages/dd-trace/src/config/config-types.d.ts +3 -0
  142. package/packages/dd-trace/src/config/defaults.js +9 -3
  143. package/packages/dd-trace/src/config/generated-config-types.d.ts +46 -2
  144. package/packages/dd-trace/src/config/index.js +111 -43
  145. package/packages/dd-trace/src/config/parsers.js +18 -1
  146. package/packages/dd-trace/src/config/supported-configurations.json +174 -4
  147. package/packages/dd-trace/src/constants.js +1 -0
  148. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +2 -1
  149. package/packages/dd-trace/src/debugger/probe_sampler.js +6 -6
  150. package/packages/dd-trace/src/encode/0.4.js +2 -2
  151. package/packages/dd-trace/src/esm-module-load.js +58 -0
  152. package/packages/dd-trace/src/exporter.js +23 -15
  153. package/packages/dd-trace/src/exporters/agent/index.js +3 -1
  154. package/packages/dd-trace/src/exporters/agentless/index.js +3 -1
  155. package/packages/dd-trace/src/exporters/common/request.js +83 -50
  156. package/packages/dd-trace/src/exporters/common/retry.js +12 -7
  157. package/packages/dd-trace/src/exporters/common/url.js +1 -1
  158. package/packages/dd-trace/src/exporters/llmobs/index.js +135 -0
  159. package/packages/dd-trace/src/exporters/log/index.js +4 -3
  160. package/packages/dd-trace/src/id.js +1 -1
  161. package/packages/dd-trace/src/lambda/facade.js +74 -0
  162. package/packages/dd-trace/src/lambda/handler.js +3 -41
  163. package/packages/dd-trace/src/lambda/index.js +38 -15
  164. package/packages/dd-trace/src/lambda/runtime/patch.js +19 -3
  165. package/packages/dd-trace/src/lambda/wrap.js +44 -0
  166. package/packages/dd-trace/src/llmobs/constants/tags.js +3 -0
  167. package/packages/dd-trace/src/llmobs/experiments/experiment.js +10 -5
  168. package/packages/dd-trace/src/llmobs/experiments/index.js +2 -3
  169. package/packages/dd-trace/src/llmobs/experiments/noop.js +5 -2
  170. package/packages/dd-trace/src/llmobs/index.js +13 -2
  171. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +1 -1
  172. package/packages/dd-trace/src/llmobs/plugins/elevenlabs.js +96 -0
  173. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +1 -1
  174. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +27 -10
  175. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +38 -11
  176. package/packages/dd-trace/src/llmobs/plugins/typesafe/index.js +102 -0
  177. package/packages/dd-trace/src/llmobs/plugins/vertexai.js +10 -2
  178. package/packages/dd-trace/src/llmobs/prompts/cache.js +3 -1
  179. package/packages/dd-trace/src/llmobs/sdk.js +21 -1
  180. package/packages/dd-trace/src/llmobs/span_processor.js +219 -12
  181. package/packages/dd-trace/src/llmobs/tagger.js +25 -0
  182. package/packages/dd-trace/src/llmobs/writers/util.js +3 -3
  183. package/packages/dd-trace/src/log/channels.js +4 -0
  184. package/packages/dd-trace/src/log/writer.js +13 -2
  185. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +68 -6
  186. package/packages/dd-trace/src/openfeature/configuration_source.js +41 -17
  187. package/packages/dd-trace/src/openfeature/debug-logging-hook.js +66 -3
  188. package/packages/dd-trace/src/openfeature/exposure-hook.js +185 -0
  189. package/packages/dd-trace/src/openfeature/flag-selection.js +152 -0
  190. package/packages/dd-trace/src/openfeature/flagging_provider.js +58 -14
  191. package/packages/dd-trace/src/openfeature/remote_config.js +16 -3
  192. package/packages/dd-trace/src/openfeature/writers/base.js +63 -30
  193. package/packages/dd-trace/src/openfeature/writers/exposures.js +161 -1
  194. package/packages/dd-trace/src/openfeature/writers/flag-eval-evp-hook.js +5 -0
  195. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-aggregation.js +9 -4
  196. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-payload.js +2 -0
  197. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-pii.js +2 -0
  198. package/packages/dd-trace/src/openfeature/writers/split-features.js +25 -0
  199. package/packages/dd-trace/src/opentelemetry/logs/index.js +11 -0
  200. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +1 -1
  201. package/packages/dd-trace/src/opentelemetry/metrics/index.js +7 -1
  202. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +1 -1
  203. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +4 -1
  204. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +2 -2
  205. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +19 -1
  206. package/packages/dd-trace/src/opentelemetry/span-ending-hook.js +5 -1
  207. package/packages/dd-trace/src/opentelemetry/span-helpers.js +6 -1
  208. package/packages/dd-trace/src/opentelemetry/span.js +2 -2
  209. package/packages/dd-trace/src/opentelemetry/startup-config.js +174 -0
  210. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +1 -1
  211. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +7 -1
  212. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +5 -1
  213. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +77 -23
  214. package/packages/dd-trace/src/opentracing/tracer.js +33 -13
  215. package/packages/dd-trace/src/otel-thread-ctx.js +72 -49
  216. package/packages/dd-trace/src/plugin_manager.js +34 -7
  217. package/packages/dd-trace/src/plugins/ci_plugin.js +45 -14
  218. package/packages/dd-trace/src/plugins/index.js +9 -0
  219. package/packages/dd-trace/src/plugins/plugin.js +4 -2
  220. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  221. package/packages/dd-trace/src/plugins/util/ci.js +18 -1
  222. package/packages/dd-trace/src/plugins/util/git-cache.js +4 -4
  223. package/packages/dd-trace/src/plugins/util/git.js +273 -86
  224. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +77 -50
  225. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +12 -4
  226. package/packages/dd-trace/src/plugins/util/status-validator.js +23 -10
  227. package/packages/dd-trace/src/plugins/util/tags.js +6 -0
  228. package/packages/dd-trace/src/plugins/util/test.js +90 -45
  229. package/packages/dd-trace/src/plugins/util/url.js +10 -2
  230. package/packages/dd-trace/src/plugins/util/user-provided-git.js +2 -2
  231. package/packages/dd-trace/src/plugins/util/web.js +81 -10
  232. package/packages/dd-trace/src/process-tags/index.js +1 -1
  233. package/packages/dd-trace/src/profiling/config.js +6 -3
  234. package/packages/dd-trace/src/profiling/webspan-utils.js +6 -5
  235. package/packages/dd-trace/src/proxy.js +48 -57
  236. package/packages/dd-trace/src/serverless.js +3 -2
  237. package/packages/dd-trace/src/span_processor.js +41 -9
  238. package/packages/dd-trace/src/span_stats.js +28 -2
  239. package/packages/dd-trace/src/startup-log.js +8 -5
  240. package/packages/dd-trace/src/tagger.js +7 -5
  241. package/packages/dd-trace/src/telemetry/dependencies.js +4 -0
  242. package/packages/dd-trace/src/telemetry/index.js +3 -0
  243. package/packages/dd-trace/src/telemetry/logs/index.js +21 -2
  244. package/packages/dd-trace/src/telemetry/logs/log-collector.js +1 -0
  245. package/packages/dd-trace/src/telemetry/metrics.js +2 -1
  246. package/packages/dd-trace/src/telemetry/telemetry.js +10 -3
  247. package/packages/dd-trace/src/tracer.js +0 -2
  248. package/packages/dd-trace/src/util.js +1 -1
  249. package/packages/dd-trace/src/web-tags-cache.js +8 -9
  250. package/register.js +4 -2
  251. package/vendor/dist/@apm-js-collab/code-transformer/LICENSE +489 -0
  252. package/vendor/dist/{@opentelemetry/resources → @datadog/flagging-core}/LICENSE +22 -2
  253. package/vendor/dist/@datadog/flagging-core/index.js +1 -0
  254. package/vendor/dist/@datadog/openfeature-node-server/LICENSE +21 -1
  255. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
  256. package/vendor/dist/@datadog/openfeature-node-server/rules-based/LICENSE +3 -1
  257. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.d.ts +78 -0
  258. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.js +1 -1
  259. package/vendor/dist/@datadog/sketches-js/LICENSE +263 -0
  260. package/vendor/dist/@datadog/source-map/LICENSE +1 -0
  261. package/vendor/dist/@isaacs/ttlcache/LICENSE +13 -0
  262. package/vendor/dist/@opentelemetry/core/LICENSE +209 -1
  263. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  264. package/vendor/dist/crypto-randomuuid/LICENSE +3 -0
  265. package/vendor/dist/escape-string-regexp/LICENSE +13 -0
  266. package/vendor/dist/esquery/LICENSE +2 -0
  267. package/vendor/dist/https-proxy-agent/LICENSE +80 -1
  268. package/vendor/dist/istanbul-lib-coverage/LICENSE +2 -0
  269. package/vendor/dist/jest-docblock/LICENSE +16 -0
  270. package/vendor/dist/jsonpath-plus/LICENSE +13 -0
  271. package/vendor/dist/limiter/LICENSE +2 -0
  272. package/vendor/dist/lodash.sortby/LICENSE +2 -0
  273. package/vendor/dist/lru-cache/LICENSE +13 -0
  274. package/vendor/dist/meriyah/LICENSE +13 -0
  275. package/vendor/dist/module-details-from-path/LICENSE +2 -0
  276. package/vendor/dist/mutexify/promise/LICENSE +28 -0
  277. package/vendor/dist/pprof-format/LICENSE +13 -0
  278. package/vendor/dist/pprof-format/index.js +1 -1
  279. package/vendor/dist/protobufjs/LICENSE +219 -0
  280. package/vendor/dist/protobufjs/minimal/LICENSE +219 -0
  281. package/vendor/dist/proxy-from-env/LICENSE +13 -0
  282. package/vendor/dist/retry/LICENSE +2 -0
  283. package/vendor/dist/rfdc/LICENSE +2 -0
  284. package/vendor/dist/semifies/LICENSE +3 -1
  285. package/vendor/dist/shell-quote/LICENSE +3 -1
  286. package/vendor/dist/source-map/LICENSE +1 -0
  287. package/vendor/dist/source-map/lib/util/LICENSE +1 -0
  288. package/vendor/dist/tlhunter-sorted-set/LICENSE +2 -0
  289. package/vendor/dist/ttl-set/LICENSE +28 -0
  290. package/ci/diagnose.js +0 -2215
  291. package/ci/runbook.md +0 -299
  292. package/ci/test-optimization-validation/approval-artifacts.js +0 -175
  293. package/ci/test-optimization-validation/approval.js +0 -386
  294. package/ci/test-optimization-validation/artifact-id.js +0 -19
  295. package/ci/test-optimization-validation/blocker-category.js +0 -24
  296. package/ci/test-optimization-validation/bounded-json.js +0 -120
  297. package/ci/test-optimization-validation/ci-command-candidate.js +0 -77
  298. package/ci/test-optimization-validation/ci-discovery.js +0 -192
  299. package/ci/test-optimization-validation/ci-package-scripts.js +0 -169
  300. package/ci/test-optimization-validation/ci-remediation.js +0 -283
  301. package/ci/test-optimization-validation/cli.js +0 -954
  302. package/ci/test-optimization-validation/command-blocker.js +0 -377
  303. package/ci/test-optimization-validation/command-output-policy.js +0 -188
  304. package/ci/test-optimization-validation/command-runner.js +0 -650
  305. package/ci/test-optimization-validation/environment.js +0 -88
  306. package/ci/test-optimization-validation/executable-approval.js +0 -47
  307. package/ci/test-optimization-validation/executable.js +0 -244
  308. package/ci/test-optimization-validation/execution-lock.js +0 -70
  309. package/ci/test-optimization-validation/framework-adapters/cucumber-validation.json +0 -3
  310. package/ci/test-optimization-validation/framework-adapters/cucumber.js +0 -767
  311. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -99
  312. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -175
  313. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -513
  314. package/ci/test-optimization-validation/generated-file-policy.js +0 -63
  315. package/ci/test-optimization-validation/generated-files.js +0 -425
  316. package/ci/test-optimization-validation/generated-test-contract.js +0 -284
  317. package/ci/test-optimization-validation/generated-verifier.js +0 -235
  318. package/ci/test-optimization-validation/literal-environment.js +0 -56
  319. package/ci/test-optimization-validation/literal-glob.js +0 -52
  320. package/ci/test-optimization-validation/manifest-loader.js +0 -116
  321. package/ci/test-optimization-validation/manifest-scaffold.js +0 -1276
  322. package/ci/test-optimization-validation/manifest-schema.js +0 -695
  323. package/ci/test-optimization-validation/offline-fixtures.js +0 -335
  324. package/ci/test-optimization-validation/offline-output.js +0 -406
  325. package/ci/test-optimization-validation/package-check.js +0 -97
  326. package/ci/test-optimization-validation/payload-normalizer.js +0 -72
  327. package/ci/test-optimization-validation/plan-writer.js +0 -541
  328. package/ci/test-optimization-validation/preflight-runner.js +0 -186
  329. package/ci/test-optimization-validation/project-build-artifact.js +0 -31
  330. package/ci/test-optimization-validation/redaction.js +0 -319
  331. package/ci/test-optimization-validation/report-writer.js +0 -666
  332. package/ci/test-optimization-validation/result-semantics.js +0 -103
  333. package/ci/test-optimization-validation/runner-command.js +0 -264
  334. package/ci/test-optimization-validation/runner-contract.js +0 -695
  335. package/ci/test-optimization-validation/safe-files.js +0 -202
  336. package/ci/test-optimization-validation/scenarios/auto-test-retries.js +0 -171
  337. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -407
  338. package/ci/test-optimization-validation/scenarios/ci-wiring.js +0 -666
  339. package/ci/test-optimization-validation/scenarios/early-flake-detection.js +0 -142
  340. package/ci/test-optimization-validation/scenarios/helpers.js +0 -621
  341. package/ci/test-optimization-validation/scenarios/test-management.js +0 -219
  342. package/ci/test-optimization-validation/source-text.js +0 -84
  343. package/ci/test-optimization-validation/static-diagnosis.js +0 -166
  344. package/ci/test-optimization-validation/test-output.js +0 -120
  345. package/ci/test-optimization-validation/validation-blocker.js +0 -21
  346. package/ci/validate-test-optimization.js +0 -3
  347. package/packages/datadog-esbuild/src/resolver.js +0 -284
  348. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -156
  349. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -287
  350. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/payload-projection.js +0 -84
  351. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -368
  352. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/writer.js +0 -59
  353. package/vendor/dist/@opentelemetry/resources/index.js +0 -1
@@ -3,263 +3,748 @@
3
3
  // No optional chaining or nullish coalescing in this file: Cypress 12 bundles it with webpack 4,
4
4
  // whose parser predates both, and its babel-loader skips node_modules.
5
5
 
6
- let rumFlushWaitMillis = 500
7
- let rumTestExecutionIdCookieName
8
-
9
- let isEarlyFlakeDetectionEnabled = false
10
- let isKnownTestsEnabled = false
11
- let knownTestsForSuite = []
12
- let earlyFlakeDetectionSchedulingRetryCount = 0
13
- let isTestManagementEnabled = false
14
- let testManagementAttemptToFixRetries = 0
15
- let testManagementTests = {}
16
- let isImpactedTestsEnabled = false
17
- let isModifiedTest = false
18
- let isTestIsolationEnabled = false
19
- let isDynamicAtrEnabled = false
6
+ // Passive inspection preserves cached data without evaluating user accessors.
7
+ function browserRetryDescriptor (value, key) {
8
+ for (let current = value; current; current = Object.getPrototypeOf(current)) {
9
+ const property = Object.getOwnPropertyDescriptor(current, key)
10
+ if (property) return property
11
+ }
12
+ }
13
+
14
+ function snapshotBrowserRetries (value, previous, seen = new WeakMap()) {
15
+ if (!value || typeof value !== 'object') return value
16
+ if (seen.has(value)) return seen.get(value)
17
+ const result = Array.isArray(value) ? [] : {}
18
+ seen.set(value, result)
19
+ for (const key in value) {
20
+ const property = browserRetryDescriptor(value, key)
21
+ const entry = property && 'value' in property
22
+ ? snapshotBrowserRetries(property.value, previous && previous[key], seen)
23
+ : previous && previous[key]
24
+ Object.defineProperty(result, key, { value: entry, enumerable: true, writable: true, configurable: true })
25
+ }
26
+ return result
27
+ }
28
+
29
+ function browserRetriesEqual (left, right) {
30
+ const previous = snapshotBrowserRetries(left)
31
+ return Cypress._.isEqual(previous, snapshotBrowserRetries(right, previous))
32
+ }
33
+
34
+ const annotationsKey = Symbol.for('dd-trace:test-annotations')
35
+ const emptyAnnotations = { mustFail: false, noAutoRetry: false }
36
+ let frameworkRetries = 0
37
+ let hasSuiteConfig = false
20
38
  let isTextTerminal = false
21
- let hasWarnedMissingBeforeEachTaskResult = false
22
- let hasWarnedMissingBeforeEachRetryResult = false
23
- // Array of test names that have been retried and the reason
24
- const retryReasonsByTestName = new Map()
25
- // Dynamic ATR computes the selected budget after the first attempt. Keep that result
26
- // in browser state and apply it when Cypress starts the retry runnable.
27
- const dynamicAtrRetryCountByTest = new Map()
28
- // Track test errors suppressed by test management so we can still report them to Datadog.
29
- const suppressedTestFailures = new Map()
30
-
31
- // Track the most recently loaded window in the AUT. Updated via the 'window:load'
32
- // event so we always get the real app window (after cy.visit()), not the
33
- // about:blank window that exists when beforeEach runs. If the test later navigates
34
- // to a cross-origin URL, safeGetRum() handles the access error.
35
- let originalWindow
36
-
37
- let currentTestCommands = []
38
- const commandStartTimes = new Map()
39
- const INTERNAL_CYPRESS_COMMANDS = new Set(['wrap', 'then', 'noop'])
40
-
41
- Cypress.on('command:start', (command) => {
42
- commandStartTimes.set(command.get('id'), { startTime: Date.now(), name: command.get('name') })
43
- })
44
-
45
- Cypress.on('command:end', (command) => {
46
- const id = command.get('id')
47
- const entry = commandStartTimes.get(id)
48
- commandStartTimes.delete(id)
49
-
50
- const name = command.get('name')
51
- const args = command.get('args')
52
- if (name === 'task' && args && typeof args[0] === 'string' && args[0].startsWith('dd:')) {
53
- return
39
+ let hasBrowserRetries = false
40
+ let browserRetries
41
+ const initialBrowserRetries = snapshotBrowserRetries(Cypress.config('retries'))
42
+ let originalRetries
43
+ let configuredRetries
44
+ let browserRetrySelection
45
+ let browserRetryAccessor
46
+ const browserRetryObjects = new WeakMap()
47
+ // Saved options keep their provenance when moved to a different retry root.
48
+ const browserRetryChildren = new WeakMap()
49
+ const browserRetryTargets = new WeakMap()
50
+ const browserConfigStates = new WeakMap()
51
+ const nativeAccessorBudgets = new WeakMap()
52
+ let computingNativeRetries = false
53
+ let nativeRetryValue
54
+ let nativeRetryExperimental
55
+ const unwrapBrowserRetries = value => browserRetryTargets.get(value) || value
56
+ const cypressConfig = Cypress.config
57
+
58
+ // Getter values are mutable native objects. Track the written path, rather than
59
+ // mistaking untouched injected fields for developer configuration.
60
+ function overlayBrowserRetries (native, configured, actual) {
61
+ actual = snapshotBrowserRetries(actual, configured)
62
+ if (browserRetriesEqual(configured, actual)) return snapshotBrowserRetries(native)
63
+ if (!actual || typeof actual !== 'object' || !configured || typeof configured !== 'object') {
64
+ return snapshotBrowserRetries(actual)
54
65
  }
55
- if (INTERNAL_CYPRESS_COMMANDS.has(name) || entry == null) {
56
- return
66
+ if (typeof native === 'number') native = { runMode: native, openMode: native }
67
+ const result = native && typeof native === 'object' ? snapshotBrowserRetries(native) : {}
68
+ for (const key of Object.keys(actual)) {
69
+ if (!browserRetriesEqual(configured[key], actual[key])) {
70
+ result[key] = overlayBrowserRetries(result[key], configured[key], actual[key])
71
+ }
57
72
  }
58
- const err = command.get('err')
59
- currentTestCommands.push({
60
- name,
61
- startTime: entry.startTime,
62
- endTime: Date.now(),
63
- // Serialize the error to a plain object so it survives cy.task JSON transport.
64
- error: err ? { message: err.message, stack: err.stack, name: err.name } : null,
65
- })
66
- })
73
+ for (const key of Object.keys(configured)) {
74
+ // Cypress 6 predates Object.hasOwn.
75
+ // eslint-disable-next-line prefer-object-has-own
76
+ if (!Object.prototype.hasOwnProperty.call(actual, key)) delete result[key]
77
+ }
78
+ return result
79
+ }
67
80
 
68
- // If the test is using multi domain with cy.origin, trying to access
69
- // window properties will result in a cross origin error.
70
- function safeGetRum (window) {
71
- try {
72
- return window.DD_RUM
73
- } catch {
74
- return null
81
+ // Cypress retry objects contain first-level experimental options with primitive fields.
82
+ function rememberBrowserRetryChild (metadata, key, value, explicit) {
83
+ const raw = unwrapBrowserRetries(value)
84
+ if (!raw || typeof raw !== 'object') return
85
+ if (browserRetryChildren.has(raw)) {
86
+ const child = browserRetryChildren.get(raw)
87
+ metadata.children.set(raw, child)
88
+ return child
89
+ }
90
+ const child = {
91
+ owner: metadata,
92
+ raw,
93
+ key,
94
+ initial: snapshotBrowserRetries(raw),
95
+ configured: snapshotBrowserRetries(metadata.observed && metadata.observed[key]),
96
+ observed: snapshotBrowserRetries(raw),
97
+ native: explicit ? snapshotBrowserRetries(raw) : undefined,
98
+ nativeReady: Boolean(explicit),
99
+ writes: [],
75
100
  }
101
+ metadata.children.set(raw, child)
102
+ browserRetryChildren.set(raw, child)
103
+ if (hasSuiteConfig) initializeBrowserRetryChild(child)
104
+ else metadata.pendingChildren.push(child)
105
+ return child
76
106
  }
77
107
 
78
- function isNewTest (test) {
79
- // If for whatever reason the worker does not receive valid known tests, we don't consider it as new
80
- if (!Array.isArray(knownTestsForSuite)) {
81
- return false
108
+ function initializeBrowserRetryChild (child) {
109
+ // A deferred child is initialized from its original root, not the root that later selects it.
110
+ const owner = child.owner
111
+ if (!owner.nativeReady && hasSuiteConfig) initializeBrowserRetryMetadata(owner)
112
+ if (!owner.nativeReady) return
113
+ if (!child.nativeReady) {
114
+ child.native = overlayBrowserRetries(owner.native && owner.native[child.key], child.configured, child.initial)
115
+ child.nativeReady = true
116
+ }
117
+ const writes = child.writes.splice(0)
118
+ if (writes.length) child.observed = snapshotBrowserRetries(child.initial)
119
+ for (const write of writes) {
120
+ if (write.raw) {
121
+ child.native = overlayBrowserRetries(child.native, write.observed, write.raw)
122
+ child.observed = snapshotBrowserRetries(write.raw)
123
+ } else {
124
+ child.native = updateBrowserRetryPath(child.native, [write.key], write.value, write.deleted)
125
+ child.observed = updateBrowserRetryPath(child.observed, [write.key], write.value, write.deleted)
126
+ }
82
127
  }
83
- return !knownTestsForSuite.includes(test.fullTitle())
84
128
  }
85
129
 
86
- function getTestProperties (testName) {
87
- // TODO: Use optional chaining when we drop support for older Cypress versions, which will happen when dd-trace@5 is
88
- // EoL. Until then, this files needs to support Node.js 16.
89
- const properties = testManagementTests[testName] && testManagementTests[testName].properties || {}
130
+ function refreshBrowserRetryChild (metadata, child) {
131
+ if (hasSuiteConfig) {
132
+ initializeBrowserRetryMetadata(metadata)
133
+ initializeBrowserRetryChild(child)
134
+ child.native = overlayBrowserRetries(child.native, child.observed, child.raw)
135
+ } else if (!browserRetriesEqual(child.observed, child.raw)) {
136
+ child.writes.push({ observed: snapshotBrowserRetries(child.observed), raw: snapshotBrowserRetries(child.raw) })
137
+ }
138
+ child.observed = snapshotBrowserRetries(child.raw)
139
+ }
90
140
 
91
- const { attempt_to_fix: isAttemptToFix, disabled: isDisabled, quarantined: isQuarantined } = properties
141
+ function recordBrowserRetryChild (metadata, child, key, value, deleted) {
142
+ if (hasSuiteConfig) {
143
+ initializeBrowserRetryMetadata(metadata)
144
+ initializeBrowserRetryChild(child)
145
+ child.native = updateBrowserRetryPath(child.native, [key], value, deleted)
146
+ } else child.writes.push({ key, value: snapshotBrowserRetries(value), deleted })
147
+ child.observed = updateBrowserRetryPath(child.observed, [key], value, deleted)
148
+ }
92
149
 
93
- return { isAttemptToFix, isDisabled, isQuarantined }
150
+ function captureBrowserRetryChild (metadata, key, value) {
151
+ const child = rememberBrowserRetryChild(metadata, key, value, true)
152
+ if (child) refreshBrowserRetryChild(metadata, child)
153
+ return child
94
154
  }
95
155
 
96
- /**
97
- * @param {string} message
98
- */
99
- function warnMissingBeforeEachTaskResult (message) {
100
- // eslint-disable-next-line no-console
101
- console.warn(message)
156
+ function initializeBrowserRetryMetadata (metadata) {
157
+ if (!hasSuiteConfig) return
158
+ if (!metadata.nativeReady) {
159
+ metadata.native = overlayBrowserRetries(originalRetries, configuredRetries, metadata.initial)
160
+ metadata.nativeReady = true
161
+ }
162
+ const writes = metadata.writes.splice(0)
163
+ for (const child of metadata.pendingChildren.splice(0)) initializeBrowserRetryChild(child)
164
+ if (writes.length) metadata.observed = snapshotBrowserRetries(metadata.initial)
165
+ for (const write of writes) {
166
+ if (write.raw) {
167
+ metadata.native = overlayBrowserRetries(metadata.native, write.observed, write.raw)
168
+ metadata.observed = snapshotBrowserRetries(write.raw)
169
+ selectBrowserRetryMetadata(metadata)
170
+ } else recordBrowserRetryPath(metadata, write.path, write.value, write.deleted, write.child)
171
+ }
102
172
  }
103
173
 
104
174
  /**
105
- * @param {object} test
106
- * @returns {Cypress.Chainable<{ traceId?: string, shouldSkip?: boolean, shouldDiscard?: boolean }>}
175
+ * @param {object|number|undefined} retries
176
+ * @param {Array<string|symbol>} path
177
+ * @param {unknown} value
178
+ * @param {boolean} deleted
107
179
  */
108
- function runBeforeEachTask (test) {
109
- return cy.task('dd:beforeEach', test).then((taskResult) => {
110
- if (taskResult !== undefined && taskResult !== null) {
111
- return taskResult
112
- }
180
+ function updateBrowserRetryPath (retries, path, value, deleted) {
181
+ if (typeof retries === 'number') retries = { runMode: retries, openMode: retries }
182
+ if (!retries || typeof retries !== 'object') retries = {}
183
+ let current = retries
184
+ for (let i = 0; i < path.length - 1; i++) {
185
+ const key = path[i]
186
+ if (!current[key] || typeof current[key] !== 'object') current[key] = {}
187
+ current = current[key]
188
+ }
189
+ // Cypress 6 uses an older browser without Array.prototype.at.
190
+ // eslint-disable-next-line unicorn/prefer-at
191
+ const key = path[path.length - 1]
192
+ if (deleted) delete current[key]
193
+ else current[key] = snapshotBrowserRetries(value)
194
+ return retries
195
+ }
113
196
 
114
- if (!hasWarnedMissingBeforeEachTaskResult) {
115
- hasWarnedMissingBeforeEachTaskResult = true
116
- warnMissingBeforeEachTaskResult('Datadog Cypress dd:beforeEach task returned no result. Retrying once.')
117
- }
197
+ function recordBrowserRetryPath (metadata, path, value, deleted, child) {
198
+ // Track only the known write: unrelated raw aliases can change other paths before selection.
199
+ if (!hasSuiteConfig) {
200
+ metadata.observed = updateBrowserRetryPath(metadata.observed, path, value, deleted)
201
+ metadata.writes.push({ path, value: snapshotBrowserRetries(value), deleted, child })
202
+ return
203
+ }
204
+ initializeBrowserRetryMetadata(metadata)
205
+ metadata.observed = updateBrowserRetryPath(metadata.observed, path, value, deleted)
206
+ if (child) refreshBrowserRetryChild(metadata, child)
207
+ metadata.native = updateBrowserRetryPath(metadata.native, path, child ? child.native : value, deleted)
208
+ selectBrowserRetryMetadata(metadata)
209
+ }
118
210
 
119
- return cy.task('dd:beforeEach', test).then((retryTaskResult) => {
120
- if (retryTaskResult !== undefined && retryTaskResult !== null) {
121
- return retryTaskResult
122
- }
211
+ function peekBrowserRetries () {
212
+ const property = browserRetryDescriptor(cypressConfig.call(Cypress), 'retries')
213
+ if (property && 'value' in property) return property.value
214
+ if (getBrowserRetryAccessor()) return browserRetryAccessor.value
215
+ }
123
216
 
124
- if (!hasWarnedMissingBeforeEachRetryResult) {
125
- hasWarnedMissingBeforeEachRetryResult = true
126
- warnMissingBeforeEachTaskResult(
127
- 'Datadog Cypress dd:beforeEach task returned no result after retry. Continuing with an empty task result.'
128
- )
129
- }
217
+ /** @param {object} metadata */
218
+ function selectBrowserRetryMetadata (metadata) {
219
+ if (metadata.raw === unwrapBrowserRetries(peekBrowserRetries())) {
220
+ browserRetries = metadata.native
221
+ browserRetrySelection = metadata
222
+ hasBrowserRetries = true
223
+ }
224
+ }
130
225
 
131
- return {}
132
- })
133
- })
226
+ /** @param {object} metadata */
227
+ function reconcileBrowserRetryMetadata (metadata) {
228
+ initializeBrowserRetryMetadata(metadata)
229
+ for (const key of Object.keys(metadata.raw)) {
230
+ const property = Object.getOwnPropertyDescriptor(metadata.raw, key)
231
+ const child = property && 'value' in property && metadata.children.get(unwrapBrowserRetries(property.value))
232
+ if (!child) continue
233
+ refreshBrowserRetryChild(metadata, child)
234
+ if (hasSuiteConfig) metadata.native = updateBrowserRetryPath(metadata.native, [key], child.native, false)
235
+ metadata.observed[key] = snapshotBrowserRetries(child.raw)
236
+ }
237
+ if (!hasSuiteConfig) {
238
+ if (!browserRetriesEqual(metadata.observed, metadata.raw)) {
239
+ const raw = snapshotBrowserRetries(metadata.raw)
240
+ metadata.writes.push({ raw, observed: snapshotBrowserRetries(metadata.observed) })
241
+ metadata.observed = snapshotBrowserRetries(raw)
242
+ }
243
+ return
244
+ }
245
+ const changed = !browserRetriesEqual(metadata.observed, metadata.raw)
246
+ metadata.native = overlayBrowserRetries(metadata.native, metadata.observed, metadata.raw)
247
+ metadata.observed = snapshotBrowserRetries(metadata.raw)
248
+ if (changed) selectBrowserRetryMetadata(metadata)
249
+ if (browserRetrySelection === metadata) browserRetries = metadata.native
134
250
  }
135
251
 
136
- /**
137
- * @param {string} message
138
- * @param {unknown} error
139
- * @returns {false}
140
- */
141
- function logRumCorrelationCookieError (message, error) {
142
- try {
143
- Cypress.log({
144
- name: 'dd-trace',
145
- message,
146
- consoleProps: () => ({ Error: error }),
147
- })
148
- } catch (loggingError) {
149
- // eslint-disable-next-line no-console
150
- console.error(message, error, loggingError)
252
+ function ownsNestedPath (root, path, target) {
253
+ let current = root
254
+ for (const key of path) {
255
+ if (!current || typeof current !== 'object') return false
256
+ const property = browserRetryDescriptor(current, key)
257
+ if (!property || !('value' in property)) return false
258
+ current = unwrapBrowserRetries(property.value)
151
259
  }
152
- return false
260
+ return current === target
153
261
  }
154
262
 
155
263
  /**
156
- * @param {unknown} error
157
- * @returns {false}
264
+ * @param {object} target
265
+ * @param {string|symbol} key
266
+ * @param {unknown} value
158
267
  */
159
- function handleRumCorrelationCookieError (error) {
160
- return logRumCorrelationCookieError('Could not set the RUM correlation cookie', error)
268
+ function isSameBrowserObjectValue (target, key, value) {
269
+ const raw = unwrapBrowserRetries(value)
270
+ const previous = Object.getOwnPropertyDescriptor(target, key)
271
+ return raw !== null && typeof raw === 'object' && previous &&
272
+ 'value' in previous && raw === unwrapBrowserRetries(previous.value)
161
273
  }
162
274
 
163
- /**
164
- * @param {unknown} error
165
- * @returns {false}
166
- */
167
- function handleRumCorrelationCookieCleanupError (error) {
168
- return logRumCorrelationCookieError('Could not clear the previous RUM correlation cookie', error)
275
+ function observeBrowserRetries (raw) {
276
+ raw = unwrapBrowserRetries(raw)
277
+ if (!raw || typeof raw !== 'object') return raw
278
+ if (browserRetryObjects.has(raw)) return browserRetryObjects.get(raw).proxy
279
+ const test = Cypress.state('test')
280
+ const applied = test && test._testConfig && test._testConfig.applied
281
+ // Native config cloning also uses this getter while applying/restoring overrides.
282
+ // Explicit root writes already carry native intent and take priority over declarations.
283
+ const overrides = (!hasBrowserRetries || browserRetries !== raw) &&
284
+ (applied === 'complete' || Cypress.state('duringUserTestExecution')) && getNativeRetryOverrides(test)
285
+ const metadata = {
286
+ raw,
287
+ initial: snapshotBrowserRetries(raw),
288
+ observed: snapshotBrowserRetries(raw),
289
+ reconcileOnRead: false,
290
+ native: snapshotBrowserRetries(
291
+ overrides ? overrides.retries : hasBrowserRetries ? browserRetries : originalRetries
292
+ ),
293
+ nativeReady: Boolean(overrides) || hasSuiteConfig || hasBrowserRetries,
294
+ writes: [],
295
+ children: new WeakMap(),
296
+ pendingChildren: [],
297
+ }
298
+ for (const key of Object.keys(raw)) {
299
+ const property = Object.getOwnPropertyDescriptor(raw, key)
300
+ if (property && 'value' in property) rememberBrowserRetryChild(metadata, key, property.value, false)
301
+ }
302
+ const proxies = new WeakMap()
303
+ function wrap (value, path) {
304
+ value = unwrapBrowserRetries(value)
305
+ if (!value || typeof value !== 'object') return value
306
+ if (proxies.has(value)) return proxies.get(value)
307
+ const child = path.length === 1 && rememberBrowserRetryChild(metadata, path[0], value, false)
308
+ const proxy = new Proxy(value, {
309
+ getOwnPropertyDescriptor (target, key) {
310
+ const property = Reflect.getOwnPropertyDescriptor(target, key)
311
+ if (property && 'value' in property && property.value && typeof property.value === 'object' &&
312
+ ownsNestedPath(metadata.raw, path, target)) metadata.reconcileOnRead = true
313
+ return property
314
+ },
315
+ get (target, key) {
316
+ const result = Reflect.get(target, key)
317
+ if (computingNativeRetries && !path.length && key === 'experimentalStrategy') {
318
+ nativeRetryExperimental = Boolean(result)
319
+ }
320
+ const property = Object.getOwnPropertyDescriptor(target, key)
321
+ if (property && !property.configurable && !property.writable && 'value' in property) {
322
+ if (result && typeof result === 'object' && ownsNestedPath(metadata.raw, path, target)) {
323
+ metadata.reconcileOnRead = true
324
+ }
325
+ return result
326
+ }
327
+ return wrap(result, [...path, key])
328
+ },
329
+ set (target, key, value) {
330
+ const sameObject = isSameBrowserObjectValue(target, key, value)
331
+ const previous = !path.length && Object.getOwnPropertyDescriptor(target, key)
332
+ const previousChild = previous && 'value' in previous &&
333
+ metadata.children.get(unwrapBrowserRetries(previous.value))
334
+ if (previousChild) refreshBrowserRetryChild(metadata, previousChild)
335
+ const result = Reflect.set(target, key, unwrapBrowserRetries(value))
336
+ if (result && child) {
337
+ if (sameObject) refreshBrowserRetryChild(metadata, child)
338
+ else recordBrowserRetryChild(metadata, child, key, value, false)
339
+ }
340
+ if (result && ownsNestedPath(metadata.raw, path, target)) {
341
+ if (sameObject) {
342
+ metadata.reconcileOnRead = true
343
+ reconcileBrowserRetryMetadata(metadata)
344
+ } else {
345
+ const restored = !path.length && captureBrowserRetryChild(metadata, key, value)
346
+ recordBrowserRetryPath(metadata, [...path, key], value, false, restored)
347
+ }
348
+ }
349
+ return result
350
+ },
351
+ defineProperty (target, key, descriptor) {
352
+ const hasValue = 'value' in descriptor
353
+ const sameObject = hasValue && isSameBrowserObjectValue(target, key, descriptor.value)
354
+ const previous = !path.length && hasValue && Object.getOwnPropertyDescriptor(target, key)
355
+ const previousChild = previous && 'value' in previous &&
356
+ metadata.children.get(unwrapBrowserRetries(previous.value))
357
+ if (previousChild) refreshBrowserRetryChild(metadata, previousChild)
358
+ const result = Reflect.defineProperty(target, key, descriptor)
359
+ const property = result && Object.getOwnPropertyDescriptor(target, key)
360
+ if (property && !('value' in property)) {
361
+ metadata.reconcileOnRead = true
362
+ return result
363
+ }
364
+ if (result && child) {
365
+ if (hasValue && !sameObject) recordBrowserRetryChild(metadata, child, key, descriptor.value, false)
366
+ else refreshBrowserRetryChild(metadata, child)
367
+ }
368
+ if (result && ownsNestedPath(metadata.raw, path, target)) {
369
+ if (hasValue && !sameObject) {
370
+ const restored = !path.length && captureBrowserRetryChild(metadata, key, descriptor.value)
371
+ recordBrowserRetryPath(metadata, [...path, key], descriptor.value, false, restored)
372
+ } else {
373
+ metadata.reconcileOnRead = true
374
+ reconcileBrowserRetryMetadata(metadata)
375
+ }
376
+ }
377
+ return result
378
+ },
379
+ deleteProperty (target, key) {
380
+ const result = Reflect.deleteProperty(target, key)
381
+ if (result && child) recordBrowserRetryChild(metadata, child, key, undefined, true)
382
+ if (result && ownsNestedPath(metadata.raw, path, target)) {
383
+ recordBrowserRetryPath(metadata, [...path, key], undefined, true)
384
+ }
385
+ return result
386
+ },
387
+ })
388
+ proxies.set(value, proxy)
389
+ browserRetryTargets.set(proxy, value)
390
+ return proxy
391
+ }
392
+ metadata.proxy = wrap(raw, [])
393
+ browserRetryObjects.set(raw, metadata)
394
+ browserRetryObjects.set(metadata.proxy, metadata)
395
+ return metadata.proxy
169
396
  }
170
397
 
171
- /**
172
- * @param {string} traceId
173
- * @returns {Promise<boolean>}
174
- */
175
- function setRumCorrelationCookie (traceId) {
176
- if (typeof cy.now !== 'function') {
177
- return Cypress.Promise.resolve(handleRumCorrelationCookieError(new Error('Cypress cy.now is not available')))
398
+ // New root values are explicit native configuration. Reusing the same observed
399
+ // object preserves its field provenance, including through Cypress restoration.
400
+ function recordBrowserRetryReplacement (retries, previous) {
401
+ retries = unwrapBrowserRetries(retries)
402
+ const test = Cypress.state('test')
403
+ const applied = test && test._testConfig && test._testConfig.applied
404
+ if (applied === 'restoring') {
405
+ const metadata = retries && typeof retries === 'object' && browserRetryObjects.get(retries)
406
+ if (metadata) reconcileBrowserRetryMetadata(metadata)
407
+ browserRetries = metadata ? metadata.native : overlayBrowserRetries(originalRetries, configuredRetries, retries)
408
+ browserRetrySelection = metadata || undefined
409
+ hasBrowserRetries = true
410
+ } else if (!applied || applied === 'complete' || Cypress.state('duringUserTestExecution')) {
411
+ if (retries && typeof retries === 'object' && retries === unwrapBrowserRetries(previous)) return
412
+ const metadata = retries && typeof retries === 'object' && browserRetryObjects.get(retries)
413
+ if (metadata) reconcileBrowserRetryMetadata(metadata)
414
+ browserRetrySelection = metadata || undefined
415
+ browserRetries = metadata ? metadata.native : retries
416
+ hasBrowserRetries = true
178
417
  }
418
+ }
419
+
420
+ /** @param {object|number|undefined} value */
421
+ function observeLockedBrowserRetries (value) {
422
+ observeBrowserRetries(value)
423
+ const metadata = value && typeof value === 'object' && browserRetryObjects.get(unwrapBrowserRetries(value))
424
+ if (metadata) metadata.reconcileOnRead = true
425
+ }
426
+
427
+ // An accessor's value is native intent, but defining or inspecting it must not run its getter.
428
+ function getBrowserRetryAccessor () {
429
+ if (!browserRetryAccessor) return
430
+ const property = Object.getOwnPropertyDescriptor(browserRetryAccessor.state, 'retries')
431
+ if (property && !('value' in property) && property.get === browserRetryAccessor.get &&
432
+ property.set === browserRetryAccessor.set) return property
433
+ browserRetryAccessor = undefined
434
+ }
435
+
436
+ function recordBrowserRetryAccessorRead (value) {
437
+ if (computingNativeRetries) nativeRetryValue = value
438
+ if (!getBrowserRetryAccessor()) return
439
+ browserRetryAccessor.value = value
440
+ const raw = unwrapBrowserRetries(value)
441
+ const metadata = raw && typeof raw === 'object' && browserRetryObjects.get(raw)
442
+ browserRetrySelection = metadata || undefined
443
+ browserRetries = metadata ? metadata.native : raw
444
+ hasBrowserRetries = true
445
+ }
446
+
447
+ function observeBrowserConfig (state) {
448
+ if (browserConfigStates.has(state)) return browserConfigStates.get(state)
449
+ const proxy = new Proxy(state, {
450
+ getOwnPropertyDescriptor (target, key) {
451
+ const property = Reflect.getOwnPropertyDescriptor(target, key)
452
+ if (key === 'retries' && property && 'value' in property) observeLockedBrowserRetries(property.value)
453
+ return property
454
+ },
455
+ get (target, key) {
456
+ const value = Reflect.get(target, key)
457
+ const property = Object.getOwnPropertyDescriptor(target, key)
458
+ if (key === 'retries') recordBrowserRetryAccessorRead(value)
459
+ if (property && !property.configurable && !property.writable && 'value' in property) {
460
+ if (key === 'retries') observeLockedBrowserRetries(value)
461
+ return value
462
+ }
463
+ return key === 'retries' ? observeBrowserRetries(value) : value
464
+ },
465
+ set (target, key, value) {
466
+ const previousProperty = Object.getOwnPropertyDescriptor(target, key)
467
+ const previous = previousProperty && previousProperty.value
468
+ const result = Reflect.set(target, key, key === 'retries' ? unwrapBrowserRetries(value) : value)
469
+ if (result && key === 'retries') recordBrowserRetryReplacement(value, previous)
470
+ return result
471
+ },
472
+ defineProperty (target, key, descriptor) {
473
+ const hasValue = 'value' in descriptor
474
+ const previousProperty = key === 'retries' && hasValue && Object.getOwnPropertyDescriptor(target, key)
475
+ const previous = previousProperty && previousProperty.value
476
+ const result = Reflect.defineProperty(target, key, descriptor)
477
+ if (result && key === 'retries') {
478
+ if (hasValue) recordBrowserRetryReplacement(descriptor.value, previous)
479
+ const property = Object.getOwnPropertyDescriptor(target, key)
480
+ browserRetryAccessor = property && !('value' in property)
481
+ ? { state: target, get: property.get, set: property.set }
482
+ : undefined
483
+ if (property && !property.configurable && !property.writable && 'value' in property) {
484
+ observeLockedBrowserRetries(property.value)
485
+ }
486
+ }
487
+ return result
488
+ },
489
+ deleteProperty (target, key) {
490
+ const previousProperty = Object.getOwnPropertyDescriptor(target, key)
491
+ const previous = previousProperty && previousProperty.value
492
+ const result = Reflect.deleteProperty(target, key)
493
+ if (result && key === 'retries') recordBrowserRetryReplacement(undefined, previous)
494
+ return result
495
+ },
496
+ })
497
+ browserConfigStates.set(state, proxy)
498
+ return proxy
499
+ }
500
+
501
+ function hasNativeRetryAccessor () {
502
+ const state = cypressConfig.call(Cypress)
503
+ const root = browserRetryDescriptor(state, 'retries')
504
+ if (!root) return false
505
+ if (!('value' in root)) return true
506
+ const retries = unwrapBrowserRetries(root.value)
507
+ if (!retries || typeof retries !== 'object') return false
508
+ const interactive = browserRetryDescriptor(state, 'isInteractive')
509
+ return hasNativeRetryValueAccessor(retries, interactive && interactive.value)
510
+ }
511
+
512
+ function hasNativeRetryValueAccessor (retries, interactive) {
513
+ const mode = browserRetryDescriptor(retries, interactive ? 'openMode' : 'runMode')
514
+ if (mode && !('value' in mode)) return true
515
+ if (!mode || mode.value !== true) return false
516
+ const strategy = browserRetryDescriptor(retries, 'experimentalStrategy')
517
+ if (strategy && !('value' in strategy)) return true
518
+ if (!strategy || !strategy.value) return false
519
+ const options = browserRetryDescriptor(retries, 'experimentalOptions')
520
+ if (options && !('value' in options)) return true
521
+ const maximum = options && options.value && browserRetryDescriptor(options.value, 'maxRetries')
522
+ return Boolean(maximum && !('value' in maximum))
523
+ }
524
+
525
+ if (typeof Cypress.getTestRetries === 'function') {
526
+ const getTestRetries = Cypress.getTestRetries
527
+ Cypress.getTestRetries = Object.assign(function () {
528
+ const accessor = hasNativeRetryAccessor()
529
+ nativeRetryValue = undefined
530
+ nativeRetryExperimental = undefined
531
+ computingNativeRetries = true
532
+ let retries
533
+ try {
534
+ retries = Reflect.apply(getTestRetries, this, arguments)
535
+ } finally {
536
+ computingNativeRetries = false
537
+ }
538
+ const value = unwrapBrowserRetries(nativeRetryValue)
539
+ const metadata = value && typeof value === 'object' && browserRetryObjects.get(value)
540
+ const state = cypressConfig.call(Cypress)
541
+ const interactive = browserRetryDescriptor(state, 'isInteractive')
542
+ const knownRoot = metadata && !hasNativeRetryValueAccessor(value, interactive && interactive.value)
543
+ const strategy = value && typeof value === 'object' && browserRetryDescriptor(value, 'experimentalStrategy')
544
+ const experimental = nativeRetryExperimental === undefined
545
+ ? Boolean(strategy && 'value' in strategy && strategy.value)
546
+ : nativeRetryExperimental
547
+ const test = Cypress.state('test')
548
+ if (test && typeof test === 'object') {
549
+ nativeAccessorBudgets.set(test, { accessor, retries, metadata: knownRoot && metadata, experimental })
550
+ }
551
+ return retries
552
+ }, getTestRetries)
553
+ }
179
554
 
180
- let clearCookiePromise = Cypress.Promise.resolve()
181
- if (!isTestIsolationEnabled) {
182
- clearCookiePromise = Cypress.Promise.try(() => {
183
- return cy.now('clearCookie', rumTestExecutionIdCookieName, { log: false })
184
- }).then(undefined, handleRumCorrelationCookieCleanupError)
555
+ Cypress.config = Object.assign(function (key, value) {
556
+ const objectConfig = typeof key === 'object' && key !== null
557
+ let objectRetries = false
558
+ if (objectConfig) {
559
+ // Native _.extend handles enumerable own/inherited string keys without reading symbols.
560
+ for (const name in key) {
561
+ if (name === 'retries') objectRetries = true
562
+ }
185
563
  }
564
+ const retries = !objectConfig && key === 'retries' && arguments.length > 1 ? value : undefined
565
+ const previous = (!objectRetries && retries === undefined) || getBrowserRetryAccessor()
566
+ ? undefined
567
+ : cypressConfig.call(this, 'retries')
568
+ const args = [...arguments]
569
+ if (retries !== undefined && unwrapBrowserRetries(retries) !== retries) args[1] = unwrapBrowserRetries(retries)
570
+ // Delegate the original object so validation and assignment retain native getter evaluation semantics.
571
+ const result = cypressConfig.apply(this, args)
572
+ if (objectRetries) {
573
+ const property = Object.getOwnPropertyDescriptor(cypressConfig.call(this), 'retries')
574
+ if (property && 'value' in property) recordBrowserRetryReplacement(property.value, previous)
575
+ } else if (retries !== undefined) recordBrowserRetryReplacement(retries, previous)
576
+ if (arguments.length === 0) return observeBrowserConfig(result)
577
+ if (key === 'retries' && arguments.length === 1) recordBrowserRetryAccessorRead(result)
578
+ return key === 'retries' && arguments.length === 1 ? observeBrowserRetries(result) : result
579
+ }, cypressConfig)
580
+
581
+ /** @param {number|object|undefined} configured */
582
+ function nativeRetryCount (configured) {
583
+ if (typeof configured === 'number' || configured == null) return configured
584
+ const retries = configured[isTextTerminal ? 'runMode' : 'openMode']
585
+ return retries === true
586
+ ? configured.experimentalOptions && configured.experimentalOptions.maxRetries
587
+ : retries === false ? 0 : retries
588
+ }
186
589
 
187
- return clearCookiePromise.then(() => {
188
- return Cypress.Promise.try(() => {
189
- return cy.now('setCookie', rumTestExecutionIdCookieName, traceId, { log: false })
590
+ /** @param {object} test */
591
+ function getTestAnnotations (test) {
592
+ return test._ddTestAnnotations || (test.fn && test.fn[annotationsKey]) || emptyAnnotations
593
+ }
594
+
595
+ /** @returns {object[]} Declaration metadata, including tests whose setup never executes. */
596
+ function getTestDeclarations () {
597
+ const testAnnotations = []
598
+ Cypress.mocha.getRootSuite().eachTest(test => {
599
+ const annotations = getTestAnnotations(test)
600
+ testAnnotations.push({
601
+ testId: test.id, testName: test.fullTitle(), mustFail: annotations.mustFail, noAutoRetry: annotations.noAutoRetry,
190
602
  })
191
- }).then(() => true, handleRumCorrelationCookieError)
603
+ })
604
+ return testAnnotations
605
+ }
606
+
607
+ let pendingSuiteDeclarationDepth = 0
608
+ const testDeclarationProxies = new WeakMap()
609
+
610
+ function captureTestDeclaration (target, receiver, args) {
611
+ // Cypress 6 uses a browser without Array.prototype.at.
612
+ // eslint-disable-next-line unicorn/prefer-at
613
+ const callback = args[args.length - 1]
614
+ const test = Reflect.apply(target, receiver, args)
615
+ if (test && typeof callback === 'function' && callback[annotationsKey]) {
616
+ const { mustFail, noAutoRetry } = callback[annotationsKey]
617
+ test._ddTestAnnotations = { mustFail, noAutoRetry }
618
+ }
619
+ return test
192
620
  }
193
621
 
194
622
  /**
195
- * @param {boolean} isCookieSet
623
+ * @param {Function} declaration
624
+ * @param {boolean} [alwaysCapture]
196
625
  */
197
- function restartRumSession (isCookieSet) {
198
- if (!isCookieSet || isTestIsolationEnabled || !originalWindow) {
199
- return
626
+ function wrapTestDeclaration (declaration, alwaysCapture = false) {
627
+ if (testDeclarationProxies.has(declaration)) {
628
+ const existing = testDeclarationProxies.get(declaration)
629
+ if (alwaysCapture) existing.alwaysCapture = true
630
+ return existing.proxy
631
+ }
632
+ const state = { alwaysCapture }
633
+ state.proxy = new Proxy(declaration, {
634
+ // Outside pending declarations, the intrinsic handler contributes no JavaScript
635
+ // wrapper frame to Cypress's native callsite stack. Aliases retain this same proxy.
636
+ get apply () {
637
+ return state.alwaysCapture || pendingSuiteDeclarationDepth > 0 ? captureTestDeclaration : Reflect.apply
638
+ },
639
+ get (target, key, receiver) {
640
+ const value = Reflect.get(target, key, receiver)
641
+ const property = Object.getOwnPropertyDescriptor(target, key)
642
+ if (property && !property.configurable && !property.writable && 'value' in property) return value
643
+ return (key === 'skip' || key === 'only') && typeof value === 'function'
644
+ ? wrapTestDeclaration(value, key === 'skip' || state.alwaysCapture)
645
+ : value
646
+ },
647
+ })
648
+ testDeclarationProxies.set(declaration, state)
649
+ return state.proxy
650
+ }
651
+
652
+ // Observe every executable declaration identity, including aliases captured before
653
+ // entering a pending suite, while preserving native callsites during normal execution.
654
+ for (const name of ['it', 'specify', 'xit', 'xspecify']) {
655
+ const declaration = globalThis[name]
656
+ if (typeof declaration === 'function') {
657
+ globalThis[name] = wrapTestDeclaration(declaration, name === 'xit' || name === 'xspecify')
200
658
  }
659
+ }
201
660
 
202
- const rum = safeGetRum(originalWindow)
203
- if (rum) {
661
+ /** @param {Function} declaration */
662
+ function wrapSkippedSuiteDeclaration (declaration) {
663
+ return function () {
664
+ pendingSuiteDeclarationDepth++
204
665
  try {
205
- const evt = new originalWindow.MouseEvent('click', { bubbles: true, cancelable: true })
206
- // The browser-sdk addEventListener wrapper filters out untrusted synthetic events
207
- // unless __ddIsTrusted is set. Set it so the click triggers expandOrRenewSession().
208
- // See: https://github.com/DataDog/browser-sdk/blob/v6.27.1/packages/core/src/browser/addEventListener.ts#L119
209
- Object.defineProperty(evt, '__ddIsTrusted', { value: true })
210
- originalWindow.dispatchEvent(evt)
211
- } catch {}
212
- if (rum.startView) {
213
- rum.startView()
666
+ return declaration.apply(this, arguments)
667
+ } finally {
668
+ pendingSuiteDeclarationDepth--
214
669
  }
215
670
  }
216
671
  }
217
672
 
218
- // Catch test failures for quarantined tests and suppress them
219
- // By not re-throwing the error, Cypress marks the test as passed
220
- // This allows quarantined tests to run but not affect the exit code
221
- Cypress.on('fail', (err, runnable) => {
222
- // For commands that time out, command:end may never fire.
223
- // Finalize any in-flight commands so their step spans carry the error.
224
- const hadInFlightCommands = commandStartTimes.size > 0
225
- for (const [, { startTime, name }] of commandStartTimes) {
226
- if (INTERNAL_CYPRESS_COMMANDS.has(name)) continue
227
- currentTestCommands.push({
228
- name,
229
- startTime,
230
- endTime: Date.now(),
231
- error: { message: err.message, stack: err.stack, name: err.name },
232
- })
673
+ for (const name of ['describe', 'context', 'xdescribe', 'xcontext']) {
674
+ const declareSuite = globalThis[name]
675
+ if (typeof declareSuite !== 'function') continue
676
+ if (name === 'xdescribe' || name === 'xcontext') {
677
+ globalThis[name] = wrapSkippedSuiteDeclaration(declareSuite)
678
+ } else if (typeof declareSuite.skip === 'function') {
679
+ declareSuite.skip = wrapSkippedSuiteDeclaration(declareSuite.skip)
233
680
  }
234
- commandStartTimes.clear()
681
+ }
235
682
 
236
- // If command:end fired for all commands (none in-flight) but the last command
237
- // has no error, it means command:end fired before the error was attached to it.
238
- if (!hadInFlightCommands && currentTestCommands.length > 0) {
239
- // We have to support very old cypress versions in v5
240
- // eslint-disable-next-line unicorn/prefer-at
241
- const lastCommand = currentTestCommands[currentTestCommands.length - 1]
242
- if (!lastCommand.error) {
243
- lastCommand.error = { message: err.message, stack: err.stack, name: err.name }
244
- }
683
+ // If the test is using multi domain with cy.origin, trying to access
684
+ // window properties will result in a cross origin error.
685
+ function safeGetRum (window) {
686
+ try {
687
+ return window.DD_RUM
688
+ } catch {
689
+ return null
245
690
  }
691
+ }
246
692
 
247
- if (!isTestManagementEnabled) {
248
- throw err
249
- }
693
+ /** @param {string} message */
694
+ function warnMissingBeforeEachTaskResult (message) {
695
+ // eslint-disable-next-line no-console
696
+ console.warn(message)
697
+ }
250
698
 
251
- const testName = runnable.fullTitle()
252
- const { isAttemptToFix, isQuarantined, isDisabled } = getTestProperties(testName)
699
+ function disableFrameworkRetries (test) {
700
+ test._retries = 0
701
+ }
253
702
 
254
- // Suppress failures for quarantined or disabled tests so they don't affect the exit code.
255
- // Attempt-to-fix ignores quarantine/disabled suppression and keeps the normal framework result.
256
- if (!isAttemptToFix && (isQuarantined || isDisabled)) {
257
- suppressedTestFailures.set(testName, { error: err, isQuarantined, isDisabled })
258
- return
703
+ /** @param {object} test */
704
+ function getNativeRetryOverrides (test) {
705
+ for (let current = test; current; current = current.parent) {
706
+ const config = current._testConfig
707
+ const overrides = config && (config.unverifiedTestConfig || config)
708
+ if (overrides && overrides.retries !== undefined) return overrides
259
709
  }
710
+ }
260
711
 
261
- throw err
262
- })
712
+ /** @param {object} test */
713
+ function getNativeRetryBudget (test) {
714
+ const computed = nativeAccessorBudgets.get(test)
715
+ if (computed && computed.accessor) {
716
+ if (computed.metadata) {
717
+ reconcileBrowserRetryMetadata(computed.metadata)
718
+ const retries = nativeRetryCount(computed.metadata.native)
719
+ return Number.isSafeInteger(retries) ? retries : 0
720
+ }
721
+ return Number.isSafeInteger(computed.retries) ? computed.retries : 0
722
+ }
723
+ if (!computed && typeof Cypress.getTestRetries === 'function' && hasNativeRetryAccessor()) {
724
+ // Future runnables are provisional until Cypress computes their actual accessor budget.
725
+ return Number.isSafeInteger(test._retries) ? test._retries : frameworkRetries
726
+ }
727
+ const accessor = getBrowserRetryAccessor()
728
+ const accessorValue = accessor && cypressConfig.call(Cypress, 'retries')
729
+ if (accessor) recordBrowserRetryAccessorRead(accessorValue)
730
+ const overrides = getNativeRetryOverrides(test)
731
+ let metadata = browserRetrySelection
732
+ if (!metadata) {
733
+ const current = unwrapBrowserRetries(accessor ? accessorValue : cypressConfig.call(Cypress, 'retries'))
734
+ const observed = current && typeof current === 'object' && browserRetryObjects.get(current)
735
+ if (observed && observed.reconcileOnRead) metadata = observed
736
+ }
737
+ if (metadata) reconcileBrowserRetryMetadata(metadata)
738
+ // A getter-only root rejects Cypress's declaration writes, so its current value remains authoritative.
739
+ const retries = accessor && !accessor.set
740
+ ? nativeRetryCount(browserRetries)
741
+ : overrides
742
+ ? nativeRetryCount(overrides.retries)
743
+ : metadata
744
+ ? nativeRetryCount(metadata.native)
745
+ : hasBrowserRetries ? nativeRetryCount(browserRetries) : frameworkRetries
746
+ return Number.isSafeInteger(retries) ? retries : 0
747
+ }
263
748
 
264
749
  function getRetriedTests (test, numRetries, tags) {
265
750
  const retriedTests = []
@@ -281,290 +766,583 @@ function getRetriedTests (test, numRetries, tags) {
281
766
  return retriedTests
282
767
  }
283
768
 
284
- function disableFrameworkRetries (test) {
285
- test._retries = 0
286
- }
769
+ // Observation must precede user support, while manual lifecycle hooks retain the
770
+ // registration point chosen by the public support entry.
771
+ let lifecycleHooksInstalled = false
772
+ function installLifecycleHooks () {
773
+ if (lifecycleHooksInstalled) return
774
+ lifecycleHooksInstalled = true
775
+ let rumFlushWaitMillis = 500
776
+ let rumTestExecutionIdCookieName
777
+
778
+ let isEarlyFlakeDetectionEnabled = false
779
+ let isKnownTestsEnabled = false
780
+ let knownTestsForSuite = []
781
+ let earlyFlakeDetectionSchedulingRetryCount = 0
782
+ let isTestManagementEnabled = false
783
+ let testManagementAttemptToFixRetries = 0
784
+ let testManagementTests = {}
785
+ let isImpactedTestsEnabled = false
786
+ let isModifiedTest = false
787
+ let isTestIsolationEnabled = false
788
+ let isDynamicAtrEnabled = false
789
+ let hasWarnedMissingBeforeEachTaskResult = false
790
+ let hasWarnedMissingBeforeEachRetryResult = false
791
+ // Array of test names that have been retried and the reason
792
+ const retryReasonsByTestName = new Map()
793
+ // Dynamic ATR computes the selected budget after the first attempt. Keep that result
794
+ // in browser state and apply it when Cypress starts the retry runnable.
795
+ const dynamicAtrRetryCountByTest = new Map()
796
+ // Track test errors suppressed by test management so we can still report them to Datadog.
797
+ const suppressedTestFailures = new Map()
798
+
799
+ // Track the most recently loaded window in the AUT. Updated via the 'window:load'
800
+ // event so we always get the real app window (after cy.visit()), not the
801
+ // about:blank window that exists when beforeEach runs. If the test later navigates
802
+ // to a cross-origin URL, safeGetRum() handles the access error.
803
+ let originalWindow
804
+
805
+ let currentTestCommands = []
806
+ const commandStartTimes = new Map()
807
+ const INTERNAL_CYPRESS_COMMANDS = new Set(['wrap', 'then', 'noop'])
808
+
809
+ Cypress.on('command:start', (command) => {
810
+ commandStartTimes.set(command.get('id'), { startTime: Date.now(), name: command.get('name') })
811
+ })
287
812
 
288
- function shouldDisableFrameworkRetries (test) {
289
- return test && (
290
- test._ddIsAttemptToFix ||
291
- (isTestIsolationEnabled &&
292
- isEarlyFlakeDetectionEnabled &&
293
- (test._ddIsNew || test._ddIsModified))
294
- )
295
- }
813
+ Cypress.on('command:end', (command) => {
814
+ const id = command.get('id')
815
+ const entry = commandStartTimes.get(id)
816
+ commandStartTimes.delete(id)
817
+
818
+ const name = command.get('name')
819
+ const args = command.get('args')
820
+ if (name === 'task' && args && typeof args[0] === 'string' && args[0].startsWith('dd:')) {
821
+ return
822
+ }
823
+ if (INTERNAL_CYPRESS_COMMANDS.has(name) || entry == null) {
824
+ return
825
+ }
826
+ const err = command.get('err')
827
+ currentTestCommands.push({
828
+ name,
829
+ startTime: entry.startTime,
830
+ endTime: Date.now(),
831
+ // Serialize the error to a plain object so it survives cy.task JSON transport.
832
+ error: err ? { message: err.message, stack: err.stack, name: err.name } : null,
833
+ })
834
+ })
296
835
 
297
- const oldRunTests = Cypress.mocha.getRunner().runTests
298
- Cypress.mocha.getRunner().runTests = function (suite, fn) {
299
- if (!isKnownTestsEnabled && !isTestManagementEnabled && !isImpactedTestsEnabled) {
300
- return oldRunTests.apply(this, arguments)
836
+ function isNewTest (test) {
837
+ // If for whatever reason the worker does not receive valid known tests, we don't consider it as new
838
+ if (!Array.isArray(knownTestsForSuite)) {
839
+ return false
840
+ }
841
+ return !knownTestsForSuite.includes(test.fullTitle())
301
842
  }
302
- // We copy the tests array and add retries to it, then assign it back to suite.tests
303
- // to avoid modifying the array while iterating over it
304
- const testsWithRetries = []
305
843
 
306
- for (let testIndex = 0; testIndex < suite.tests.length; testIndex++) {
307
- const test = suite.tests[testIndex]
308
- const testName = test.fullTitle()
309
- const { isAttemptToFix } = getTestProperties(testName)
310
- const isSkipped = test.isPending()
844
+ function getTestProperties (testName) {
845
+ // TODO: Use optional chaining when we drop support for older Cypress versions, which will happen when dd-trace@5 is
846
+ // EoL. Until then, this files needs to support Node.js 16.
847
+ const properties = testManagementTests[testName] && testManagementTests[testName].properties || {}
311
848
 
312
- const isAtemptToFix = isTestManagementEnabled && isAttemptToFix && !isSkipped
313
- const isModified = isImpactedTestsEnabled && isModifiedTest
314
- const isNew = isKnownTestsEnabled && !isSkipped && isNewTest(test)
849
+ const { attempt_to_fix: isAttemptToFix, disabled: isDisabled, quarantined: isQuarantined } = properties
315
850
 
316
- // We want is_modified and is_new regardless of the retry reason
317
- if (isModified) {
318
- test._ddIsModified = true
319
- }
320
- if (isNew) {
321
- test._ddIsNew = true
851
+ return { isAttemptToFix, isDisabled, isQuarantined }
852
+ }
853
+
854
+ /**
855
+ * @param {object} test
856
+ * @returns {Cypress.Chainable<{ traceId?: string, shouldSkip?: boolean, shouldDiscard?: boolean }>}
857
+ */
858
+ function runBeforeEachTask (test) {
859
+ return cy.task('dd:beforeEach', test).then((taskResult) => {
860
+ if (taskResult !== undefined && taskResult !== null) {
861
+ return taskResult
862
+ }
863
+
864
+ if (!hasWarnedMissingBeforeEachTaskResult) {
865
+ hasWarnedMissingBeforeEachTaskResult = true
866
+ warnMissingBeforeEachTaskResult('Datadog Cypress dd:beforeEach task returned no result. Retrying once.')
867
+ }
868
+
869
+ return cy.task('dd:beforeEach', test).then((retryTaskResult) => {
870
+ if (retryTaskResult !== undefined && retryTaskResult !== null) {
871
+ return retryTaskResult
872
+ }
873
+
874
+ if (!hasWarnedMissingBeforeEachRetryResult) {
875
+ hasWarnedMissingBeforeEachRetryResult = true
876
+ warnMissingBeforeEachTaskResult(
877
+ 'Datadog Cypress dd:beforeEach task returned no result after retry. Continuing with an empty task result.'
878
+ )
879
+ }
880
+
881
+ return {}
882
+ })
883
+ })
884
+ }
885
+
886
+ /**
887
+ * @param {string} message
888
+ * @param {unknown} error
889
+ * @returns {false}
890
+ */
891
+ function logRumCorrelationCookieError (message, error) {
892
+ try {
893
+ Cypress.log({
894
+ name: 'dd-trace',
895
+ message,
896
+ consoleProps: () => ({ Error: error }),
897
+ })
898
+ } catch (loggingError) {
899
+ // eslint-disable-next-line no-console
900
+ console.error(message, error, loggingError)
322
901
  }
902
+ return false
903
+ }
323
904
 
324
- // Add the original test first
325
- testsWithRetries.push(test)
905
+ /**
906
+ * @param {unknown} error
907
+ * @returns {false}
908
+ */
909
+ function handleRumCorrelationCookieError (error) {
910
+ return logRumCorrelationCookieError('Could not set the RUM correlation cookie', error)
911
+ }
326
912
 
327
- if (!isTestIsolationEnabled) {
328
- continue
913
+ /**
914
+ * @param {unknown} error
915
+ * @returns {false}
916
+ */
917
+ function handleRumCorrelationCookieCleanupError (error) {
918
+ return logRumCorrelationCookieError('Could not clear the previous RUM correlation cookie', error)
919
+ }
920
+
921
+ /**
922
+ * @param {string} traceId
923
+ * @returns {Promise<boolean>}
924
+ */
925
+ function setRumCorrelationCookie (traceId) {
926
+ if (typeof cy.now !== 'function') {
927
+ return Cypress.Promise.resolve(handleRumCorrelationCookieError(new Error('Cypress cy.now is not available')))
329
928
  }
330
929
 
331
- // Then add retries right after it
332
- let retriedTests = []
333
- let retryMessage = ''
334
- if (isAtemptToFix) {
335
- test._ddIsAttemptToFix = true
336
- disableFrameworkRetries(test)
337
- retryMessage = 'because it is an attempt to fix'
338
- retriedTests = getRetriedTests(test, testManagementAttemptToFixRetries, ['_ddIsAttemptToFix'])
339
- } else if (isModified && isEarlyFlakeDetectionEnabled) {
340
- disableFrameworkRetries(test)
341
- retryMessage = 'to detect flakes because it is modified'
342
- retriedTests = getRetriedTests(test, earlyFlakeDetectionSchedulingRetryCount, [
343
- '_ddIsModified',
344
- '_ddIsEfdRetry',
345
- isKnownTestsEnabled && isNewTest(test) && '_ddIsNew',
346
- ])
347
- } else if (isNew && isEarlyFlakeDetectionEnabled) {
348
- disableFrameworkRetries(test)
349
- retryMessage = 'to detect flakes because it is new'
350
- retriedTests = getRetriedTests(test, earlyFlakeDetectionSchedulingRetryCount, ['_ddIsNew', '_ddIsEfdRetry'])
930
+ let clearCookiePromise = Cypress.Promise.resolve()
931
+ if (!isTestIsolationEnabled) {
932
+ clearCookiePromise = Cypress.Promise.try(() => {
933
+ return cy.now('clearCookie', rumTestExecutionIdCookieName, { log: false })
934
+ }).then(undefined, handleRumCorrelationCookieCleanupError)
351
935
  }
352
936
 
353
- testsWithRetries.push(...retriedTests)
937
+ return clearCookiePromise.then(() => {
938
+ return Cypress.Promise.try(() => {
939
+ return cy.now('setCookie', rumTestExecutionIdCookieName, traceId, { log: false })
940
+ })
941
+ }).then(() => true, handleRumCorrelationCookieError)
942
+ }
354
943
 
355
- if (retryMessage) {
356
- retryReasonsByTestName.set(testName, retryMessage)
944
+ /**
945
+ * @param {boolean} isCookieSet
946
+ */
947
+ function restartRumSession (isCookieSet) {
948
+ if (!isCookieSet || isTestIsolationEnabled || !originalWindow) {
949
+ return
950
+ }
951
+
952
+ const rum = safeGetRum(originalWindow)
953
+ if (rum) {
954
+ try {
955
+ const evt = new originalWindow.MouseEvent('click', { bubbles: true, cancelable: true })
956
+ // The browser-sdk addEventListener wrapper filters out untrusted synthetic events
957
+ // unless __ddIsTrusted is set. Set it so the click triggers expandOrRenewSession().
958
+ // See: https://github.com/DataDog/browser-sdk/blob/v6.27.1/packages/core/src/browser/addEventListener.ts#L119
959
+ Object.defineProperty(evt, '__ddIsTrusted', { value: true })
960
+ originalWindow.dispatchEvent(evt)
961
+ } catch {}
962
+ if (rum.startView) {
963
+ rum.startView()
964
+ }
357
965
  }
358
966
  }
359
967
 
360
- suite.tests = testsWithRetries
968
+ // Catch test failures for quarantined tests and suppress them
969
+ // By not re-throwing the error, Cypress marks the test as passed
970
+ // This allows quarantined tests to run but not affect the exit code
971
+ Cypress.on('fail', (err, runnable) => {
972
+ // For commands that time out, command:end may never fire.
973
+ // Finalize any in-flight commands so their step spans carry the error.
974
+ const hadInFlightCommands = commandStartTimes.size > 0
975
+ for (const [, { startTime, name }] of commandStartTimes) {
976
+ if (INTERNAL_CYPRESS_COMMANDS.has(name)) continue
977
+ currentTestCommands.push({
978
+ name,
979
+ startTime,
980
+ endTime: Date.now(),
981
+ error: { message: err.message, stack: err.stack, name: err.name },
982
+ })
983
+ }
984
+ commandStartTimes.clear()
361
985
 
362
- return oldRunTests.apply(this, [suite, fn])
363
- }
986
+ // If command:end fired for all commands (none in-flight) but the last command
987
+ // has no error, it means command:end fired before the error was attached to it.
988
+ if (!hadInFlightCommands && currentTestCommands.length > 0) {
989
+ // We have to support very old cypress versions in v5
990
+ // eslint-disable-next-line unicorn/prefer-at
991
+ const lastCommand = currentTestCommands[currentTestCommands.length - 1]
992
+ if (!lastCommand.error) {
993
+ lastCommand.error = { message: err.message, stack: err.stack, name: err.name }
994
+ }
995
+ }
364
996
 
365
- /**
366
- * @param {{ id: string }} test
367
- */
368
- function getDynamicAtrTestKey (test) {
369
- // Cypress preserves the runnable ID when cloning a retry, including across browser reloads.
370
- return `${Cypress.mocha.getRootSuite().file}\0${test.id}`
371
- }
997
+ if (!isTestManagementEnabled) {
998
+ throw err
999
+ }
372
1000
 
373
- /**
374
- * @param {{ id: string, _retries: number }} test
375
- */
376
- function configureTestRetries (test) {
377
- if (shouldDisableFrameworkRetries(test)) {
378
- disableFrameworkRetries(test)
379
- return
1001
+ const testName = runnable.fullTitle()
1002
+ const annotations = getTestAnnotations(runnable)
1003
+ const properties = getTestProperties(testName)
1004
+ const isAttemptToFix = properties.isAttemptToFix && !annotations.noAutoRetry
1005
+ const isQuarantined = properties.isQuarantined && !annotations.mustFail
1006
+ const isDisabled = properties.isDisabled && !annotations.mustFail
1007
+
1008
+ // Suppress failures for quarantined or disabled tests so they don't affect the exit code.
1009
+ // Attempt-to-fix ignores quarantine/disabled suppression and keeps the normal framework result.
1010
+ if (!isAttemptToFix && (isQuarantined || isDisabled)) {
1011
+ suppressedTestFailures.set(testName, { error: err, isQuarantined, isDisabled })
1012
+ return
1013
+ }
1014
+
1015
+ throw err
1016
+ })
1017
+
1018
+ function shouldDisableFrameworkRetries (test) {
1019
+ return test && (
1020
+ test._ddIsAttemptToFix ||
1021
+ (isTestIsolationEnabled &&
1022
+ isEarlyFlakeDetectionEnabled &&
1023
+ (test._ddIsNew || test._ddIsModified))
1024
+ )
380
1025
  }
381
1026
 
382
- if (!isTextTerminal) return
1027
+ const oldRunTests = Cypress.mocha.getRunner().runTests
1028
+ Cypress.mocha.getRunner().runTests = function (suite, fn) {
1029
+ if (!isKnownTestsEnabled && !isTestManagementEnabled && !isImpactedTestsEnabled) {
1030
+ return oldRunTests.apply(this, arguments)
1031
+ }
1032
+ // We copy the tests array and add retries to it, then assign it back to suite.tests
1033
+ // to avoid modifying the array while iterating over it
1034
+ const testsWithRetries = []
1035
+
1036
+ for (let testIndex = 0; testIndex < suite.tests.length; testIndex++) {
1037
+ const test = suite.tests[testIndex]
1038
+ const testName = test.fullTitle()
1039
+ const { isAttemptToFix } = getTestProperties(testName)
1040
+ const isSkipped = test.isPending()
1041
+
1042
+ const annotations = getTestAnnotations(test)
1043
+ const isAtemptToFix = isTestManagementEnabled && isAttemptToFix && !isSkipped && !annotations.noAutoRetry
1044
+ const isModified = isImpactedTestsEnabled && isModifiedTest
1045
+ const isNew = isKnownTestsEnabled && !isSkipped && isNewTest(test)
1046
+
1047
+ // We want is_modified and is_new regardless of the retry reason
1048
+ if (isModified) {
1049
+ test._ddIsModified = true
1050
+ }
1051
+ if (isNew) {
1052
+ test._ddIsNew = true
1053
+ }
1054
+
1055
+ // Add the original test first
1056
+ testsWithRetries.push(test)
1057
+
1058
+ if (!isTestIsolationEnabled || annotations.noAutoRetry) {
1059
+ continue
1060
+ }
1061
+
1062
+ // Then add retries right after it
1063
+ let retriedTests = []
1064
+ let retryMessage = ''
1065
+ if (isAtemptToFix) {
1066
+ test._ddIsAttemptToFix = true
1067
+ disableFrameworkRetries(test)
1068
+ retryMessage = 'because it is an attempt to fix'
1069
+ retriedTests = getRetriedTests(test, testManagementAttemptToFixRetries, ['_ddIsAttemptToFix'])
1070
+ } else if (isModified && isEarlyFlakeDetectionEnabled) {
1071
+ disableFrameworkRetries(test)
1072
+ retryMessage = 'to detect flakes because it is modified'
1073
+ retriedTests = getRetriedTests(test, earlyFlakeDetectionSchedulingRetryCount, [
1074
+ '_ddIsModified',
1075
+ '_ddIsEfdRetry',
1076
+ isKnownTestsEnabled && isNewTest(test) && '_ddIsNew',
1077
+ ])
1078
+ } else if (isNew && isEarlyFlakeDetectionEnabled) {
1079
+ disableFrameworkRetries(test)
1080
+ retryMessage = 'to detect flakes because it is new'
1081
+ retriedTests = getRetriedTests(test, earlyFlakeDetectionSchedulingRetryCount, ['_ddIsNew', '_ddIsEfdRetry'])
1082
+ }
1083
+
1084
+ testsWithRetries.push(...retriedTests)
383
1085
 
384
- const dynamicAtrRetryCount = dynamicAtrRetryCountByTest.get(getDynamicAtrTestKey(test))
385
- if (Number.isSafeInteger(dynamicAtrRetryCount)) {
386
- test._retries = dynamicAtrRetryCount
387
- } else if (isDynamicAtrEnabled) {
388
- // Cypress forbids calling retries(count) on the original runnable.
389
- // Ensure local retries: 0 overrides still reach the duration-based budget selection.
390
- test._retries = Math.max(1, test._retries)
1086
+ if (retryMessage) {
1087
+ retryReasonsByTestName.set(testName, retryMessage)
1088
+ }
1089
+ }
1090
+
1091
+ suite.tests = testsWithRetries
1092
+
1093
+ return oldRunTests.apply(this, [suite, fn])
391
1094
  }
392
- }
393
1095
 
394
- Cypress.on('test:before:run', (attributes, test) => {
395
- configureTestRetries(test)
396
- })
1096
+ /**
1097
+ * @param {{ id: string }} test
1098
+ */
1099
+ function getDynamicAtrTestKey (test) {
1100
+ // Cypress preserves the runnable ID when cloning a retry, including across browser reloads.
1101
+ return `${Cypress.mocha.getRootSuite().file}\0${test.id}`
1102
+ }
397
1103
 
398
- Cypress.on('test:before:run:async', (attributes, test) => {
399
- configureTestRetries(test)
400
- })
1104
+ /**
1105
+ * @param {{ id: string, _retries: number }} test
1106
+ */
1107
+ function configureTestRetries (test) {
1108
+ if (hasSuiteConfig && getTestAnnotations(test).noAutoRetry) {
1109
+ // Restore developer configuration after the plugin's global ATR configuration.
1110
+ // Read the nearest test/suite override before or after Cypress resolves it.
1111
+ test._retries = getNativeRetryBudget(test)
1112
+ // Cypress resolves local retries after this event; the support hook reapplies this value.
1113
+ return
1114
+ }
1115
+ if (shouldDisableFrameworkRetries(test)) {
1116
+ disableFrameworkRetries(test)
1117
+ return
1118
+ }
401
1119
 
402
- beforeEach(function () {
403
- const currentTest = Cypress.mocha.getRunner().suite.ctx.currentTest
404
- // The first test:before:run event can precede the suite configuration task.
405
- configureTestRetries(currentTest)
406
- const testName = currentTest.fullTitle()
1120
+ if (!isTextTerminal) return
407
1121
 
408
- const retryMessage = retryReasonsByTestName.get(testName)
409
- if (retryMessage) {
410
- cy.task(
411
- 'dd:log',
412
- `Retrying "${testName}" ${retryMessage}`
413
- )
414
- retryReasonsByTestName.delete(testName)
1122
+ const dynamicAtrRetryCount = dynamicAtrRetryCountByTest.get(getDynamicAtrTestKey(test))
1123
+ if (Number.isSafeInteger(dynamicAtrRetryCount)) {
1124
+ test._retries = dynamicAtrRetryCount
1125
+ } else if (isDynamicAtrEnabled) {
1126
+ // Cypress forbids calling retries(count) on the original runnable.
1127
+ // Ensure local retries: 0 overrides still reach the duration-based budget selection.
1128
+ test._retries = Math.max(1, test._retries)
1129
+ }
415
1130
  }
416
1131
 
417
- currentTestCommands = []
418
- commandStartTimes.clear()
1132
+ Cypress.on('test:before:run', (attributes, test) => {
1133
+ configureTestRetries(test)
1134
+ })
419
1135
 
420
- cy.on('window:load', (win) => {
421
- originalWindow = win
1136
+ Cypress.on('test:before:run:async', (attributes, test) => {
1137
+ configureTestRetries(test)
422
1138
  })
423
1139
 
424
- runBeforeEachTask({
425
- testId: currentTest.id,
426
- testName,
427
- testSuite: Cypress.mocha.getRootSuite().file,
428
- isEfdRetry: Cypress.mocha.getRunner().suite.ctx.currentTest._ddIsEfdRetry,
429
- efdRetryIndex: Cypress.mocha.getRunner().suite.ctx.currentTest._ddEfdRetryIndex,
430
- }).then(({ traceId, shouldSkip, shouldDiscard }) => {
431
- if (shouldDiscard) {
432
- this.currentTest._ddShouldDiscard = true
433
- }
434
- let rumCookiePromise
435
- if (traceId) {
436
- rumCookiePromise = setRumCorrelationCookie(traceId)
437
- }
438
- if (shouldSkip) {
439
- // Test Optimization requested this runtime skip through the Cypress support hook.
440
- this.skip()
441
- }
442
- if (rumCookiePromise) {
443
- return rumCookiePromise.then(restartRumSession)
444
- }
445
- }).then(() => {
446
- // Clear any commands accumulated during DD-owned setup (e.g. setCookie, RUM restart)
447
- // so they are not reported as user test steps.
1140
+ beforeEach(function () {
1141
+ const currentTest = Cypress.mocha.getRunner().suite.ctx.currentTest
1142
+ // The first test:before:run event can precede the suite configuration task.
1143
+ configureTestRetries(currentTest)
1144
+ const testName = currentTest.fullTitle()
1145
+
1146
+ const retryMessage = retryReasonsByTestName.get(testName)
1147
+ if (retryMessage) {
1148
+ cy.task(
1149
+ 'dd:log',
1150
+ `Retrying "${testName}" ${retryMessage}`
1151
+ )
1152
+ retryReasonsByTestName.delete(testName)
1153
+ }
1154
+
448
1155
  currentTestCommands = []
449
1156
  commandStartTimes.clear()
1157
+
1158
+ cy.on('window:load', (win) => {
1159
+ originalWindow = win
1160
+ })
1161
+
1162
+ runBeforeEachTask({
1163
+ testId: currentTest.id,
1164
+ testName,
1165
+ annotations: getTestAnnotations(currentTest),
1166
+ testSuite: Cypress.mocha.getRootSuite().file,
1167
+ isEfdRetry: Cypress.mocha.getRunner().suite.ctx.currentTest._ddIsEfdRetry,
1168
+ efdRetryIndex: Cypress.mocha.getRunner().suite.ctx.currentTest._ddEfdRetryIndex,
1169
+ }).then(({ traceId, shouldSkip, shouldDiscard }) => {
1170
+ if (shouldDiscard) {
1171
+ this.currentTest._ddShouldDiscard = true
1172
+ }
1173
+ let rumCookiePromise
1174
+ if (traceId) {
1175
+ rumCookiePromise = setRumCorrelationCookie(traceId)
1176
+ }
1177
+ if (shouldSkip) {
1178
+ // Test Optimization requested this runtime skip through the Cypress support hook.
1179
+ this.skip()
1180
+ }
1181
+ if (rumCookiePromise) {
1182
+ return rumCookiePromise.then(restartRumSession)
1183
+ }
1184
+ }).then(() => {
1185
+ // Clear any commands accumulated during DD-owned setup (e.g. setCookie, RUM restart)
1186
+ // so they are not reported as user test steps.
1187
+ currentTestCommands = []
1188
+ commandStartTimes.clear()
1189
+ })
450
1190
  })
451
- })
452
-
453
- before(function () {
454
- cy.task('dd:testSuiteStart', {
455
- testSuite: Cypress.mocha.getRootSuite().file,
456
- testSuiteAbsolutePath: Cypress.spec && Cypress.spec.absolute,
457
- isTextTerminal: Cypress.config('isTextTerminal'),
458
- }).then((suiteConfig) => {
459
- if (suiteConfig) {
460
- isEarlyFlakeDetectionEnabled = suiteConfig.isEarlyFlakeDetectionEnabled
461
- isKnownTestsEnabled = suiteConfig.isKnownTestsEnabled
462
- knownTestsForSuite = suiteConfig.knownTestsForSuite
463
- earlyFlakeDetectionSchedulingRetryCount = suiteConfig.earlyFlakeDetectionSchedulingRetryCount
464
- isTestManagementEnabled = suiteConfig.isTestManagementEnabled
465
- testManagementAttemptToFixRetries = suiteConfig.testManagementAttemptToFixRetries
466
- testManagementTests = suiteConfig.testManagementTests
467
- isImpactedTestsEnabled = suiteConfig.isImpactedTestsEnabled
468
- isModifiedTest = suiteConfig.isModifiedTest
469
- isTestIsolationEnabled = suiteConfig.isTestIsolationEnabled
470
- isDynamicAtrEnabled = suiteConfig.isDynamicAtrEnabled
471
- isTextTerminal = suiteConfig.isTextTerminal
472
- if (isDynamicAtrEnabled && isTextTerminal) {
473
- // The first test event can precede this task, and an earlier user hook can skip our beforeEach.
474
- Cypress.mocha.getRootSuite().eachTest(configureTestRetries)
1191
+
1192
+ before(function () {
1193
+ cy.task('dd:testSuiteStart', {
1194
+ testAnnotations: getTestDeclarations(),
1195
+ testSuite: Cypress.mocha.getRootSuite().file,
1196
+ testSuiteAbsolutePath: Cypress.spec && Cypress.spec.absolute,
1197
+ isTextTerminal: Cypress.config('isTextTerminal'),
1198
+ }).then((suiteConfig) => {
1199
+ if (suiteConfig) {
1200
+ hasSuiteConfig = true
1201
+ frameworkRetries = suiteConfig.frameworkRetries
1202
+ originalRetries = suiteConfig.originalRetries
1203
+ configuredRetries = suiteConfig.configuredRetries
1204
+ const rawRetries = peekBrowserRetries()
1205
+ const metadata = rawRetries && typeof rawRetries === 'object' && browserRetryObjects.get(rawRetries)
1206
+ if (metadata) initializeBrowserRetryMetadata(metadata)
1207
+ if (!hasBrowserRetries &&
1208
+ !browserRetriesEqual(initialBrowserRetries, suiteConfig.configuredRetries)) {
1209
+ // Manual support can load after a browser configuration override already happened.
1210
+ browserRetries = overlayBrowserRetries(
1211
+ originalRetries, suiteConfig.configuredRetries, initialBrowserRetries
1212
+ )
1213
+ hasBrowserRetries = true
1214
+ }
1215
+ isEarlyFlakeDetectionEnabled = suiteConfig.isEarlyFlakeDetectionEnabled
1216
+ isKnownTestsEnabled = suiteConfig.isKnownTestsEnabled
1217
+ knownTestsForSuite = suiteConfig.knownTestsForSuite
1218
+ earlyFlakeDetectionSchedulingRetryCount = suiteConfig.earlyFlakeDetectionSchedulingRetryCount
1219
+ isTestManagementEnabled = suiteConfig.isTestManagementEnabled
1220
+ testManagementAttemptToFixRetries = suiteConfig.testManagementAttemptToFixRetries
1221
+ testManagementTests = suiteConfig.testManagementTests
1222
+ isImpactedTestsEnabled = suiteConfig.isImpactedTestsEnabled
1223
+ isModifiedTest = suiteConfig.isModifiedTest
1224
+ isTestIsolationEnabled = suiteConfig.isTestIsolationEnabled
1225
+ isDynamicAtrEnabled = suiteConfig.isDynamicAtrEnabled
1226
+ isTextTerminal = suiteConfig.isTextTerminal
1227
+ if (isTextTerminal) {
1228
+ // The first test event can precede this task, and an earlier user hook can skip our beforeEach.
1229
+ Cypress.mocha.getRootSuite().eachTest(configureTestRetries)
1230
+ }
1231
+ rumTestExecutionIdCookieName = suiteConfig.rumTestExecutionIdCookieName
1232
+ if (Number.isFinite(suiteConfig.rumFlushWaitMillis)) {
1233
+ rumFlushWaitMillis = suiteConfig.rumFlushWaitMillis
1234
+ }
475
1235
  }
476
- rumTestExecutionIdCookieName = suiteConfig.rumTestExecutionIdCookieName
477
- if (Number.isFinite(suiteConfig.rumFlushWaitMillis)) {
478
- rumFlushWaitMillis = suiteConfig.rumFlushWaitMillis
1236
+ })
1237
+ })
1238
+
1239
+ after(() => {
1240
+ // Root teardown still runs when a user root setup hook fails before Datadog setup.
1241
+ // Publish all declarations so Node-side recovery can annotate the skipped tests.
1242
+ if (!hasSuiteConfig) {
1243
+ cy.task('dd:testDeclarations', {
1244
+ testSuite: Cypress.mocha.getRootSuite().file,
1245
+ testAnnotations: getTestDeclarations(),
1246
+ })
1247
+ }
1248
+ dynamicAtrRetryCountByTest.clear()
1249
+ try {
1250
+ if (safeGetRum(originalWindow)) {
1251
+ originalWindow.dispatchEvent(new Event('beforeunload'))
479
1252
  }
1253
+ } catch {
1254
+ // ignore error. It's usually a multi origin issue.
480
1255
  }
481
1256
  })
482
- })
483
1257
 
484
- after(() => {
485
- dynamicAtrRetryCountByTest.clear()
486
- try {
487
- if (safeGetRum(originalWindow)) {
488
- originalWindow.dispatchEvent(new Event('beforeunload'))
1258
+ afterEach(function () {
1259
+ const currentTest = Cypress.mocha.getRunner().suite.ctx.currentTest
1260
+ if (currentTest._ddShouldDiscard) {
1261
+ return
489
1262
  }
490
- } catch {
491
- // ignore error. It's usually a multi origin issue.
492
- }
493
- })
494
-
495
- afterEach(function () {
496
- const currentTest = Cypress.mocha.getRunner().suite.ctx.currentTest
497
- if (currentTest._ddShouldDiscard) {
498
- return
499
- }
500
- const testName = currentTest.fullTitle()
501
-
502
- // Check if this was a test management test that we suppressed the failure for.
503
- const suppressedTestFailure = suppressedTestFailures.get(testName)
504
- const suppressedError = suppressedTestFailure && suppressedTestFailure.error
505
- const isTestManagementTestThatFailed = !!suppressedError
506
-
507
- // For suppressed test management tests, convert Error to a serializable format for cy.task.
508
- const errorToReport = isTestManagementTestThatFailed
509
- ? { message: suppressedError.message, stack: suppressedError.stack }
510
- : currentTest.err
511
-
512
- const testInfo = {
513
- testId: currentTest.id,
514
- testName,
515
- testItTitle: currentTest.title,
516
- testSuite: Cypress.mocha.getRootSuite().file,
517
- testSuiteAbsolutePath: Cypress.spec && Cypress.spec.absolute,
518
- // Report the actual failed state to Datadog, not the pass state Cypress sees after suppression.
519
- state: isTestManagementTestThatFailed ? 'failed' : currentTest.state,
520
- // Include the actual error that was suppressed.
521
- error: errorToReport,
522
- isNew: currentTest._ddIsNew,
523
- isEfdRetry: currentTest._ddIsEfdRetry,
524
- isAttemptToFix: currentTest._ddIsAttemptToFix,
525
- isModified: currentTest._ddIsModified,
526
- hasNativeRetries: !!(currentTest._testConfig && currentTest._testConfig.unverifiedTestConfig &&
527
- currentTest._testConfig.unverifiedTestConfig.retries !== undefined),
528
- duration: currentTest.duration,
529
- // Mark suppressed tests so the plugin can tag them with the correct test management reason.
530
- isQuarantined: isTestManagementTestThatFailed && suppressedTestFailure.isQuarantined,
531
- isDisabled: isTestManagementTestThatFailed && suppressedTestFailure.isDisabled,
532
- }
533
- try {
534
- const invocationDetails = Cypress.mocha.getRunner().currentRunnable.invocationDetails
535
- testInfo.testSourceLine = invocationDetails.line
536
- testInfo.testSourceStack = invocationDetails.stack
537
- } catch {}
1263
+ const testName = currentTest.fullTitle()
1264
+
1265
+ // Check if this was a test management test that we suppressed the failure for.
1266
+ const suppressedTestFailure = suppressedTestFailures.get(testName)
1267
+ const suppressedError = suppressedTestFailure && suppressedTestFailure.error
1268
+ const isTestManagementTestThatFailed = !!suppressedError
1269
+
1270
+ // For suppressed test management tests, convert Error to a serializable format for cy.task.
1271
+ const errorToReport = isTestManagementTestThatFailed
1272
+ ? { message: suppressedError.message, stack: suppressedError.stack }
1273
+ : currentTest.err
1274
+
1275
+ const retries = peekBrowserRetries()
1276
+ const strategy = retries && typeof retries === 'object' && browserRetryDescriptor(retries, 'experimentalStrategy')
1277
+ const computed = nativeAccessorBudgets.get(currentTest)
1278
+ const hasNativeExperimentalRetries = strategy && !('value' in strategy)
1279
+ ? Boolean(computed && computed.experimental)
1280
+ : Boolean(strategy && strategy.value)
1281
+ const nativeRetryFloor = isDynamicAtrEnabled && hasNativeExperimentalRetries ? getNativeRetryBudget(currentTest) : 0
1282
+ const testInfo = {
1283
+ nativeRetryFloor,
1284
+ hasNativeExperimentalRetries,
1285
+ testId: currentTest.id,
1286
+ testName,
1287
+ testItTitle: currentTest.title,
1288
+ testSuite: Cypress.mocha.getRootSuite().file,
1289
+ testSuiteAbsolutePath: Cypress.spec && Cypress.spec.absolute,
1290
+ // Report the actual failed state to Datadog, not the pass state Cypress sees after suppression.
1291
+ state: isTestManagementTestThatFailed ? 'failed' : currentTest.state,
1292
+ // Include the actual error that was suppressed.
1293
+ error: errorToReport,
1294
+ isNew: currentTest._ddIsNew,
1295
+ isEfdRetry: currentTest._ddIsEfdRetry,
1296
+ isAttemptToFix: currentTest._ddIsAttemptToFix,
1297
+ annotations: getTestAnnotations(currentTest),
1298
+ isModified: currentTest._ddIsModified,
1299
+ hasNativeRetries: !!(currentTest._testConfig && currentTest._testConfig.unverifiedTestConfig &&
1300
+ currentTest._testConfig.unverifiedTestConfig.retries !== undefined),
1301
+ duration: currentTest.duration,
1302
+ // Mark suppressed tests so the plugin can tag them with the correct test management reason.
1303
+ isQuarantined: isTestManagementTestThatFailed && suppressedTestFailure.isQuarantined,
1304
+ isDisabled: isTestManagementTestThatFailed && suppressedTestFailure.isDisabled,
1305
+ }
1306
+ try {
1307
+ const invocationDetails = Cypress.mocha.getRunner().currentRunnable.invocationDetails
1308
+ testInfo.testSourceLine = invocationDetails.line
1309
+ testInfo.testSourceStack = invocationDetails.stack
1310
+ } catch {}
538
1311
 
539
- // Snapshot before any DD-owned Cypress commands so they are not reported as test steps.
540
- const commandsToReport = [...currentTestCommands]
1312
+ // Snapshot before any DD-owned Cypress commands so they are not reported as test steps.
1313
+ const commandsToReport = [...currentTestCommands]
541
1314
 
542
- const rum = safeGetRum(originalWindow)
543
- if (rum) {
544
- testInfo.isRUMActive = true
545
- if (rum.stopSession) {
546
- rum.stopSession()
547
- // eslint-disable-next-line cypress/no-unnecessary-waiting
548
- cy.wait(rumFlushWaitMillis)
1315
+ const rum = safeGetRum(originalWindow)
1316
+ if (rum) {
1317
+ testInfo.isRUMActive = true
1318
+ if (rum.stopSession) {
1319
+ rum.stopSession()
1320
+ // eslint-disable-next-line cypress/no-unnecessary-waiting
1321
+ cy.wait(rumFlushWaitMillis)
1322
+ }
1323
+ }
1324
+ let coverage
1325
+ try {
1326
+ coverage = originalWindow.__coverage__
1327
+ } catch {
1328
+ // ignore error and continue
549
1329
  }
550
- }
551
- let coverage
552
- try {
553
- coverage = originalWindow.__coverage__
554
- } catch {
555
- // ignore error and continue
556
- }
557
-
558
- // Clean up the suppressed error tracking.
559
- if (isTestManagementTestThatFailed) {
560
- suppressedTestFailures.delete(testName)
561
- }
562
1330
 
563
- cy.task('dd:afterEach', { test: testInfo, coverage, commands: commandsToReport }).then((taskResult) => {
564
- // Preserve the first-attempt result until Cypress starts the retry runnable.
565
- // Changing the completed test here is too late for Cypress's retry lifecycle.
566
- if (taskResult && Number.isSafeInteger(taskResult.dynamicAtrRetryCount)) {
567
- dynamicAtrRetryCountByTest.set(getDynamicAtrTestKey(currentTest), taskResult.dynamicAtrRetryCount)
1331
+ // Clean up the suppressed error tracking.
1332
+ if (isTestManagementTestThatFailed) {
1333
+ suppressedTestFailures.delete(testName)
568
1334
  }
1335
+
1336
+ cy.task('dd:afterEach', { test: testInfo, coverage, commands: commandsToReport }).then((taskResult) => {
1337
+ // Preserve the first-attempt result until Cypress starts the retry runnable.
1338
+ // Changing the completed test here is too late for Cypress's retry lifecycle.
1339
+ if (taskResult && Number.isSafeInteger(taskResult.dynamicAtrRetryCount)) {
1340
+ dynamicAtrRetryCountByTest.set(getDynamicAtrTestKey(currentTest), taskResult.dynamicAtrRetryCount)
1341
+ }
1342
+ })
569
1343
  })
570
- })
1344
+ }
1345
+
1346
+ const supportRoot = Cypress.mocha.getRootSuite()
1347
+ supportRoot[Symbol.for('dd-trace.cypress.install-lifecycle')] = installLifecycleHooks
1348
+ if (!supportRoot[Symbol.for('dd-trace.cypress.defer-lifecycle')]) installLifecycleHooks()