@depup/dd-trace 5.97.0-depup.0 → 6.5.0-depup.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 (712) hide show
  1. package/LICENSE-3rdparty.csv +89 -104
  2. package/README.electron.md +7 -0
  3. package/README.md +2 -2
  4. package/changes.json +1 -1
  5. package/ci/diagnose.js +2100 -0
  6. package/ci/init.js +46 -5
  7. package/ci/runbook.md +198 -0
  8. package/ci/test-optimization-validation/approval-artifacts.js +143 -0
  9. package/ci/test-optimization-validation/approval.js +299 -0
  10. package/ci/test-optimization-validation/artifact-id.js +20 -0
  11. package/ci/test-optimization-validation/bounded-json.js +121 -0
  12. package/ci/test-optimization-validation/ci-command-candidate.js +83 -0
  13. package/ci/test-optimization-validation/ci-discovery.js +181 -0
  14. package/ci/test-optimization-validation/ci-remediation.js +210 -0
  15. package/ci/test-optimization-validation/cli.js +903 -0
  16. package/ci/test-optimization-validation/command-blocker.js +81 -0
  17. package/ci/test-optimization-validation/command-output-policy.js +206 -0
  18. package/ci/test-optimization-validation/command-runner.js +707 -0
  19. package/ci/test-optimization-validation/command-suitability.js +471 -0
  20. package/ci/test-optimization-validation/executable-approval.js +48 -0
  21. package/ci/test-optimization-validation/executable.js +480 -0
  22. package/ci/test-optimization-validation/generated-file-policy.js +63 -0
  23. package/ci/test-optimization-validation/generated-files.js +351 -0
  24. package/ci/test-optimization-validation/generated-verifier.js +196 -0
  25. package/ci/test-optimization-validation/init-probe-preload.js +163 -0
  26. package/ci/test-optimization-validation/init-probe.js +246 -0
  27. package/ci/test-optimization-validation/late-initialization.js +63 -0
  28. package/ci/test-optimization-validation/local-command.js +163 -0
  29. package/ci/test-optimization-validation/manifest-loader.js +133 -0
  30. package/ci/test-optimization-validation/manifest-scaffold.js +738 -0
  31. package/ci/test-optimization-validation/manifest-schema.js +862 -0
  32. package/ci/test-optimization-validation/offline-fixtures.js +327 -0
  33. package/ci/test-optimization-validation/offline-output.js +406 -0
  34. package/ci/test-optimization-validation/payload-normalizer.js +72 -0
  35. package/ci/test-optimization-validation/plan-writer.js +1120 -0
  36. package/ci/test-optimization-validation/preflight-runner.js +114 -0
  37. package/ci/test-optimization-validation/redaction.js +331 -0
  38. package/ci/test-optimization-validation/report-writer.js +1508 -0
  39. package/ci/test-optimization-validation/safe-files.js +203 -0
  40. package/ci/test-optimization-validation/scenarios/auto-test-retries.js +159 -0
  41. package/ci/test-optimization-validation/scenarios/basic-reporting.js +657 -0
  42. package/ci/test-optimization-validation/scenarios/ci-wiring.js +780 -0
  43. package/ci/test-optimization-validation/scenarios/early-flake-detection.js +141 -0
  44. package/ci/test-optimization-validation/scenarios/helpers.js +539 -0
  45. package/ci/test-optimization-validation/scenarios/test-management.js +218 -0
  46. package/ci/test-optimization-validation/setup-runner.js +97 -0
  47. package/ci/test-optimization-validation/static-diagnosis.js +159 -0
  48. package/ci/test-optimization-validation/test-output.js +129 -0
  49. package/ci/test-optimization-validation-manifest.schema.json +1 -0
  50. package/ci/validate-test-optimization.js +3 -0
  51. package/ci/vitest-no-worker-init-setup.mjs +430 -0
  52. package/ext/exporters.js +2 -0
  53. package/ext/tags.js +3 -0
  54. package/index.d.ts +436 -252
  55. package/index.electron.js +3 -0
  56. package/init.js +18 -0
  57. package/initialize.mjs +10 -9
  58. package/loader-hook.mjs +170 -53
  59. package/openfeature.d.ts +1 -0
  60. package/openfeature.js +4 -0
  61. package/package.json +118 -80
  62. package/packages/datadog-core/src/storage.js +47 -48
  63. package/packages/datadog-esbuild/index.js +32 -1
  64. package/packages/datadog-esbuild/src/utils.js +46 -3
  65. package/packages/datadog-instrumentations/src/aerospike.js +3 -3
  66. package/packages/datadog-instrumentations/src/ai.js +137 -76
  67. package/packages/datadog-instrumentations/src/amqplib.js +6 -7
  68. package/packages/datadog-instrumentations/src/anthropic.js +10 -10
  69. package/packages/datadog-instrumentations/src/apollo-server-core.js +3 -3
  70. package/packages/datadog-instrumentations/src/apollo-server.js +10 -18
  71. package/packages/datadog-instrumentations/src/avsc.js +6 -6
  72. package/packages/datadog-instrumentations/src/aws-durable-execution-sdk-js-context-methods.js +18 -0
  73. package/packages/datadog-instrumentations/src/aws-durable-execution-sdk-js.js +111 -0
  74. package/packages/datadog-instrumentations/src/aws-sdk.js +172 -72
  75. package/packages/datadog-instrumentations/src/azure-cosmos.js +7 -0
  76. package/packages/datadog-instrumentations/src/azure-durable-functions.js +8 -8
  77. package/packages/datadog-instrumentations/src/azure-functions.js +3 -0
  78. package/packages/datadog-instrumentations/src/bluebird.js +2 -2
  79. package/packages/datadog-instrumentations/src/body-parser.js +5 -2
  80. package/packages/datadog-instrumentations/src/cassandra-driver.js +12 -9
  81. package/packages/datadog-instrumentations/src/child_process.js +16 -16
  82. package/packages/datadog-instrumentations/src/claude-agent-sdk.js +587 -0
  83. package/packages/datadog-instrumentations/src/confluentinc-kafka-javascript.js +41 -24
  84. package/packages/datadog-instrumentations/src/connect.js +14 -12
  85. package/packages/datadog-instrumentations/src/cookie-parser.js +5 -4
  86. package/packages/datadog-instrumentations/src/cookie.js +9 -3
  87. package/packages/datadog-instrumentations/src/couchbase.js +73 -238
  88. package/packages/datadog-instrumentations/src/crypto.js +49 -4
  89. package/packages/datadog-instrumentations/src/cucumber-worker-threads.js +25 -0
  90. package/packages/datadog-instrumentations/src/cucumber.js +762 -189
  91. package/packages/datadog-instrumentations/src/cypress-config.js +547 -93
  92. package/packages/datadog-instrumentations/src/cypress.js +5 -3
  93. package/packages/datadog-instrumentations/src/dns.js +60 -59
  94. package/packages/datadog-instrumentations/src/elasticsearch.js +9 -12
  95. package/packages/datadog-instrumentations/src/electron/preload.js +42 -0
  96. package/packages/datadog-instrumentations/src/electron.js +240 -0
  97. package/packages/datadog-instrumentations/src/express-mongo-sanitize.js +11 -9
  98. package/packages/datadog-instrumentations/src/express-session.js +14 -13
  99. package/packages/datadog-instrumentations/src/express.js +52 -30
  100. package/packages/datadog-instrumentations/src/fastify.js +166 -87
  101. package/packages/datadog-instrumentations/src/fetch.js +5 -5
  102. package/packages/datadog-instrumentations/src/fs.js +22 -20
  103. package/packages/datadog-instrumentations/src/google-cloud-pubsub.js +5 -7
  104. package/packages/datadog-instrumentations/src/google-genai.js +4 -4
  105. package/packages/datadog-instrumentations/src/graphql.js +26 -362
  106. package/packages/datadog-instrumentations/src/grpc/client.js +48 -32
  107. package/packages/datadog-instrumentations/src/grpc/server.js +20 -2
  108. package/packages/datadog-instrumentations/src/hapi.js +2 -2
  109. package/packages/datadog-instrumentations/src/helpers/callback-instrumentor.js +74 -0
  110. package/packages/datadog-instrumentations/src/helpers/check-require-cache.js +85 -9
  111. package/packages/datadog-instrumentations/src/helpers/hook.js +31 -7
  112. package/packages/datadog-instrumentations/src/helpers/hooks.js +12 -0
  113. package/packages/datadog-instrumentations/src/helpers/instrument.js +36 -3
  114. package/packages/datadog-instrumentations/src/helpers/kafka.js +58 -0
  115. package/packages/datadog-instrumentations/src/helpers/optional-peer-bundler.js +65 -0
  116. package/packages/datadog-instrumentations/src/helpers/promise-instrumentor.js +42 -0
  117. package/packages/datadog-instrumentations/src/helpers/promise.js +2 -2
  118. package/packages/datadog-instrumentations/src/helpers/register.js +7 -5
  119. package/packages/datadog-instrumentations/src/helpers/rewriter/compiler.js +13 -5
  120. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +24 -7
  121. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/ai.js +6 -6
  122. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/aws-durable-execution-sdk-js.js +31 -0
  123. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/azure-cosmos.js +50 -0
  124. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/claude-agent-sdk.js +17 -0
  125. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +201 -0
  126. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/index.js +7 -0
  127. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/langgraph.js +4 -2
  128. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/mercurius.js +31 -0
  129. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-sdk.js +35 -0
  130. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/playwright.js +111 -0
  131. package/packages/datadog-instrumentations/src/helpers/rewriter/loader.mjs +18 -2
  132. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +49 -224
  133. package/packages/datadog-instrumentations/src/helpers/router-helper.js +8 -8
  134. package/packages/datadog-instrumentations/src/hono.js +71 -9
  135. package/packages/datadog-instrumentations/src/http/client.js +48 -24
  136. package/packages/datadog-instrumentations/src/http/server.js +75 -29
  137. package/packages/datadog-instrumentations/src/http2/client.js +15 -12
  138. package/packages/datadog-instrumentations/src/http2/server.js +156 -23
  139. package/packages/datadog-instrumentations/src/ioredis.js +17 -14
  140. package/packages/datadog-instrumentations/src/iovalkey.js +1 -2
  141. package/packages/datadog-instrumentations/src/jest/bail-reporter.js +42 -0
  142. package/packages/datadog-instrumentations/src/jest/coverage-backfill.js +163 -0
  143. package/packages/datadog-instrumentations/src/jest.js +1809 -401
  144. package/packages/datadog-instrumentations/src/kafkajs.js +284 -170
  145. package/packages/datadog-instrumentations/src/knex.js +17 -17
  146. package/packages/datadog-instrumentations/src/koa.js +15 -14
  147. package/packages/datadog-instrumentations/src/ldapjs.js +5 -5
  148. package/packages/datadog-instrumentations/src/light-my-request.js +2 -2
  149. package/packages/datadog-instrumentations/src/limitd-client.js +4 -4
  150. package/packages/datadog-instrumentations/src/lodash.js +4 -4
  151. package/packages/datadog-instrumentations/src/mariadb.js +18 -16
  152. package/packages/datadog-instrumentations/src/memcached.js +4 -3
  153. package/packages/datadog-instrumentations/src/mercurius.js +11 -0
  154. package/packages/datadog-instrumentations/src/microgateway-core.js +2 -2
  155. package/packages/datadog-instrumentations/src/mocha/common.js +7 -4
  156. package/packages/datadog-instrumentations/src/mocha/main.js +557 -120
  157. package/packages/datadog-instrumentations/src/mocha/utils.js +531 -135
  158. package/packages/datadog-instrumentations/src/mocha/worker.js +27 -9
  159. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +254 -0
  160. package/packages/datadog-instrumentations/src/mongodb-core.js +43 -31
  161. package/packages/datadog-instrumentations/src/mongodb.js +82 -8
  162. package/packages/datadog-instrumentations/src/mongoose.js +46 -37
  163. package/packages/datadog-instrumentations/src/mquery.js +7 -7
  164. package/packages/datadog-instrumentations/src/multer.js +5 -4
  165. package/packages/datadog-instrumentations/src/mysql.js +17 -17
  166. package/packages/datadog-instrumentations/src/mysql2.js +39 -5
  167. package/packages/datadog-instrumentations/src/nats.js +182 -0
  168. package/packages/datadog-instrumentations/src/net.js +19 -11
  169. package/packages/datadog-instrumentations/src/next.js +68 -10
  170. package/packages/datadog-instrumentations/src/nyc.js +43 -8
  171. package/packages/datadog-instrumentations/src/openai.js +124 -38
  172. package/packages/datadog-instrumentations/src/oracledb.js +12 -7
  173. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +27 -6
  174. package/packages/datadog-instrumentations/src/passport-utils.js +5 -5
  175. package/packages/datadog-instrumentations/src/path-to-regexp.js +44 -0
  176. package/packages/datadog-instrumentations/src/pg.js +58 -25
  177. package/packages/datadog-instrumentations/src/pino.js +25 -41
  178. package/packages/datadog-instrumentations/src/playwright-browser-scripts.js +27 -0
  179. package/packages/datadog-instrumentations/src/playwright.js +1229 -356
  180. package/packages/datadog-instrumentations/src/process.js +3 -0
  181. package/packages/datadog-instrumentations/src/protobufjs.js +16 -16
  182. package/packages/datadog-instrumentations/src/redis.js +28 -15
  183. package/packages/datadog-instrumentations/src/restify.js +6 -5
  184. package/packages/datadog-instrumentations/src/router.js +253 -87
  185. package/packages/datadog-instrumentations/src/selenium.js +53 -28
  186. package/packages/datadog-instrumentations/src/stripe.js +47 -33
  187. package/packages/datadog-instrumentations/src/tedious.js +28 -0
  188. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +1297 -0
  189. package/packages/datadog-instrumentations/src/vitest-main.js +1590 -0
  190. package/packages/datadog-instrumentations/src/vitest-util.js +251 -0
  191. package/packages/datadog-instrumentations/src/vitest-worker.js +822 -0
  192. package/packages/datadog-instrumentations/src/vitest.js +11 -1262
  193. package/packages/datadog-instrumentations/src/winston.js +4 -4
  194. package/packages/datadog-instrumentations/src/ws.js +9 -8
  195. package/packages/datadog-instrumentations/src/zlib.js +29 -0
  196. package/packages/datadog-plugin-ai/src/index.js +1 -1
  197. package/packages/datadog-plugin-ai/src/tracing.js +66 -3
  198. package/packages/datadog-plugin-ai/src/utils.js +17 -4
  199. package/packages/datadog-plugin-apollo/src/gateway/request.js +1 -21
  200. package/packages/datadog-plugin-avsc/src/schema_iterator.js +3 -3
  201. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/checkpoint.js +31 -0
  202. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/client.js +55 -0
  203. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/context.js +123 -0
  204. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/handler.js +129 -0
  205. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/index.js +19 -0
  206. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/trace-checkpoint.js +224 -0
  207. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/util.js +80 -0
  208. package/packages/datadog-plugin-aws-sdk/src/base.js +86 -50
  209. package/packages/datadog-plugin-aws-sdk/src/services/bedrockruntime/tracing.js +1 -1
  210. package/packages/datadog-plugin-aws-sdk/src/services/bedrockruntime/utils.js +218 -4
  211. package/packages/datadog-plugin-aws-sdk/src/services/cloudwatchlogs.js +1 -1
  212. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +2 -1
  213. package/packages/datadog-plugin-aws-sdk/src/services/eventbridge.js +59 -14
  214. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +174 -75
  215. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +34 -23
  216. package/packages/datadog-plugin-aws-sdk/src/services/redshift.js +2 -1
  217. package/packages/datadog-plugin-aws-sdk/src/services/s3.js +1 -1
  218. package/packages/datadog-plugin-aws-sdk/src/services/sns.js +26 -26
  219. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +187 -101
  220. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +20 -18
  221. package/packages/datadog-plugin-aws-sdk/src/util.js +2 -2
  222. package/packages/datadog-plugin-azure-cosmos/src/index.js +144 -0
  223. package/packages/datadog-plugin-azure-event-hubs/src/producer.js +8 -15
  224. package/packages/datadog-plugin-azure-functions/src/index.js +7 -3
  225. package/packages/datadog-plugin-azure-service-bus/src/producer.js +5 -10
  226. package/packages/datadog-plugin-bullmq/src/consumer.js +5 -4
  227. package/packages/datadog-plugin-bullmq/src/filter.js +35 -0
  228. package/packages/datadog-plugin-bullmq/src/producer.js +121 -33
  229. package/packages/datadog-plugin-bunyan/src/index.js +28 -0
  230. package/packages/datadog-plugin-child_process/src/index.js +13 -2
  231. package/packages/datadog-plugin-child_process/src/scrub-cmd-params.js +6 -6
  232. package/packages/datadog-plugin-claude-agent-sdk/src/index.js +31 -0
  233. package/packages/datadog-plugin-claude-agent-sdk/src/tracing.js +107 -0
  234. package/packages/datadog-plugin-claude-agent-sdk/src/util.js +15 -0
  235. package/packages/datadog-plugin-couchbase/src/index.js +58 -52
  236. package/packages/datadog-plugin-cucumber/src/index.js +47 -29
  237. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +929 -98
  238. package/packages/datadog-plugin-cypress/src/index.js +109 -2
  239. package/packages/datadog-plugin-cypress/src/plugin.js +6 -14
  240. package/packages/datadog-plugin-cypress/src/source-map-utils.js +48 -1
  241. package/packages/datadog-plugin-cypress/src/support.js +272 -51
  242. package/packages/datadog-plugin-dd-trace-api/src/index.js +1 -1
  243. package/packages/datadog-plugin-dns/src/lookup.js +8 -6
  244. package/packages/datadog-plugin-elasticsearch/src/index.js +28 -8
  245. package/packages/datadog-plugin-electron/src/index.js +17 -0
  246. package/packages/datadog-plugin-electron/src/ipc.js +143 -0
  247. package/packages/datadog-plugin-electron/src/net.js +82 -0
  248. package/packages/datadog-plugin-express/src/code_origin.js +1 -1
  249. package/packages/datadog-plugin-fastify/src/code_origin.js +1 -1
  250. package/packages/datadog-plugin-fs/src/index.js +2 -1
  251. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +2 -5
  252. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +27 -18
  253. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +5 -8
  254. package/packages/datadog-plugin-graphql/src/execute.js +748 -34
  255. package/packages/datadog-plugin-graphql/src/index.js +43 -9
  256. package/packages/datadog-plugin-graphql/src/parse.js +45 -4
  257. package/packages/datadog-plugin-graphql/src/request.js +135 -0
  258. package/packages/datadog-plugin-graphql/src/tools/signature.js +32 -7
  259. package/packages/datadog-plugin-graphql/src/tools/transforms.js +118 -100
  260. package/packages/datadog-plugin-graphql/src/utils.js +261 -3
  261. package/packages/datadog-plugin-graphql/src/validate.js +54 -8
  262. package/packages/datadog-plugin-grpc/src/client.js +7 -8
  263. package/packages/datadog-plugin-grpc/src/server.js +1 -1
  264. package/packages/datadog-plugin-grpc/src/util.js +57 -22
  265. package/packages/datadog-plugin-http/src/client.js +12 -14
  266. package/packages/datadog-plugin-http/src/index.js +6 -8
  267. package/packages/datadog-plugin-http/src/server.js +63 -20
  268. package/packages/datadog-plugin-http2/src/client.js +7 -4
  269. package/packages/datadog-plugin-http2/src/server.js +48 -8
  270. package/packages/datadog-plugin-jest/src/index.js +133 -67
  271. package/packages/datadog-plugin-jest/src/util.js +37 -16
  272. package/packages/datadog-plugin-kafkajs/src/batch-consumer.js +1 -1
  273. package/packages/datadog-plugin-kafkajs/src/consumer.js +2 -9
  274. package/packages/datadog-plugin-kafkajs/src/producer.js +37 -8
  275. package/packages/datadog-plugin-langchain/src/handlers/embedding.js +2 -1
  276. package/packages/datadog-plugin-langchain/src/handlers/language_models.js +2 -1
  277. package/packages/datadog-plugin-langchain/src/tokens.js +2 -2
  278. package/packages/datadog-plugin-langgraph/src/stream.js +1 -1
  279. package/packages/datadog-plugin-memcached/src/index.js +1 -1
  280. package/packages/datadog-plugin-mocha/src/index.js +66 -20
  281. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/index.js +24 -0
  282. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +173 -0
  283. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +30 -0
  284. package/packages/datadog-plugin-mongodb-core/src/bulk-write.js +43 -0
  285. package/packages/datadog-plugin-mongodb-core/src/index.js +8 -206
  286. package/packages/datadog-plugin-mongodb-core/src/query.js +452 -0
  287. package/packages/datadog-plugin-mysql/src/index.js +9 -4
  288. package/packages/datadog-plugin-nats/src/consumer.js +43 -0
  289. package/packages/datadog-plugin-nats/src/index.js +20 -0
  290. package/packages/datadog-plugin-nats/src/producer.js +62 -0
  291. package/packages/datadog-plugin-nats/src/util.js +33 -0
  292. package/packages/datadog-plugin-next/src/index.js +12 -4
  293. package/packages/datadog-plugin-openai/src/services.js +4 -3
  294. package/packages/datadog-plugin-openai/src/tracing.js +27 -25
  295. package/packages/datadog-plugin-oracledb/src/index.js +13 -2
  296. package/packages/datadog-plugin-pg/src/index.js +13 -3
  297. package/packages/datadog-plugin-pino/src/index.js +42 -0
  298. package/packages/datadog-plugin-playwright/src/index.js +195 -72
  299. package/packages/datadog-plugin-protobufjs/src/schema_iterator.js +3 -3
  300. package/packages/datadog-plugin-redis/src/index.js +54 -25
  301. package/packages/datadog-plugin-rhea/src/producer.js +1 -1
  302. package/packages/datadog-plugin-router/src/index.js +55 -44
  303. package/packages/datadog-plugin-selenium/src/index.js +5 -36
  304. package/packages/datadog-plugin-tedious/src/index.js +1 -1
  305. package/packages/datadog-plugin-undici/src/index.js +24 -2
  306. package/packages/datadog-plugin-vitest/src/index.js +160 -90
  307. package/packages/datadog-plugin-winston/src/index.js +30 -0
  308. package/packages/datadog-plugin-ws/src/close.js +5 -2
  309. package/packages/datadog-plugin-ws/src/producer.js +4 -1
  310. package/packages/datadog-plugin-ws/src/receiver.js +4 -2
  311. package/packages/datadog-plugin-ws/src/server.js +2 -1
  312. package/packages/datadog-shimmer/src/shimmer.js +101 -39
  313. package/packages/datadog-webpack/index.js +17 -1
  314. package/packages/datadog-webpack/src/optional-peer-loader.js +17 -0
  315. package/packages/dd-trace/index.electron.js +3 -0
  316. package/packages/dd-trace/index.js +2 -36
  317. package/packages/dd-trace/src/aiguard/channels.js +7 -0
  318. package/packages/dd-trace/src/aiguard/index.js +16 -34
  319. package/packages/dd-trace/src/aiguard/integrations/evaluate.js +46 -0
  320. package/packages/dd-trace/src/aiguard/integrations/index.js +34 -0
  321. package/packages/dd-trace/src/aiguard/integrations/openai.js +80 -0
  322. package/packages/dd-trace/src/aiguard/integrations/vercel-ai.js +92 -0
  323. package/packages/dd-trace/src/aiguard/messages/openai.js +382 -0
  324. package/packages/{datadog-instrumentations/src/helpers/ai-messages.js → dd-trace/src/aiguard/messages/vercel-ai.js} +30 -27
  325. package/packages/dd-trace/src/aiguard/sdk.js +148 -55
  326. package/packages/dd-trace/src/aiguard/tags.js +26 -10
  327. package/packages/dd-trace/src/appsec/api_security/index.js +55 -0
  328. package/packages/dd-trace/src/appsec/api_security/sampler.js +147 -0
  329. package/packages/dd-trace/src/appsec/blocked_templates.js +4 -3
  330. package/packages/dd-trace/src/appsec/blocking.js +82 -42
  331. package/packages/dd-trace/src/appsec/channels.js +5 -1
  332. package/packages/dd-trace/src/appsec/downstream_requests.js +116 -62
  333. package/packages/dd-trace/src/appsec/graphql.js +20 -17
  334. package/packages/dd-trace/src/appsec/iast/analyzers/hardcoded-password-rules.js +1 -1
  335. package/packages/dd-trace/src/appsec/iast/analyzers/hardcoded-secret-rules.js +81 -81
  336. package/packages/dd-trace/src/appsec/iast/analyzers/nosql-injection-mongodb-analyzer.js +23 -23
  337. package/packages/dd-trace/src/appsec/iast/index.js +3 -2
  338. package/packages/dd-trace/src/appsec/iast/security-controls/index.js +4 -4
  339. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugin.js +2 -2
  340. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugins/kafka.js +2 -2
  341. package/packages/dd-trace/src/appsec/iast/taint-tracking/rewriter.js +4 -4
  342. package/packages/dd-trace/src/appsec/iast/taint-tracking/taint-tracking-impl.js +2 -2
  343. package/packages/dd-trace/src/appsec/iast/telemetry/index.js +2 -1
  344. package/packages/dd-trace/src/appsec/iast/telemetry/span-tags.js +3 -1
  345. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-analyzers/ldap-sensitive-analyzer.js +54 -12
  346. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-analyzers/url-sensitive-analyzer.js +5 -1
  347. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-handler.js +31 -4
  348. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/index.js +1 -3
  349. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/utils.js +83 -48
  350. package/packages/dd-trace/src/appsec/iast/vulnerability-reporter.js +1 -1
  351. package/packages/dd-trace/src/appsec/index.js +65 -47
  352. package/packages/dd-trace/src/appsec/lambda.js +135 -0
  353. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -5
  354. package/packages/dd-trace/src/appsec/rasp/lfi.js +8 -4
  355. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +5 -10
  356. package/packages/dd-trace/src/appsec/rasp/ssrf.js +26 -18
  357. package/packages/dd-trace/src/appsec/recommended.json +2438 -13
  358. package/packages/dd-trace/src/appsec/reporter.js +87 -28
  359. package/packages/dd-trace/src/appsec/rule_manager.js +4 -2
  360. package/packages/dd-trace/src/appsec/sdk/set_user.js +1 -1
  361. package/packages/dd-trace/src/appsec/sdk/track_event.js +5 -5
  362. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +7 -11
  363. package/packages/dd-trace/src/appsec/sdk/utils.js +5 -3
  364. package/packages/dd-trace/src/appsec/store.js +50 -0
  365. package/packages/dd-trace/src/appsec/telemetry/api_security.js +34 -0
  366. package/packages/dd-trace/src/appsec/telemetry/index.js +27 -1
  367. package/packages/dd-trace/src/appsec/user_tracking.js +5 -4
  368. package/packages/dd-trace/src/appsec/waf/index.js +19 -9
  369. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +35 -20
  370. package/packages/dd-trace/src/appsec/waf/waf_manager.js +1 -1
  371. package/packages/dd-trace/src/azure_metadata.js +19 -7
  372. package/packages/dd-trace/src/baggage.js +32 -13
  373. package/packages/dd-trace/src/bootstrap.js +39 -0
  374. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/index.js +123 -33
  375. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +122 -24
  376. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +22 -7
  377. package/packages/dd-trace/src/ci-visibility/exporters/agent-proxy/index.js +5 -2
  378. package/packages/dd-trace/src/ci-visibility/exporters/agentless/coverage-writer.js +2 -2
  379. package/packages/dd-trace/src/ci-visibility/exporters/agentless/di-logs-writer.js +2 -2
  380. package/packages/dd-trace/src/ci-visibility/exporters/agentless/index.js +6 -2
  381. package/packages/dd-trace/src/ci-visibility/exporters/agentless/writer.js +2 -2
  382. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +160 -0
  383. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +288 -0
  384. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/payload-projection.js +84 -0
  385. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +369 -0
  386. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/writer.js +60 -0
  387. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +188 -27
  388. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +3 -4
  389. package/packages/dd-trace/src/ci-visibility/exporters/test-worker/index.js +28 -10
  390. package/packages/dd-trace/src/ci-visibility/exporters/test-worker/writer.js +22 -0
  391. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +110 -22
  392. package/packages/dd-trace/src/ci-visibility/lage.js +2 -1
  393. package/packages/dd-trace/src/ci-visibility/log-submission/log-submission-plugin.js +4 -5
  394. package/packages/dd-trace/src/ci-visibility/requests/fs-cache.js +4 -5
  395. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +73 -55
  396. package/packages/dd-trace/src/ci-visibility/requests/request.js +14 -50
  397. package/packages/dd-trace/src/ci-visibility/requests/upload-coverage-report.js +10 -6
  398. package/packages/dd-trace/src/ci-visibility/requests/upload-test-screenshot.js +156 -0
  399. package/packages/dd-trace/src/ci-visibility/rum.js +7 -0
  400. package/packages/dd-trace/src/ci-visibility/test-api-manual/test-api-manual-plugin.js +9 -3
  401. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +24 -6
  402. package/packages/dd-trace/src/ci-visibility/test-optimization-cache.js +70 -6
  403. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +256 -0
  404. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +451 -0
  405. package/packages/dd-trace/src/ci-visibility/test-screenshot.js +90 -0
  406. package/packages/dd-trace/src/config/config-types.d.ts +8 -6
  407. package/packages/dd-trace/src/config/defaults.js +71 -44
  408. package/packages/dd-trace/src/config/generated-config-types.d.ts +692 -131
  409. package/packages/dd-trace/src/config/git_properties.js +2 -2
  410. package/packages/dd-trace/src/config/helper.js +140 -33
  411. package/packages/dd-trace/src/config/index.js +127 -131
  412. package/packages/dd-trace/src/config/major-overrides.js +100 -0
  413. package/packages/dd-trace/src/config/normalize-service.js +31 -0
  414. package/packages/dd-trace/src/config/parsers.js +138 -10
  415. package/packages/dd-trace/src/config/remote_config.js +1 -1
  416. package/packages/dd-trace/src/config/supported-configurations.json +460 -203
  417. package/packages/dd-trace/src/constants.js +15 -0
  418. package/packages/dd-trace/src/crashtracking/crashtracker.js +18 -6
  419. package/packages/dd-trace/src/datastreams/checkpointer.js +6 -12
  420. package/packages/dd-trace/src/datastreams/context.js +4 -2
  421. package/packages/dd-trace/src/datastreams/encoding.js +39 -28
  422. package/packages/dd-trace/src/datastreams/index.js +2 -1
  423. package/packages/dd-trace/src/datastreams/manager.js +1 -1
  424. package/packages/dd-trace/src/datastreams/pathway.js +35 -30
  425. package/packages/dd-trace/src/datastreams/processor.js +31 -22
  426. package/packages/dd-trace/src/datastreams/size.js +6 -2
  427. package/packages/dd-trace/src/datastreams/writer.js +15 -6
  428. package/packages/dd-trace/src/debugger/config.js +9 -4
  429. package/packages/dd-trace/src/debugger/devtools_client/breakpoints.js +49 -35
  430. package/packages/dd-trace/src/debugger/devtools_client/condition.js +5 -8
  431. package/packages/dd-trace/src/debugger/devtools_client/config.js +3 -2
  432. package/packages/dd-trace/src/debugger/devtools_client/index.js +33 -71
  433. package/packages/dd-trace/src/debugger/devtools_client/probe_sampler.js +83 -0
  434. package/packages/dd-trace/src/debugger/devtools_client/send.js +27 -6
  435. package/packages/dd-trace/src/debugger/devtools_client/snapshot/collector.js +2 -2
  436. package/packages/dd-trace/src/debugger/devtools_client/snapshot/processor.js +5 -2
  437. package/packages/dd-trace/src/debugger/devtools_client/snapshot-pruner.js +1 -0
  438. package/packages/dd-trace/src/debugger/devtools_client/source-maps.js +1 -1
  439. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  440. package/packages/dd-trace/src/debugger/index.js +13 -9
  441. package/packages/dd-trace/src/debugger/probe_sampler.js +112 -0
  442. package/packages/dd-trace/src/debugger/probe_sampler_constants.js +19 -0
  443. package/packages/dd-trace/src/dogstatsd.js +34 -28
  444. package/packages/dd-trace/src/encode/0.4.js +829 -268
  445. package/packages/dd-trace/src/encode/0.5.js +158 -22
  446. package/packages/dd-trace/src/encode/agentless-ci-visibility.js +141 -65
  447. package/packages/dd-trace/src/encode/agentless-json.js +12 -6
  448. package/packages/dd-trace/src/encode/coverage-ci-visibility.js +52 -15
  449. package/packages/dd-trace/src/encode/span-stats.js +19 -16
  450. package/packages/dd-trace/src/encode/tags-processors.js +30 -25
  451. package/packages/dd-trace/src/exporter.js +5 -1
  452. package/packages/dd-trace/src/exporters/agent/index.js +4 -5
  453. package/packages/dd-trace/src/exporters/agent/writer.js +1 -2
  454. package/packages/dd-trace/src/exporters/agentless/index.js +12 -13
  455. package/packages/dd-trace/src/exporters/agentless/intake.js +43 -0
  456. package/packages/dd-trace/src/exporters/agentless/writer.js +12 -11
  457. package/packages/dd-trace/src/exporters/common/agents.js +3 -1
  458. package/packages/dd-trace/src/exporters/common/buffering-exporter.js +3 -3
  459. package/packages/dd-trace/src/exporters/common/client-library-headers.js +21 -0
  460. package/packages/dd-trace/src/exporters/common/request.js +93 -44
  461. package/packages/dd-trace/src/exporters/common/retry.js +104 -0
  462. package/packages/dd-trace/src/exporters/common/url.js +48 -0
  463. package/packages/dd-trace/src/exporters/common/util.js +2 -2
  464. package/packages/dd-trace/src/exporters/common/writer.js +17 -1
  465. package/packages/dd-trace/src/exporters/electron/index.js +49 -0
  466. package/packages/dd-trace/src/exporters/span-stats/index.js +1 -2
  467. package/packages/dd-trace/src/exporters/span-stats/writer.js +1 -3
  468. package/packages/dd-trace/src/external-logger/src/index.js +2 -1
  469. package/packages/dd-trace/src/feature-registry.js +29 -0
  470. package/packages/dd-trace/src/git_metadata.js +68 -0
  471. package/packages/dd-trace/src/git_metadata_tagger.js +13 -5
  472. package/packages/dd-trace/src/guardrails/index.js +11 -6
  473. package/packages/dd-trace/src/guardrails/telemetry.js +40 -3
  474. package/packages/dd-trace/src/heap_snapshots.js +4 -4
  475. package/packages/dd-trace/src/id.js +46 -27
  476. package/packages/dd-trace/src/index.js +7 -8
  477. package/packages/dd-trace/src/lambda/handler-paths.js +52 -0
  478. package/packages/dd-trace/src/lambda/handler.js +2 -6
  479. package/packages/dd-trace/src/lambda/index.js +62 -14
  480. package/packages/dd-trace/src/lambda/runtime/patch.js +21 -46
  481. package/packages/dd-trace/src/llmobs/constants/tags.js +13 -0
  482. package/packages/dd-trace/src/llmobs/experiments/client.js +113 -0
  483. package/packages/dd-trace/src/llmobs/experiments/dataset.js +154 -0
  484. package/packages/dd-trace/src/llmobs/experiments/experiment.js +283 -0
  485. package/packages/dd-trace/src/llmobs/experiments/index.js +152 -0
  486. package/packages/dd-trace/src/llmobs/experiments/noop.js +30 -0
  487. package/packages/dd-trace/src/llmobs/experiments/result.js +34 -0
  488. package/packages/dd-trace/src/llmobs/index.js +37 -7
  489. package/packages/dd-trace/src/llmobs/noop.js +6 -0
  490. package/packages/dd-trace/src/llmobs/plugins/ai/ddTelemetry.js +403 -0
  491. package/packages/dd-trace/src/llmobs/plugins/ai/index.js +8 -395
  492. package/packages/dd-trace/src/llmobs/plugins/ai/util.js +119 -7
  493. package/packages/dd-trace/src/llmobs/plugins/ai/vercelTelemetry.js +380 -0
  494. package/packages/dd-trace/src/llmobs/plugins/{anthropic.js → anthropic/index.js} +32 -79
  495. package/packages/dd-trace/src/llmobs/plugins/anthropic/util.js +109 -0
  496. package/packages/dd-trace/src/llmobs/plugins/base.js +4 -4
  497. package/packages/dd-trace/src/llmobs/plugins/bedrockruntime.js +89 -37
  498. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +270 -0
  499. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/utils.js +10 -0
  500. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +5 -1
  501. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +81 -16
  502. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/chain.js +3 -2
  503. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/chat_model.js +3 -2
  504. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/embedding.js +2 -1
  505. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/index.js +1 -50
  506. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/vectorstore.js +2 -1
  507. package/packages/dd-trace/src/llmobs/plugins/langchain/index.js +14 -8
  508. package/packages/dd-trace/src/llmobs/plugins/langchain/messages.js +76 -0
  509. package/packages/dd-trace/src/llmobs/plugins/langgraph/index.js +4 -29
  510. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +68 -0
  511. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +57 -0
  512. package/packages/dd-trace/src/llmobs/plugins/openai/constants.js +8 -0
  513. package/packages/dd-trace/src/llmobs/plugins/openai/index.js +68 -64
  514. package/packages/dd-trace/src/llmobs/plugins/openai/utils.js +43 -0
  515. package/packages/dd-trace/src/llmobs/sdk.js +73 -35
  516. package/packages/dd-trace/src/llmobs/span_processor.js +90 -11
  517. package/packages/dd-trace/src/llmobs/tagger.js +197 -4
  518. package/packages/dd-trace/src/llmobs/telemetry.js +33 -2
  519. package/packages/dd-trace/src/llmobs/util.js +234 -9
  520. package/packages/dd-trace/src/llmobs/writers/base.js +11 -5
  521. package/packages/dd-trace/src/llmobs/writers/spans.js +1 -1
  522. package/packages/dd-trace/src/llmobs/writers/util.js +1 -2
  523. package/packages/dd-trace/src/log/index.js +19 -31
  524. package/packages/dd-trace/src/log/writer.js +3 -1
  525. package/packages/dd-trace/src/msgpack/chunk.js +430 -11
  526. package/packages/dd-trace/src/msgpack/index.js +101 -2
  527. package/packages/dd-trace/src/noop/proxy.js +5 -4
  528. package/packages/dd-trace/src/noop/span.js +3 -1
  529. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +322 -0
  530. package/packages/dd-trace/src/openfeature/configuration_source.js +90 -0
  531. package/packages/dd-trace/src/openfeature/encoding.js +70 -0
  532. package/packages/dd-trace/src/openfeature/eval-metrics-hook.js +103 -0
  533. package/packages/dd-trace/src/openfeature/flagging_provider.js +32 -16
  534. package/packages/dd-trace/src/openfeature/index.js +0 -2
  535. package/packages/dd-trace/src/openfeature/noop.js +41 -64
  536. package/packages/dd-trace/src/openfeature/register.js +35 -0
  537. package/packages/dd-trace/src/openfeature/remote_config.js +16 -14
  538. package/packages/dd-trace/src/openfeature/require-provider.js +18 -0
  539. package/packages/dd-trace/src/openfeature/span-enrichment-hook.js +143 -0
  540. package/packages/dd-trace/src/openfeature/span-enrichment.js +149 -0
  541. package/packages/dd-trace/src/openfeature/writers/base.js +3 -11
  542. package/packages/dd-trace/src/openfeature/writers/exposures.js +82 -70
  543. package/packages/dd-trace/src/openfeature/writers/util.js +1 -2
  544. package/packages/dd-trace/src/opentelemetry/active-span-proxy.js +42 -0
  545. package/packages/dd-trace/src/opentelemetry/bridge-span-base.js +107 -0
  546. package/packages/dd-trace/src/opentelemetry/context_manager.js +27 -13
  547. package/packages/dd-trace/src/opentelemetry/logs/index.js +6 -6
  548. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +3 -2
  549. package/packages/dd-trace/src/opentelemetry/metrics/index.js +61 -12
  550. package/packages/dd-trace/src/opentelemetry/metrics/instruments.js +28 -14
  551. package/packages/dd-trace/src/opentelemetry/metrics/meter.js +7 -10
  552. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +3 -2
  553. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +40 -0
  554. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_transformer.js +169 -0
  555. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +99 -5
  556. package/packages/dd-trace/src/opentelemetry/metrics/time.js +19 -0
  557. package/packages/dd-trace/src/opentelemetry/otlp/common.proto +2 -2
  558. package/packages/dd-trace/src/opentelemetry/otlp/logs.proto +1 -1
  559. package/packages/dd-trace/src/opentelemetry/otlp/logs_service.proto +1 -1
  560. package/packages/dd-trace/src/opentelemetry/otlp/metrics.proto +1 -1
  561. package/packages/dd-trace/src/opentelemetry/otlp/metrics_service.proto +1 -1
  562. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +56 -82
  563. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +1 -2
  564. package/packages/dd-trace/src/opentelemetry/otlp/protobuf_loader.js +14 -2
  565. package/packages/dd-trace/src/opentelemetry/otlp/trace.proto +358 -0
  566. package/packages/dd-trace/src/opentelemetry/otlp/trace_service.proto +78 -0
  567. package/packages/dd-trace/src/opentelemetry/span-ending-hook.js +10 -0
  568. package/packages/dd-trace/src/opentelemetry/span-helpers.js +325 -0
  569. package/packages/dd-trace/src/opentelemetry/span.js +64 -109
  570. package/packages/dd-trace/src/opentelemetry/span_context.js +1 -0
  571. package/packages/dd-trace/src/opentelemetry/span_processor.js +7 -5
  572. package/packages/dd-trace/src/opentelemetry/trace/index.js +75 -0
  573. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +75 -0
  574. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +375 -0
  575. package/packages/dd-trace/src/opentelemetry/tracer.js +20 -69
  576. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +33 -17
  577. package/packages/dd-trace/src/opentracing/propagation/log.js +28 -8
  578. package/packages/dd-trace/src/opentracing/propagation/text_map.js +278 -148
  579. package/packages/dd-trace/src/opentracing/propagation/text_map_dsm.js +11 -11
  580. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +98 -32
  581. package/packages/dd-trace/src/opentracing/span.js +127 -73
  582. package/packages/dd-trace/src/opentracing/span_context.js +68 -3
  583. package/packages/dd-trace/src/opentracing/tracer.js +46 -19
  584. package/packages/dd-trace/src/payload-tagging/config/index.js +2 -2
  585. package/packages/dd-trace/src/plugin_manager.js +36 -14
  586. package/packages/dd-trace/src/plugins/apollo.js +3 -1
  587. package/packages/dd-trace/src/plugins/ci_plugin.js +407 -91
  588. package/packages/dd-trace/src/plugins/database.js +61 -18
  589. package/packages/dd-trace/src/plugins/index.js +14 -0
  590. package/packages/dd-trace/src/plugins/log_injection.js +56 -0
  591. package/packages/dd-trace/src/plugins/log_plugin.js +4 -44
  592. package/packages/dd-trace/src/plugins/outbound.js +1 -1
  593. package/packages/dd-trace/src/plugins/plugin.js +19 -28
  594. package/packages/dd-trace/src/plugins/storage.js +2 -2
  595. package/packages/dd-trace/src/plugins/tracing.js +70 -13
  596. package/packages/dd-trace/src/plugins/util/ci.js +127 -40
  597. package/packages/dd-trace/src/plugins/util/git-cache.js +23 -23
  598. package/packages/dd-trace/src/plugins/util/git.js +6 -3
  599. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +276 -0
  600. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +29 -5
  601. package/packages/dd-trace/src/plugins/util/llm.js +6 -1
  602. package/packages/dd-trace/src/plugins/util/stacktrace.js +2 -2
  603. package/packages/dd-trace/src/plugins/util/test.js +950 -69
  604. package/packages/dd-trace/src/plugins/util/url.js +71 -5
  605. package/packages/dd-trace/src/plugins/util/user-provided-git.js +18 -16
  606. package/packages/dd-trace/src/plugins/util/web.js +116 -180
  607. package/packages/dd-trace/src/priority_sampler.js +12 -21
  608. package/packages/dd-trace/src/profiling/config.js +132 -212
  609. package/packages/dd-trace/src/profiling/constants.js +4 -7
  610. package/packages/dd-trace/src/profiling/exporter_cli.js +10 -10
  611. package/packages/dd-trace/src/profiling/exporters/agent.js +61 -28
  612. package/packages/dd-trace/src/profiling/exporters/event_serializer.js +45 -14
  613. package/packages/dd-trace/src/profiling/exporters/file.js +16 -5
  614. package/packages/dd-trace/src/profiling/oom.js +71 -0
  615. package/packages/dd-trace/src/profiling/profiler.js +84 -105
  616. package/packages/dd-trace/src/profiling/profilers/event_plugins/crypto.js +32 -0
  617. package/packages/dd-trace/src/profiling/profilers/event_plugins/zlib.js +19 -0
  618. package/packages/dd-trace/src/profiling/profilers/events.js +57 -13
  619. package/packages/dd-trace/src/profiling/profilers/space.js +27 -16
  620. package/packages/dd-trace/src/profiling/profilers/wall.js +49 -35
  621. package/packages/dd-trace/src/profiling/ssi-heuristics.js +3 -3
  622. package/packages/dd-trace/src/propagation-hash/index.js +1 -1
  623. package/packages/dd-trace/src/proxy.js +128 -37
  624. package/packages/dd-trace/src/rate_limiter.js +1 -1
  625. package/packages/dd-trace/src/remote_config/index.js +6 -5
  626. package/packages/dd-trace/src/remote_config/scheduler.js +1 -1
  627. package/packages/dd-trace/src/ritm.js +6 -3
  628. package/packages/dd-trace/src/runtime_metrics/client.js +30 -0
  629. package/packages/dd-trace/src/runtime_metrics/index.js +14 -4
  630. package/packages/dd-trace/src/runtime_metrics/otlp_runtime_metrics.js +284 -0
  631. package/packages/dd-trace/src/runtime_metrics/runtime_metrics.js +42 -41
  632. package/packages/dd-trace/src/sampling_rule.js +7 -7
  633. package/packages/dd-trace/src/scope.js +10 -15
  634. package/packages/dd-trace/src/serverless.js +6 -7
  635. package/packages/dd-trace/src/service-naming/extra-services.js +14 -0
  636. package/packages/dd-trace/src/service-naming/index.js +1 -1
  637. package/packages/dd-trace/src/service-naming/schemas/definition.js +4 -1
  638. package/packages/dd-trace/src/service-naming/schemas/util.js +48 -3
  639. package/packages/dd-trace/src/service-naming/schemas/v0/graphql.js +6 -0
  640. package/packages/dd-trace/src/service-naming/schemas/v0/messaging.js +61 -2
  641. package/packages/dd-trace/src/service-naming/schemas/v0/serverless.js +12 -0
  642. package/packages/dd-trace/src/service-naming/schemas/v0/storage.js +60 -0
  643. package/packages/dd-trace/src/service-naming/schemas/v0/web.js +25 -1
  644. package/packages/dd-trace/src/service-naming/schemas/v0/websocket.js +5 -0
  645. package/packages/dd-trace/src/service-naming/schemas/v1/graphql.js +8 -0
  646. package/packages/dd-trace/src/service-naming/schemas/v1/messaging.js +32 -0
  647. package/packages/dd-trace/src/service-naming/schemas/v1/serverless.js +12 -0
  648. package/packages/dd-trace/src/service-naming/schemas/v1/storage.js +17 -0
  649. package/packages/dd-trace/src/service-naming/schemas/v1/web.js +23 -3
  650. package/packages/dd-trace/src/service-naming/schemas/v1/websocket.js +6 -0
  651. package/packages/dd-trace/src/service-naming/source-resolver.js +50 -0
  652. package/packages/dd-trace/src/span_format.js +269 -81
  653. package/packages/dd-trace/src/span_processor.js +18 -13
  654. package/packages/dd-trace/src/span_stats.js +101 -79
  655. package/packages/dd-trace/src/spanleak.js +1 -2
  656. package/packages/dd-trace/src/standalone/index.js +0 -36
  657. package/packages/dd-trace/src/startup-log.js +3 -3
  658. package/packages/dd-trace/src/tagger.js +2 -4
  659. package/packages/dd-trace/src/telemetry/dependencies.js +2 -2
  660. package/packages/dd-trace/src/telemetry/endpoints.js +7 -5
  661. package/packages/dd-trace/src/telemetry/index.js +2 -2
  662. package/packages/dd-trace/src/telemetry/logs/index.js +1 -1
  663. package/packages/dd-trace/src/telemetry/send-data.js +22 -22
  664. package/packages/dd-trace/src/telemetry/session-propagation.js +1 -1
  665. package/packages/dd-trace/src/telemetry/telemetry.js +16 -14
  666. package/packages/dd-trace/src/tracer.js +23 -9
  667. package/packages/dd-trace/src/tracer_metadata.js +1 -1
  668. package/packages/dd-trace/src/util.js +57 -0
  669. package/register.js +58 -1
  670. package/vendor/dist/@apm-js-collab/code-transformer/index.js +94 -42
  671. package/vendor/dist/@datadog/sketches-js/LICENSE +10 -36
  672. package/vendor/dist/@datadog/sketches-js/index.js +1 -1
  673. package/vendor/dist/pprof-format/index.js +1 -1
  674. package/vendor/dist/protobufjs/index.js +1 -1
  675. package/vendor/dist/protobufjs/minimal/index.js +1 -1
  676. package/vendor/dist/shell-quote/index.js +1 -1
  677. package/packages/datadog-plugin-graphql/src/resolve.js +0 -178
  678. package/packages/dd-trace/src/agent/url.js +0 -28
  679. package/packages/dd-trace/src/appsec/api_security_sampler.js +0 -117
  680. package/packages/dd-trace/src/lambda/runtime/ritm.js +0 -133
  681. package/packages/dd-trace/src/log/utils.js +0 -16
  682. package/packages/dd-trace/src/msgpack/encoder.js +0 -308
  683. package/packages/dd-trace/src/plugins/structured_log_plugin.js +0 -9
  684. package/scripts/preinstall.js +0 -34
  685. package/vendor/dist/ignore/LICENSE +0 -21
  686. package/vendor/dist/ignore/index.js +0 -1
  687. package/vendor/dist/opentracing/LICENSE +0 -201
  688. package/vendor/dist/opentracing/binary_carrier.d.ts +0 -11
  689. package/vendor/dist/opentracing/constants.d.ts +0 -61
  690. package/vendor/dist/opentracing/examples/demo/demo.d.ts +0 -2
  691. package/vendor/dist/opentracing/ext/tags.d.ts +0 -90
  692. package/vendor/dist/opentracing/functions.d.ts +0 -20
  693. package/vendor/dist/opentracing/global_tracer.d.ts +0 -14
  694. package/vendor/dist/opentracing/index.d.ts +0 -12
  695. package/vendor/dist/opentracing/index.js +0 -1
  696. package/vendor/dist/opentracing/mock_tracer/index.d.ts +0 -5
  697. package/vendor/dist/opentracing/mock_tracer/mock_context.d.ts +0 -13
  698. package/vendor/dist/opentracing/mock_tracer/mock_report.d.ts +0 -16
  699. package/vendor/dist/opentracing/mock_tracer/mock_span.d.ts +0 -50
  700. package/vendor/dist/opentracing/mock_tracer/mock_tracer.d.ts +0 -26
  701. package/vendor/dist/opentracing/noop.d.ts +0 -8
  702. package/vendor/dist/opentracing/reference.d.ts +0 -33
  703. package/vendor/dist/opentracing/span.d.ts +0 -147
  704. package/vendor/dist/opentracing/span_context.d.ts +0 -26
  705. package/vendor/dist/opentracing/test/api_compatibility.d.ts +0 -16
  706. package/vendor/dist/opentracing/test/mocktracer_implemenation.d.ts +0 -3
  707. package/vendor/dist/opentracing/test/noop_implementation.d.ts +0 -4
  708. package/vendor/dist/opentracing/test/opentracing_api.d.ts +0 -3
  709. package/vendor/dist/opentracing/test/unittest.d.ts +0 -2
  710. package/vendor/dist/opentracing/tracer.d.ts +0 -127
  711. package/vendor/dist/path-to-regexp/LICENSE +0 -21
  712. package/vendor/dist/path-to-regexp/index.js +0 -1
@@ -3,14 +3,21 @@
3
3
  // Capture real timers at module load time, before any test can install fake timers.
4
4
  const realSetTimeout = setTimeout
5
5
 
6
+ const { readFileSync } = require('node:fs')
7
+ const { builtinModules, createRequire } = require('node:module')
6
8
  const path = require('path')
9
+ const satisfies = require('../../../vendor/dist/semifies')
10
+ const { DD_MAJOR } = require('../../../version')
7
11
  const shimmer = require('../../datadog-shimmer')
12
+ const { getEnvironmentVariable } = require('../../dd-trace/src/config/helper')
8
13
  const log = require('../../dd-trace/src/log')
9
14
  const {
10
- getCoveredFilenamesFromCoverage,
15
+ getCoveredFilesFromCoverage,
16
+ getExecutableFilesFromCoverage,
11
17
  JEST_WORKER_TRACE_PAYLOAD_CODE,
12
18
  JEST_WORKER_COVERAGE_PAYLOAD_CODE,
13
19
  JEST_WORKER_TELEMETRY_PAYLOAD_CODE,
20
+ JEST_WORKER_QUARANTINE_PAYLOAD_CODE,
14
21
  getTestLineStart,
15
22
  getTestSuitePath,
16
23
  getTestParametersString,
@@ -20,14 +27,25 @@ const {
20
27
  isModifiedTest,
21
28
  DYNAMIC_NAME_RE,
22
29
  collectDynamicNamesFromTraces,
30
+ recordAttemptToFixExecution,
31
+ logAttemptToFixTestExecution,
32
+ logTestOptimizationSummary,
33
+ getEfdRetryCount,
34
+ getTestCoverageLinesPercentage,
35
+ applySkippedCoverageToCoverage,
36
+ getTestOptimizationRequestResults,
23
37
  } = require('../../dd-trace/src/plugins/util/test')
24
38
  const {
25
- SEED_SUFFIX_RE,
26
39
  getFormattedJestTestParameters,
27
40
  getJestTestName,
41
+ getRawJestTestName,
28
42
  getJestSuitesToRun,
29
- getEfdRetryCount,
43
+ removeSeedSuffixFromTestName,
30
44
  } = require('../../datadog-plugin-jest/src/util')
45
+ const {
46
+ addCoverageBackfillUntestedFiles,
47
+ getCoverageBackfillFiles,
48
+ } = require('./jest/coverage-backfill')
31
49
  const { addHook, channel } = require('./helpers/instrument')
32
50
 
33
51
  const testSessionStartCh = channel('ci:jest:session:start')
@@ -68,16 +86,25 @@ const CHILD_MESSAGE_CALL = 1
68
86
 
69
87
  // Maximum time we'll wait for the tracer to flush
70
88
  const FLUSH_TIMEOUT = 10_000
89
+ const JEST_SESSION_STATE = Symbol.for('dd-trace:jest:session')
90
+ const JEST_BAIL_REPORTER_PATH = require.resolve('./jest/bail-reporter')
91
+ const DD_JEST_HANDLE_TEST_EVENT_WRAPPED = Symbol('dd-trace:jest:handle-test-event-wrapped')
92
+ const DD_JEST_HANDLE_TEST_EVENT_DATADOG = Symbol('dd-trace:jest:handle-test-event-datadog')
93
+ const DD_JEST_CONCURRENT_TEST_ORIGINAL = Symbol('dd-trace:jest:concurrent-test-original')
94
+ const isJestWorker = !!getEnvironmentVariable('JEST_WORKER_ID')
95
+ const jestSessionState = globalThis[JEST_SESSION_STATE] || (globalThis[JEST_SESSION_STATE] = {})
71
96
 
72
97
  // https://github.com/jestjs/jest/blob/41f842a46bb2691f828c3a5f27fc1d6290495b82/packages/jest-circus/src/types.ts#L9C8-L9C54
73
98
  const RETRY_TIMES = Symbol.for('RETRY_TIMES')
74
99
 
75
100
  let skippableSuites = []
101
+ let skippableSuitesCoverage = {}
102
+ let skippedSuitesCoverage = {}
76
103
  let knownTests = {}
77
104
  let isCodeCoverageEnabled = false
78
- let isCodeCoverageEnabledBecauseOfUs = false
105
+ let isCoverageReportUploadEnabled = false
106
+ let isItrEnabled = false
79
107
  let isSuitesSkippingEnabled = false
80
- let isKeepingCoverageConfiguration = false
81
108
  let isUserCodeCoverageEnabled = false
82
109
  let isSuitesSkipped = false
83
110
  let numSkippedSuites = 0
@@ -95,10 +122,21 @@ let testManagementTests = {}
95
122
  let testManagementAttemptToFixRetries = 0
96
123
  let isImpactedTestsEnabled = false
97
124
  let modifiedFiles = {}
125
+ let repositoryRoot
126
+ let lastCoverageMap
127
+ let lastCoverageMapRootDir
128
+ let coverageBackfillContexts
129
+ let coverageBackfillFiles
130
+ let coverageReporterClass
131
+ let coverageReporterRequire
132
+ let activeTestSuiteAbsolutePath
133
+ let isConsoleErrorWrapped = false
98
134
 
99
135
  const testContexts = new WeakMap()
100
136
  const originalTestFns = new WeakMap()
101
137
  const originalHookFns = new WeakMap()
138
+ const concurrentHookContextQueues = new WeakMap()
139
+ const concurrentHookFns = new WeakMap()
102
140
  const retriedTestsToNumAttempts = new Map()
103
141
  const newTestsTestStatuses = new Map()
104
142
  const attemptToFixRetriedTestsStatuses = new Map()
@@ -106,6 +144,7 @@ const wrappedWorkerChannels = new WeakMap()
106
144
  // New tests whose names contain likely dynamic data (timestamps, UUIDs, etc.)
107
145
  // Populated in-process for runInBand, and via worker-report:trace for parallel mode.
108
146
  const newTestsWithDynamicNames = new Set()
147
+ const loggedAttemptToFixTests = new Set()
109
148
  const testSuiteMockedFiles = new Map()
110
149
  const testsToBeRetried = new Set()
111
150
  // Per-test: how many EFD retries were determined after the first execution.
@@ -116,12 +155,81 @@ const efdSlowAbortedTests = new Set()
116
155
  const efdNewTestCandidates = new Set()
117
156
  // Tests that are genuinely new (not in known tests list).
118
157
  const newTests = new Set()
119
- const testSuiteAbsolutePathsWithFastCheck = new Set()
120
158
  const testSuiteJestObjects = new Map()
159
+ const testSuiteDatadogEnvironments = new Map()
160
+ const wrappedJestGlobals = new WeakSet()
161
+ const wrappedJestObjects = new WeakSet()
162
+ const wrappedWorkerInitializers = new WeakSet()
163
+ const publishedRuntimeReferenceErrors = new WeakMap()
164
+ const wrappedCoverageReporters = new WeakSet()
165
+ const coverageReporterRequires = new WeakMap()
166
+ const handledJestEvents = new WeakSet()
167
+
168
+ /**
169
+ * @typedef {object} ConcurrentTestOptions
170
+ * @property {(...args: unknown[]) => unknown} [concurrentTest]
171
+ * @property {unknown} [concurrentTestThisArg]
172
+ * @property {boolean} [isAttemptToFixRetry]
173
+ * @property {boolean} [isEfdRetry]
174
+ * @property {boolean} [isModified]
175
+ * @property {(...args: unknown[]) => unknown} [serialTest]
176
+ * @property {unknown} [serialTestThisArg]
177
+ * @property {(...args: unknown[]) => unknown} [sourceTestFn]
178
+ * @property {string} [testParameters]
179
+ */
121
180
 
122
- const BREAKPOINT_HIT_GRACE_PERIOD_MS = 200
123
181
  const ATR_RETRY_SUPPRESSION_FLAG = '_ddDisableAtrRetry'
182
+ const MINIMUM_JEST_VERSION = DD_MAJOR >= 6 ? '>=28.0.0' : '>=24.8.0'
183
+ const MINIMUM_JEST_VERSION_BEFORE_30 = DD_MAJOR >= 6 ? '>=28.0.0 <30.0.0' : '>=24.8.0 <30.0.0'
184
+ const MINIMUM_JEST_WORKER_VERSION_BEFORE_30 = DD_MAJOR >= 6 ? '>=28.0.0 <30.0.0' : '>=24.9.0 <30.0.0'
185
+ const MINIMUM_JEST_CONFIG_ASYNC_VERSION = DD_MAJOR >= 6 ? '>=28.0.0' : '>=25.1.0'
186
+ const MINIMUM_JEST_TEST_SCHEDULER_VERSION = DD_MAJOR >= 6 ? '>=28.0.0' : '>=27.0.0'
187
+ const MINIMUM_JEST_COVERAGE_BACKFILL_VERSION = '>=28.0.0'
124
188
  const atrSuppressedErrors = new Map()
189
+ let hasWarnedDeprecatedJestVersion = false
190
+ let isJestCoverageBackfillSupported = false
191
+ let hasFinishedTestSession = false
192
+ let jestEachBind
193
+
194
+ // Track quarantined tests whose errors were suppressed, keyed by "suite › testName"
195
+ const quarantinedFailingTests = new Set()
196
+
197
+ function getJestRepositoryRoot (readConfigsResult) {
198
+ const configuredRepositoryRoot = readConfigsResult.configs
199
+ ?.find(config => config.testEnvironmentOptions?._ddRepositoryRoot)
200
+ ?.testEnvironmentOptions._ddRepositoryRoot
201
+
202
+ return configuredRepositoryRoot || process.cwd()
203
+ }
204
+
205
+ /**
206
+ * Sends suppressed quarantine test names from a worker process to the main process.
207
+ * Supports both child_process (process.send) and worker_threads (parentPort.postMessage).
208
+ * Returns true if the data was sent (worker mode), false if in main process (runInBand).
209
+ *
210
+ * @param {string[]} testNames
211
+ * @returns {boolean}
212
+ */
213
+ function sendQuarantineInfoToMainProcess (testNames) {
214
+ const payload = [JEST_WORKER_QUARANTINE_PAYLOAD_CODE, JSON.stringify(testNames)]
215
+
216
+ if (process.send) {
217
+ process.send(payload)
218
+ return true
219
+ }
220
+
221
+ try {
222
+ const { isMainThread, parentPort } = require('node:worker_threads')
223
+ if (!isMainThread && parentPort) {
224
+ parentPort.postMessage(payload)
225
+ return true
226
+ }
227
+ } catch {
228
+ // Not in a worker context
229
+ }
230
+
231
+ return false
232
+ }
125
233
 
126
234
  // based on https://github.com/facebook/jest/blob/main/packages/jest-circus/src/formatNodeAssertErrors.ts#L41
127
235
  function formatJestError (errors) {
@@ -140,6 +248,20 @@ function formatJestError (errors) {
140
248
  return error
141
249
  }
142
250
 
251
+ function warnDeprecatedJestVersion (frameworkVersion) {
252
+ if (DD_MAJOR >= 6 || hasWarnedDeprecatedJestVersion || !frameworkVersion ||
253
+ !satisfies(frameworkVersion, '<28.0.0')) {
254
+ return
255
+ }
256
+
257
+ hasWarnedDeprecatedJestVersion = true
258
+ // eslint-disable-next-line no-console
259
+ console.warn(
260
+ 'dd-trace support for Jest<28.0.0 is deprecated and will be removed in dd-trace v6. ' +
261
+ 'Please upgrade Jest to >=28.0.0.'
262
+ )
263
+ }
264
+
143
265
  function getTestEnvironmentOptions (config) {
144
266
  if (config.projectConfig && config.projectConfig.testEnvironmentOptions) { // newer versions
145
267
  return config.projectConfig.testEnvironmentOptions
@@ -160,64 +282,183 @@ function getTestStats (testStatuses) {
160
282
  }
161
283
 
162
284
  /**
163
- * @param {string[]} efdNames
164
- * @param {string[]} quarantineNames
165
- * @param {number} totalCount
166
- */
167
- /**
168
- * Renders a truncated bullet list from an array of items.
285
+ * Formats the ignored-failure section for the Test Optimization summary.
169
286
  *
170
- * @param {Array<{ text: string, suffix?: string }>} items
287
+ * @param {{ efdNames: string[], quarantineNames: string[], totalCount: number } | undefined} ignoredFailures
171
288
  * @returns {string}
172
289
  */
173
- function formatList (items) {
290
+ function formatIgnoredFailuresSummary (ignoredFailures) {
291
+ if (!ignoredFailures) return ''
292
+
293
+ const items = []
294
+
295
+ for (const n of ignoredFailures.efdNames) {
296
+ items.push({ text: n, suffix: 'Early Flake Detection' })
297
+ }
298
+ for (const n of ignoredFailures.quarantineNames) {
299
+ items.push({ text: n, suffix: 'Quarantine' })
300
+ }
301
+
302
+ if (items.length === 0 || ignoredFailures.totalCount <= 0) return ''
303
+
174
304
  const shown = items.slice(0, MAX_IGNORED_TEST_NAMES)
175
305
  const more = items.length - shown.length
176
306
  const moreSuffix = more > 0 ? `\n ... and ${more} more` : ''
177
- return shown.map(({ text, suffix }) => ` • ${text}${suffix ? ` (${suffix})` : ''}`).join('\n') + moreSuffix
307
+ const formattedItems = shown
308
+ .map(({ text, suffix }) => ` • ${text}${suffix ? ` (${suffix})` : ''}`)
309
+ .join('\n') + moreSuffix
310
+
311
+ return `${ignoredFailures.totalCount} test failure(s) were ignored. Exit code set to 0.\n\n${formattedItems}`
178
312
  }
179
313
 
180
314
  /**
181
- * Logs a single "Datadog Test Optimization" summary at session end,
182
- * combining all relevant sections (ignored failures, dynamic names).
315
+ * Logs a single "Datadog Test Optimization" summary at session end.
183
316
  *
184
317
  * @param {{ efdNames: string[], quarantineNames: string[], totalCount: number } | undefined} ignoredFailures
185
318
  */
186
- function logSessionSummary (ignoredFailures) {
187
- const sections = []
319
+ function logSessionSummary (ignoredFailures, attemptToFixExecutions) {
320
+ logTestOptimizationSummary({
321
+ attemptToFixExecutions,
322
+ extraSections: [formatIgnoredFailuresSummary(ignoredFailures)],
323
+ newTestsWithDynamicNames,
324
+ })
325
+ loggedAttemptToFixTests.clear()
326
+ }
327
+
328
+ function getTestStatusFromJestResult (status) {
329
+ if (status === 'failed') return 'fail'
330
+ if (status === 'passed') return 'pass'
331
+ }
188
332
 
189
- if (ignoredFailures) {
190
- const items = []
191
- for (const n of ignoredFailures.efdNames) {
192
- items.push({ text: n, suffix: 'Early Flake Detection' })
333
+ function getAttemptToFixExecutionsFromJestResults (result) {
334
+ const executions = new Map()
335
+ const rootDir = result.globalConfig?.rootDir || process.cwd()
336
+
337
+ for (const { testResults, testFilePath } of result.results.testResults) {
338
+ const testSuite = getTestSuitePath(testFilePath, rootDir)
339
+ const testManagementTestsForSuite = testManagementTests
340
+ ?.jest
341
+ ?.suites
342
+ ?.[testSuite]
343
+ ?.tests
344
+ if (!testManagementTestsForSuite) continue
345
+
346
+ for (const { fullName, status } of testResults) {
347
+ const testName = removeSeedSuffixFromTestName(fullName)
348
+ const testStatus = getTestStatusFromJestResult(status)
349
+ if (!testStatus) continue
350
+
351
+ const testManagementTest = testManagementTestsForSuite[testName]?.properties
352
+ if (!testManagementTest?.attempt_to_fix) continue
353
+
354
+ recordAttemptToFixExecution(executions, {
355
+ testSuite,
356
+ testName,
357
+ status: testStatus,
358
+ isDisabled: testManagementTest.disabled,
359
+ isQuarantined: testManagementTest.quarantined,
360
+ })
193
361
  }
194
- for (const n of ignoredFailures.quarantineNames) {
195
- items.push({ text: n, suffix: 'Quarantine' })
362
+ }
363
+
364
+ return executions
365
+ }
366
+
367
+ function wrapConsoleErrorForJestReferenceErrors () {
368
+ if (isConsoleErrorWrapped) return
369
+
370
+ isConsoleErrorWrapped = true
371
+ // eslint-disable-next-line no-console
372
+ const originalConsoleError = console.error
373
+ // eslint-disable-next-line no-console
374
+ console.error = function () {
375
+ const [message] = arguments
376
+ if (
377
+ typeof message === 'string' &&
378
+ message.includes('Jest environment has been torn down') &&
379
+ activeTestSuiteAbsolutePath
380
+ ) {
381
+ publishRuntimeReferenceError({ _testPath: activeTestSuiteAbsolutePath }, message)
196
382
  }
197
- sections.push(
198
- `${ignoredFailures.totalCount} test failure(s) were ignored. Exit code set to 0.\n\n` +
199
- formatList(items)
200
- )
383
+ return originalConsoleError.apply(this, arguments)
384
+ }
385
+ }
386
+
387
+ function isDatadogJestEventHandled (event) {
388
+ return event && typeof event === 'object' && handledJestEvents.has(event)
389
+ }
390
+
391
+ function markDatadogJestEventHandled (event) {
392
+ if (event && typeof event === 'object') {
393
+ handledJestEvents.add(event)
201
394
  }
395
+ }
202
396
 
203
- if (newTestsWithDynamicNames.size > 0) {
204
- const items = [...newTestsWithDynamicNames].map(name => ({ text: name }))
205
- sections.push(
206
- `${newTestsWithDynamicNames.size} test(s) detected as new but their names contain ` +
207
- 'dynamic data (timestamps, UUIDs, etc.).\n' +
208
- 'Tests with changing names are always treated as new on every run, ' +
209
- 'causing unnecessary Early Flake Detection retries and preventing correct new test detection.\n' +
210
- 'Consider using stable, deterministic test names.\n\n' +
211
- formatList(items)
212
- )
213
- newTestsWithDynamicNames.clear()
397
+ /**
398
+ * Gets the original Jest concurrent registration function behind a Datadog wrapper.
399
+ *
400
+ * @param {(...args: unknown[]) => unknown} concurrentTest
401
+ * @returns {(...args: unknown[]) => unknown}
402
+ */
403
+ function getOriginalConcurrentTest (concurrentTest) {
404
+ return concurrentTest[DD_JEST_CONCURRENT_TEST_ORIGINAL] || concurrentTest
405
+ }
406
+
407
+ /**
408
+ * Marks a Datadog concurrent registration wrapper with its original Jest function.
409
+ *
410
+ * @param {(...args: unknown[]) => unknown} wrappedConcurrentTest
411
+ * @param {(...args: unknown[]) => unknown} originalConcurrentTest
412
+ * @returns {void}
413
+ */
414
+ function setOriginalConcurrentTest (wrappedConcurrentTest, originalConcurrentTest) {
415
+ Object.defineProperty(wrappedConcurrentTest, DD_JEST_CONCURRENT_TEST_ORIGINAL, {
416
+ configurable: true,
417
+ value: originalConcurrentTest,
418
+ })
419
+ }
420
+
421
+ /**
422
+ * Wraps a custom Jest environment handler so Datadog still observes events even
423
+ * when the custom environment does not call `super.handleTestEvent`.
424
+ *
425
+ * @param {(event: object, state: object) => Promise<void>|void} handleTestEvent
426
+ * @param {(event: object, state: object) => Promise<void>|void} datadogHandleTestEvent
427
+ * @returns {(event: object, state: object) => Promise<void>|void}
428
+ */
429
+ function getWrappedCustomHandleTestEvent (handleTestEvent, datadogHandleTestEvent) {
430
+ if (
431
+ !handleTestEvent ||
432
+ handleTestEvent === datadogHandleTestEvent ||
433
+ handleTestEvent[DD_JEST_HANDLE_TEST_EVENT_WRAPPED]
434
+ ) {
435
+ return handleTestEvent || datadogHandleTestEvent
214
436
  }
215
437
 
216
- if (sections.length === 0) return
438
+ const wrappedHandleTestEvent = function (event, state) {
439
+ const result = handleTestEvent.call(this, event, state)
440
+ const runDatadogHandler = value => {
441
+ if (isDatadogJestEventHandled(event)) return value
442
+
443
+ const datadogResult = datadogHandleTestEvent.call(this, event, state)
444
+ if (typeof datadogResult?.then === 'function') {
445
+ return datadogResult.then(() => value)
446
+ }
447
+ return value
448
+ }
449
+
450
+ if (event.name === 'add_test') {
451
+ runDatadogHandler(result)
452
+ return result
453
+ }
217
454
 
218
- const line = '-'.repeat(50)
219
- // eslint-disable-next-line no-console -- Intentional user-facing session summary
220
- console.warn(`\n${line}\nDatadog Test Optimization\n${line}\n${sections.join('\n\n')}\n`)
455
+ if (typeof result?.then === 'function') {
456
+ return result.then(runDatadogHandler)
457
+ }
458
+ return runDatadogHandler(result)
459
+ }
460
+ wrappedHandleTestEvent[DD_JEST_HANDLE_TEST_EVENT_WRAPPED] = true
461
+ return wrappedHandleTestEvent
221
462
  }
222
463
 
223
464
  function getWrappedEnvironment (BaseEnvironment, jestVersion) {
@@ -226,16 +467,20 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
226
467
  super(config, context)
227
468
  const rootDir = config.globalConfig ? config.globalConfig.rootDir : config.rootDir
228
469
  this.rootDir = rootDir
229
- this.testSuite = getTestSuitePath(context.testPath, rootDir)
230
470
  this.nameToParams = {}
231
471
  this.global._ddtrace = global._ddtrace
232
472
  this.hasSnapshotTests = undefined
233
473
  this.testSuiteAbsolutePath = context.testPath
474
+ activeTestSuiteAbsolutePath = this.testSuiteAbsolutePath
475
+ testSuiteDatadogEnvironments.set(this.testSuiteAbsolutePath, this)
476
+ wrapConsoleErrorForJestReferenceErrors()
477
+ this.globalConfig = config.globalConfig
234
478
 
235
479
  this.displayName = config.projectConfig?.displayName?.name || config.displayName
236
480
  this.testEnvironmentOptions = getTestEnvironmentOptions(config)
237
481
 
238
482
  const repositoryRoot = this.testEnvironmentOptions._ddRepositoryRoot
483
+ this.testSuite = getTestSuitePath(context.testPath, rootDir)
239
484
 
240
485
  // TODO: could we grab testPath from `this.getVmContext().expect.getState()` instead?
241
486
  // so we don't rely on context being passed (some custom test environment do not pass it)
@@ -251,6 +496,12 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
251
496
  this.isKnownTestsEnabled = this.testEnvironmentOptions._ddIsKnownTestsEnabled
252
497
  this.isTestManagementTestsEnabled = this.testEnvironmentOptions._ddIsTestManagementTestsEnabled
253
498
  this.isImpactedTestsEnabled = this.testEnvironmentOptions._ddIsImpactedTestsEnabled
499
+ this.hasConcurrentTests = false
500
+ this.concurrentTestContexts = new Map()
501
+ this.concurrentTestStates = new WeakMap()
502
+ this.concurrentTestSourceFns = new WeakMap()
503
+ this.wrappedConcurrentTestFunctions = new WeakSet()
504
+ this.jestEachBind = undefined
254
505
 
255
506
  if (this.isKnownTestsEnabled) {
256
507
  earlyFlakeDetectionSlowTestRetries = this.testEnvironmentOptions._ddEarlyFlakeDetectionSlowTestRetries ?? {}
@@ -298,6 +549,390 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
298
549
  this.isImpactedTestsEnabled = false
299
550
  }
300
551
  }
552
+
553
+ this[DD_JEST_HANDLE_TEST_EVENT_DATADOG] = DatadogEnvironment.prototype.handleTestEvent
554
+ this.wrapCustomHandleTestEvent(DatadogEnvironment.prototype.handleTestEvent)
555
+ }
556
+
557
+ /**
558
+ * Rechecks custom `handleTestEvent` implementations after subclass instance fields
559
+ * and constructors have run.
560
+ *
561
+ * @returns {Promise<void>|void}
562
+ */
563
+ setup () {
564
+ this.wrapCustomHandleTestEvent(DatadogEnvironment.prototype.handleTestEvent)
565
+
566
+ if (super.setup) {
567
+ const result = super.setup()
568
+ if (typeof result?.then === 'function') {
569
+ return result.then(() => {
570
+ this.wrapCustomHandleTestEvent(DatadogEnvironment.prototype.handleTestEvent)
571
+ })
572
+ }
573
+ this.wrapCustomHandleTestEvent(DatadogEnvironment.prototype.handleTestEvent)
574
+ return result
575
+ }
576
+ }
577
+
578
+ /**
579
+ * Wraps Jest's concurrent test registration methods so eager concurrent bodies
580
+ * in older Jest versions execute inside their test span context.
581
+ *
582
+ * @param {object} state
583
+ * @returns {void}
584
+ */
585
+ wrapConcurrentTest (state) {
586
+ this.concurrentTestState = state
587
+ this.wrapConcurrentTestGlobals(this.global.test, state)
588
+ }
589
+
590
+ /**
591
+ * Wraps one Jest `test` function object's concurrent registration methods.
592
+ *
593
+ * @param {Function|undefined} test
594
+ * @param {object} state
595
+ * @returns {void}
596
+ */
597
+ wrapConcurrentTestGlobals (test, state) {
598
+ if (!state) return
599
+
600
+ const concurrentTest = test?.concurrent
601
+ if (typeof concurrentTest !== 'function') return
602
+
603
+ this.wrapConcurrentTestFunction(test, 'concurrent', state, test, test)
604
+ this.wrapConcurrentTestFunction(test.concurrent, 'only', state, test.only, test)
605
+ this.wrapConcurrentTestFunction(test.concurrent, 'failing', state, test.failing, test)
606
+ this.wrapConcurrentTestFunction(test.concurrent.only, 'failing', state, test.only?.failing, test.only)
607
+ }
608
+
609
+ /**
610
+ * Wraps one concurrent test function variant.
611
+ *
612
+ * @param {object} target
613
+ * @param {string} methodName
614
+ * @param {object} state
615
+ * @param {Function|undefined} serialTest
616
+ * @param {unknown} serialTestThisArg
617
+ * @returns {void}
618
+ */
619
+ wrapConcurrentTestFunction (target, methodName, state, serialTest, serialTestThisArg) {
620
+ let concurrentTest = target?.[methodName]
621
+ if (typeof concurrentTest !== 'function') return
622
+ if (this.wrappedConcurrentTestFunctions.has(concurrentTest)) return
623
+
624
+ const originalConcurrentTest = getOriginalConcurrentTest(concurrentTest)
625
+ if (originalConcurrentTest !== concurrentTest) {
626
+ target[methodName] = originalConcurrentTest
627
+ concurrentTest = originalConcurrentTest
628
+ }
629
+ if (typeof concurrentTest !== 'function') return
630
+
631
+ const environment = this
632
+ shimmer.wrap(target, methodName, concurrentTest => {
633
+ return function wrappedConcurrentTest (testName, testFn, ...args) {
634
+ if (typeof testFn !== 'function') {
635
+ return concurrentTest.apply(this, arguments)
636
+ }
637
+
638
+ environment.hasConcurrentTests = true
639
+ const asyncError = environment.isImpactedTestsEnabled
640
+ ? new Error('Datadog concurrent test registration')
641
+ : undefined
642
+ const wrappedTestFn = environment.createConcurrentTestFn(testName, testFn, asyncError, state, {
643
+ concurrentTest,
644
+ concurrentTestThisArg: this,
645
+ serialTest,
646
+ serialTestThisArg,
647
+ sourceTestFn: environment.concurrentTestSourceFns.get(testFn),
648
+ })
649
+ return concurrentTest.call(this, testName, wrappedTestFn, ...args)
650
+ }
651
+ })
652
+
653
+ const wrappedConcurrentTest = target[methodName]
654
+ setOriginalConcurrentTest(wrappedConcurrentTest, concurrentTest)
655
+ this.wrappedConcurrentTestFunctions.add(wrappedConcurrentTest)
656
+ this.bindConcurrentEach(wrappedConcurrentTest, methodName === 'failing')
657
+ }
658
+
659
+ /**
660
+ * Rebuilds a concurrent `.each` helper so each generated row calls the wrapped test function.
661
+ *
662
+ * @param {Function} concurrentTest
663
+ * @param {boolean} needsEachError
664
+ * @returns {void}
665
+ */
666
+ bindConcurrentEach (concurrentTest, needsEachError) {
667
+ if (typeof concurrentTest?.each !== 'function') return
668
+
669
+ const bind = this.getJestEachBind()
670
+ if (typeof bind !== 'function') return
671
+
672
+ const environment = this
673
+ concurrentTest.each = function wrappedConcurrentEach (...eachArgs) {
674
+ const testParameters = getFormattedJestTestParameters(eachArgs)
675
+ return function (...testArgs) {
676
+ let parameterIndex = 0
677
+ const sourceTestFn = testArgs[1]
678
+ const concurrentEachTest = function (testName, testFn, ...callArgs) {
679
+ const parameters = testParameters?.[parameterIndex++]
680
+ if (parameters !== undefined) {
681
+ environment.appendNameToParams(testName, parameters)
682
+ }
683
+ if (typeof testFn === 'function' && typeof sourceTestFn === 'function') {
684
+ environment.concurrentTestSourceFns.set(testFn, sourceTestFn)
685
+ }
686
+ return concurrentTest.call(this, testName, testFn, ...callArgs)
687
+ }
688
+ const eachBind = bind(concurrentEachTest, false, needsEachError).apply(this, eachArgs)
689
+ return eachBind.apply(this, testArgs)
690
+ }
691
+ }
692
+ }
693
+
694
+ /**
695
+ * Creates a Jest test function wrapper and stores its concurrent execution state.
696
+ *
697
+ * @param {string} testName
698
+ * @param {(...args: unknown[]) => unknown} testFn
699
+ * @param {Error|undefined} asyncError
700
+ * @param {object} state
701
+ * @param {ConcurrentTestOptions|undefined} options
702
+ * @returns {(...args: unknown[]) => unknown}
703
+ */
704
+ createConcurrentTestFn (testName, testFn, asyncError, state, options) {
705
+ const concurrentTestState = {
706
+ concurrentTest: options?.concurrentTest,
707
+ concurrentTestThisArg: options?.concurrentTestThisArg,
708
+ ctx: this.createConcurrentTestContext(testName, testFn, asyncError, state, options),
709
+ numExecutions: 0,
710
+ serialTest: options?.serialTest,
711
+ serialTestThisArg: options?.serialTestThisArg,
712
+ state,
713
+ testFn,
714
+ }
715
+ concurrentTestState.ctx.concurrentTestState = concurrentTestState
716
+ const environment = this
717
+ const wrappedTestFn = shimmer.wrapFunction(testFn, testFn => function (...args) {
718
+ return environment.runConcurrentTestFn(concurrentTestState, testFn, this, args)
719
+ })
720
+ this.concurrentTestStates.set(wrappedTestFn, concurrentTestState)
721
+ return wrappedTestFn
722
+ }
723
+
724
+ /**
725
+ * Gets Jest's table-driven test binder from the user's Jest installation.
726
+ *
727
+ * @returns {Function|undefined}
728
+ */
729
+ getJestEachBind () {
730
+ if (this.jestEachBind !== undefined) return this.jestEachBind
731
+
732
+ if (typeof jestEachBind === 'function') {
733
+ this.jestEachBind = jestEachBind
734
+ return this.jestEachBind
735
+ }
736
+
737
+ let jestEach
738
+ try {
739
+ jestEach = createRequire(path.join(this.rootDir, 'package.json'))('jest-each')
740
+ } catch {
741
+ try {
742
+ jestEach = createRequire(path.join(process.cwd(), 'package.json'))('jest-each')
743
+ } catch {
744
+ jestEach = undefined
745
+ }
746
+ }
747
+ this.jestEachBind = jestEach?.bind
748
+ return this.jestEachBind
749
+ }
750
+
751
+ /**
752
+ * Creates the context used to start and finish a concurrent test span.
753
+ *
754
+ * @param {string} testName
755
+ * @param {(...args: unknown[]) => unknown} testFn
756
+ * @param {Error|undefined} asyncError
757
+ * @param {object} state
758
+ * @param {ConcurrentTestOptions|undefined} options
759
+ * @returns {object}
760
+ */
761
+ createConcurrentTestContext (testName, testFn, asyncError, state, options) {
762
+ const testFullName = this.getTestNameFromAddTestEvent({ testName }, state)
763
+ const isNewTest = this.isKnownTestsEnabled && !this.knownTestsForThisSuite?.includes(testFullName)
764
+ const isAttemptToFix = this.isTestManagementTestsEnabled &&
765
+ this.testManagementTestsForThisSuite?.attemptToFix?.includes(testFullName)
766
+ const sourceTestFn = options?.sourceTestFn || testFn
767
+ const ctx = {
768
+ name: testFullName,
769
+ suite: this.testSuite,
770
+ testSourceFile: this.testSourceFile,
771
+ displayName: this.displayName,
772
+ testParameters: options?.testParameters || getTestParametersString(this.nameToParams, testName),
773
+ frameworkVersion: jestVersion,
774
+ isNew: isNewTest,
775
+ isEfdRetry: options?.isEfdRetry === true,
776
+ isAttemptToFix,
777
+ isAttemptToFixRetry: options?.isAttemptToFixRetry === true,
778
+ isJestRetry: false,
779
+ isDisabled: this.testManagementTestsForThisSuite?.disabled?.includes(testFullName),
780
+ isQuarantined: this.testManagementTestsForThisSuite?.quarantined?.includes(testFullName),
781
+ isModified: options?.isModified ?? this.isTestModified(asyncError, sourceTestFn),
782
+ hasDynamicName: isNewTest && DYNAMIC_NAME_RE.test(testFullName),
783
+ testSuiteAbsolutePath: this.testSuiteAbsolutePath,
784
+ }
785
+ let contexts = this.concurrentTestContexts.get(testFullName)
786
+ if (contexts) {
787
+ contexts.push(ctx)
788
+ } else {
789
+ contexts = [ctx]
790
+ this.concurrentTestContexts.set(testFullName, contexts)
791
+ }
792
+ return ctx
793
+ }
794
+
795
+ /**
796
+ * Checks if a test overlaps modified lines for impacted-test detection.
797
+ *
798
+ * @param {Error|undefined} asyncError
799
+ * @param {Function|undefined} testFn
800
+ * @returns {boolean}
801
+ */
802
+ isTestModified (asyncError, testFn) {
803
+ if (!this.isImpactedTestsEnabled || !asyncError || typeof testFn !== 'function') return false
804
+
805
+ const testStartLine = getTestLineStart(asyncError, this.testSuite)
806
+ const testEndLine = getTestEndLine(testFn, testStartLine)
807
+ return isModifiedTest(
808
+ this.testSourceFile,
809
+ testStartLine,
810
+ testEndLine,
811
+ this.modifiedFiles,
812
+ 'jest'
813
+ )
814
+ }
815
+
816
+ /**
817
+ * Gets the next registered concurrent test context for a full Jest test name.
818
+ *
819
+ * @param {string} testName
820
+ * @returns {object|undefined}
821
+ */
822
+ getNextConcurrentTestContext (testName) {
823
+ const contexts = this.concurrentTestContexts.get(testName)
824
+ if (!contexts?.length) return
825
+
826
+ const ctx = contexts.shift()
827
+ if (contexts.length === 0) {
828
+ this.concurrentTestContexts.delete(testName)
829
+ }
830
+ return ctx
831
+ }
832
+
833
+ /**
834
+ * Removes one registered concurrent test context from the name fallback queue.
835
+ *
836
+ * @param {string} testName
837
+ * @param {object} ctx
838
+ * @returns {void}
839
+ */
840
+ removeConcurrentTestContext (testName, ctx) {
841
+ const contexts = this.concurrentTestContexts.get(testName)
842
+ if (!contexts?.length) return
843
+
844
+ const contextIndex = contexts.indexOf(ctx)
845
+ if (contextIndex === -1) return
846
+
847
+ contexts.splice(contextIndex, 1)
848
+ if (contexts.length === 0) {
849
+ this.concurrentTestContexts.delete(testName)
850
+ }
851
+ }
852
+
853
+ /**
854
+ * Records formatted parameters for one table-driven Jest test declaration.
855
+ *
856
+ * @param {string} name
857
+ * @param {unknown[]} params
858
+ * @returns {void}
859
+ */
860
+ setNameToParams (name, params) {
861
+ this.nameToParams[name] = [...params]
862
+ }
863
+
864
+ /**
865
+ * Appends formatted parameters for one table-driven Jest test row.
866
+ *
867
+ * @param {string} name
868
+ * @param {unknown[]|object} params
869
+ * @returns {void}
870
+ */
871
+ appendNameToParams (name, params) {
872
+ if (this.nameToParams[name]) {
873
+ this.nameToParams[name].push(params)
874
+ } else {
875
+ this.nameToParams[name] = [params]
876
+ }
877
+ }
878
+
879
+ /**
880
+ * Runs a concurrent test function inside its test span context.
881
+ *
882
+ * @param {{ ctx: object, numExecutions: number }} concurrentTestState
883
+ * @param {(...args: unknown[]) => unknown} testFn
884
+ * @param {object} thisArg
885
+ * @param {unknown[]} args
886
+ * @returns {unknown|void}
887
+ */
888
+ runConcurrentTestFn (concurrentTestState, testFn, thisArg, args) {
889
+ const ctx = concurrentTestState.ctx
890
+ if (ctx.isDisabled && !ctx.isAttemptToFix) {
891
+ const done = args[0]
892
+ if (typeof done === 'function') {
893
+ done()
894
+ }
895
+ return
896
+ }
897
+
898
+ const runTest = () => testFn.apply(thisArg, args)
899
+ if (!ctx.isAttemptToFixRetry && !ctx.isEfdRetry) {
900
+ ctx.isJestRetry = concurrentTestState.numExecutions > 0
901
+ }
902
+ concurrentTestState.numExecutions++
903
+
904
+ if (ctx.currentStore) {
905
+ return testFnCh.runStores(ctx, runTest)
906
+ }
907
+
908
+ let result
909
+ testStartCh.runStores(ctx, () => {
910
+ result = testFnCh.runStores(ctx, runTest)
911
+ })
912
+ return result
913
+ }
914
+
915
+ /**
916
+ * Ensures Datadog handles Jest circus events even when a custom environment overrides
917
+ * `handleTestEvent` without calling `super.handleTestEvent`.
918
+ *
919
+ * @param {(event: object, state: object) => Promise<void>|void} datadogHandleTestEvent
920
+ * @returns {void}
921
+ */
922
+ wrapCustomHandleTestEvent (datadogHandleTestEvent) {
923
+ const descriptor = Object.getOwnPropertyDescriptor(this, 'handleTestEvent')
924
+ let handleTestEvent = getWrappedCustomHandleTestEvent(this.handleTestEvent, datadogHandleTestEvent)
925
+
926
+ Object.defineProperty(this, 'handleTestEvent', {
927
+ configurable: true,
928
+ enumerable: descriptor?.enumerable ?? false,
929
+ get () {
930
+ return handleTestEvent
931
+ },
932
+ set (value) {
933
+ handleTestEvent = getWrappedCustomHandleTestEvent(value, datadogHandleTestEvent)
934
+ },
935
+ })
301
936
  }
302
937
 
303
938
  /**
@@ -340,6 +975,10 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
340
975
  */
341
976
  resetMockState () {
342
977
  try {
978
+ if (this.moduleMocker?.clearAllMocks) {
979
+ this.moduleMocker.clearAllMocks()
980
+ return
981
+ }
343
982
  const jestObject = testSuiteJestObjects.get(this.testSuiteAbsolutePath)
344
983
  if (jestObject?.clearAllMocks) {
345
984
  jestObject.clearAllMocks()
@@ -407,12 +1046,47 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
407
1046
  // Generic function to handle test retries
408
1047
  retryTest ({
409
1048
  jestEvent,
1049
+ forceSerial,
410
1050
  retryCount,
411
1051
  retryType,
412
1052
  }) {
413
1053
  const { testName, fn, timeout } = jestEvent
1054
+ const isAttemptToFixRetry = retryType === 'Test Management (Attempt to Fix)'
1055
+ const isEfdRetry = retryType === 'Impacted tests' || retryType === 'Early flake detection'
414
1056
  for (let retryIndex = 0; retryIndex < retryCount; retryIndex++) {
415
- if (this.global.test) {
1057
+ const concurrentTestState = this.concurrentTestStates.get(fn)
1058
+ if (concurrentTestState) {
1059
+ const test = forceSerial
1060
+ ? concurrentTestState.serialTest
1061
+ : (
1062
+ concurrentTestState.concurrentTest ||
1063
+ getOriginalConcurrentTest(this.global.test?.concurrent)
1064
+ )
1065
+ if (typeof test !== 'function') {
1066
+ log.error('%s could not retry concurrent test because test is undefined', retryType)
1067
+ continue
1068
+ }
1069
+ const retryFn = this.createConcurrentTestFn(
1070
+ testName,
1071
+ concurrentTestState.testFn,
1072
+ undefined,
1073
+ concurrentTestState.state,
1074
+ {
1075
+ concurrentTest: concurrentTestState.concurrentTest,
1076
+ concurrentTestThisArg: concurrentTestState.concurrentTestThisArg,
1077
+ isAttemptToFixRetry,
1078
+ isEfdRetry,
1079
+ isModified: concurrentTestState.ctx.isModified,
1080
+ serialTest: concurrentTestState.serialTest,
1081
+ serialTestThisArg: concurrentTestState.serialTestThisArg,
1082
+ testParameters: concurrentTestState.ctx.testParameters,
1083
+ }
1084
+ )
1085
+ const thisArg = forceSerial
1086
+ ? concurrentTestState.serialTestThisArg
1087
+ : concurrentTestState.concurrentTestThisArg
1088
+ test.call(thisArg, testName, retryFn, timeout)
1089
+ } else if (this.global.test) {
416
1090
  this.global.test(testName, fn, timeout)
417
1091
  } else {
418
1092
  log.error('%s could not retry test because global.test is undefined', retryType)
@@ -420,36 +1094,45 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
420
1094
  }
421
1095
  }
422
1096
 
423
- getShouldStripSeedFromTestName () {
424
- return testSuiteAbsolutePathsWithFastCheck.has(this.testSuiteAbsolutePath)
425
- }
426
-
427
1097
  // At the `add_test` event we don't have the test object yet, so we can't use it
428
1098
  getTestNameFromAddTestEvent (event, state) {
429
- const describeSuffix = getJestTestName(state.currentDescribeBlock, this.getShouldStripSeedFromTestName())
430
- return describeSuffix ? `${describeSuffix} ${event.testName}` : event.testName
1099
+ const describeSuffix = getRawJestTestName(state.currentDescribeBlock)
1100
+ const testName = describeSuffix ? `${describeSuffix} ${event.testName}` : event.testName
1101
+ return removeSeedSuffixFromTestName(testName)
431
1102
  }
432
1103
 
433
1104
  async handleTestEvent (event, state) {
1105
+ if (isDatadogJestEventHandled(event)) return
1106
+ markDatadogJestEventHandled(event)
1107
+
434
1108
  if (super.handleTestEvent) {
435
1109
  await super.handleTestEvent(event, state)
436
1110
  }
437
1111
 
438
- const setNameToParams = (name, params) => { this.nameToParams[name] = [...params] }
439
-
1112
+ if (event.name === 'setup') {
1113
+ this.wrapConcurrentTest(state)
1114
+ }
440
1115
  if (event.name === 'setup' && this.global.test) {
441
- shimmer.wrap(this.global.test, 'each', each => function () {
442
- const testParameters = getFormattedJestTestParameters(arguments)
443
- const eachBind = each.apply(this, arguments)
444
- return function () {
445
- const [testName] = arguments
446
- setNameToParams(testName, testParameters)
447
- return eachBind.apply(this, arguments)
1116
+ const environment = this
1117
+ shimmer.wrap(this.global.test, 'each', each => function (...args) {
1118
+ const testParameters = getFormattedJestTestParameters(args)
1119
+ const eachBind = each.apply(this, args)
1120
+ return function (...args) {
1121
+ const [testName] = args
1122
+ environment.setNameToParams(testName, testParameters)
1123
+ return eachBind.apply(this, args)
448
1124
  }
449
1125
  })
450
1126
  }
451
1127
  if (event.name === 'test_start') {
452
- const testName = getJestTestName(event.test, this.getShouldStripSeedFromTestName())
1128
+ const testName = getJestTestName(event.test)
1129
+ const concurrentTestState = this.concurrentTestStates.get(event.test.fn)
1130
+ let concurrentCtx = concurrentTestState?.ctx
1131
+ if (concurrentCtx) {
1132
+ this.removeConcurrentTestContext(testName, concurrentCtx)
1133
+ } else {
1134
+ concurrentCtx = this.getNextConcurrentTestContext(testName)
1135
+ }
453
1136
  if (testsToBeRetried.has(testName)) {
454
1137
  // This is needed because we're retrying tests with the same name
455
1138
  this.resetSnapshotState()
@@ -459,7 +1142,9 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
459
1142
  let isNewTest = false
460
1143
  let numEfdRetry = null
461
1144
  let numOfAttemptsToFixRetries = null
462
- const testParameters = getTestParametersString(this.nameToParams, event.test.name)
1145
+ const testParameters = concurrentCtx?.testParameters ||
1146
+ concurrentTestState?.ctx?.testParameters ||
1147
+ getTestParametersString(this.nameToParams, event.test.name)
463
1148
 
464
1149
  let isAttemptToFix = false
465
1150
  let isDisabled = false
@@ -476,17 +1161,9 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
476
1161
  }
477
1162
  }
478
1163
 
479
- let isModified = false
480
- if (this.isImpactedTestsEnabled) {
481
- const testStartLine = getTestLineStart(event.test.asyncError, this.testSuite)
482
- const testEndLine = getTestEndLine(event.test.fn, testStartLine)
483
- isModified = isModifiedTest(
484
- this.testSourceFile,
485
- testStartLine,
486
- testEndLine,
487
- this.modifiedFiles,
488
- 'jest'
489
- )
1164
+ let isModified = this.isTestModified(event.test.asyncError, event.test.fn)
1165
+ if (concurrentCtx?.isModified || concurrentTestState?.ctx?.isModified) {
1166
+ isModified = true
490
1167
  }
491
1168
 
492
1169
  if (this.isKnownTestsEnabled) {
@@ -503,27 +1180,34 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
503
1180
 
504
1181
  const isJestRetry = event.test?.invocations > 1
505
1182
  const hasDynamicName = isNewTest && DYNAMIC_NAME_RE.test(testName)
506
- const ctx = {
507
- name: testName,
508
- suite: this.testSuite,
509
- testSourceFile: this.testSourceFile,
510
- displayName: this.displayName,
511
- testParameters,
512
- frameworkVersion: jestVersion,
513
- isNew: isNewTest,
514
- isEfdRetry: numEfdRetry > 0,
515
- isAttemptToFix,
516
- isAttemptToFixRetry: numOfAttemptsToFixRetries > 0,
517
- isJestRetry,
518
- isDisabled,
519
- isQuarantined,
520
- isModified,
521
- hasDynamicName,
522
- testSuiteAbsolutePath: this.testSuiteAbsolutePath,
1183
+ const ctx = concurrentCtx || concurrentTestState?.ctx || {}
1184
+ ctx.name = testName
1185
+ ctx.suite = this.testSuite
1186
+ ctx.testSourceFile = this.testSourceFile
1187
+ ctx.displayName = this.displayName
1188
+ ctx.testParameters = testParameters
1189
+ ctx.frameworkVersion = jestVersion
1190
+ ctx.isNew = isNewTest
1191
+ ctx.isEfdRetry = ctx.isEfdRetry || numEfdRetry > 0
1192
+ ctx.isAttemptToFix = isAttemptToFix
1193
+ ctx.isAttemptToFixRetry = ctx.isAttemptToFixRetry || numOfAttemptsToFixRetries > 0
1194
+ ctx.isJestRetry = isJestRetry
1195
+ ctx.isDisabled = isDisabled
1196
+ ctx.isQuarantined = isQuarantined
1197
+ ctx.isModified = isModified
1198
+ ctx.hasDynamicName = hasDynamicName
1199
+ ctx.testSuiteAbsolutePath = this.testSuiteAbsolutePath
1200
+ if (concurrentTestState) {
1201
+ ctx.concurrentTestState = concurrentTestState
1202
+ concurrentTestState.ctx = ctx
523
1203
  }
524
1204
  testContexts.set(event.test, ctx)
525
1205
 
526
- testStartCh.runStores(ctx, () => {
1206
+ if (isAttemptToFix) {
1207
+ logAttemptToFixTestExecution(this.testSuite, testName, loggedAttemptToFixTests)
1208
+ }
1209
+
1210
+ const wrapTestAndHooks = () => {
527
1211
  let p = event.test.parent
528
1212
  const hooks = []
529
1213
  while (p != null) {
@@ -537,20 +1221,67 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
537
1221
  } else {
538
1222
  originalHookFns.set(hook, hookFn)
539
1223
  }
540
- const newHookFn = shimmer.wrapFunction(hookFn, hookFn => function () {
541
- return testFnCh.runStores(ctx, () => hookFn.apply(this, arguments))
1224
+ const newHookFn = shimmer.wrapFunction(hookFn, hookFn => function (...args) {
1225
+ return testFnCh.runStores(ctx, () => hookFn.apply(this, args))
542
1226
  })
543
1227
  hook.fn = newHookFn
544
1228
  }
1229
+
545
1230
  const originalFn = event.test.fn
546
1231
  originalTestFns.set(event.test, originalFn)
547
1232
 
548
- const newFn = shimmer.wrapFunction(event.test.fn, testFn => function () {
549
- return testFnCh.runStores(ctx, () => testFn.apply(this, arguments))
1233
+ const newFn = shimmer.wrapFunction(event.test.fn, testFn => function (...args) {
1234
+ return testFnCh.runStores(ctx, () => testFn.apply(this, args))
550
1235
  })
551
1236
 
552
1237
  event.test.fn = newFn
553
- })
1238
+ }
1239
+
1240
+ const isConcurrentTest = event.test.concurrent || ctx.concurrentTestState
1241
+ if (isConcurrentTest) {
1242
+ if (!ctx.currentStore && event.test.errors?.length) {
1243
+ testStartCh.runStores(ctx, () => {})
1244
+ }
1245
+ } else if (ctx.currentStore) {
1246
+ wrapTestAndHooks()
1247
+ } else {
1248
+ testStartCh.runStores(ctx, wrapTestAndHooks)
1249
+ }
1250
+ }
1251
+
1252
+ if (event.name === 'hook_start' && (event.hook.type === 'beforeEach' || event.hook.type === 'afterEach')) {
1253
+ const ctx = testContexts.get(event.test) || this.concurrentTestStates.get(event.test?.fn)?.ctx
1254
+ if (ctx?.concurrentTestState && (!ctx.isDisabled || ctx.isAttemptToFix)) {
1255
+ let hookFn = event.hook.fn
1256
+ if (originalHookFns.has(event.hook)) {
1257
+ hookFn = originalHookFns.get(event.hook)
1258
+ } else {
1259
+ originalHookFns.set(event.hook, hookFn)
1260
+ }
1261
+ let hookContexts = concurrentHookContextQueues.get(event.hook)
1262
+ if (!hookContexts) {
1263
+ hookContexts = []
1264
+ concurrentHookContextQueues.set(event.hook, hookContexts)
1265
+ }
1266
+ hookContexts.push(ctx)
1267
+ if (!ctx.currentStore) {
1268
+ testStartCh.runStores(ctx, () => {})
1269
+ }
1270
+ let concurrentHookFn = concurrentHookFns.get(event.hook)
1271
+ if (!concurrentHookFn) {
1272
+ concurrentHookFn = shimmer.wrapFunction(hookFn, hookFn => function (...args) {
1273
+ const hookContexts = concurrentHookContextQueues.get(event.hook)
1274
+ const [hookCtx] = hookContexts || []
1275
+ if (hookCtx) {
1276
+ hookContexts.shift()
1277
+ return testFnCh.runStores(hookCtx, () => hookFn.apply(this, args))
1278
+ }
1279
+ return hookFn.apply(this, args)
1280
+ })
1281
+ concurrentHookFns.set(event.hook, concurrentHookFn)
1282
+ }
1283
+ event.hook.fn = concurrentHookFn
1284
+ }
554
1285
  }
555
1286
 
556
1287
  if (event.name === 'hook_start' && (event.hook.type === 'beforeAll' || event.hook.type === 'afterAll')) {
@@ -561,12 +1292,16 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
561
1292
  } else {
562
1293
  originalHookFns.set(event.hook, hookFn)
563
1294
  }
564
- event.hook.fn = shimmer.wrapFunction(hookFn, hookFn => function () {
565
- return testSuiteHookFnCh.runStores(ctx, () => hookFn.apply(this, arguments))
1295
+ event.hook.fn = shimmer.wrapFunction(hookFn, hookFn => function (...args) {
1296
+ return testSuiteHookFnCh.runStores(ctx, () => hookFn.apply(this, args))
566
1297
  })
567
1298
  }
568
1299
 
569
1300
  if (event.name === 'add_test') {
1301
+ if (event.concurrent) {
1302
+ this.hasConcurrentTests = true
1303
+ }
1304
+
570
1305
  if (event.failing) {
571
1306
  return
572
1307
  }
@@ -589,15 +1324,9 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
589
1324
  })
590
1325
  }
591
1326
  if (!isAttemptToFix && this.isImpactedTestsEnabled) {
592
- const testStartLine = getTestLineStart(event.asyncError, this.testSuite)
593
- const testEndLine = getTestEndLine(event.fn, testStartLine)
594
- const isModified = isModifiedTest(
595
- this.testSourceFile,
596
- testStartLine,
597
- testEndLine,
598
- this.modifiedFiles,
599
- 'jest'
600
- )
1327
+ const concurrentTestState = this.concurrentTestStates.get(event.fn)
1328
+ const isModified = concurrentTestState?.ctx?.isModified ||
1329
+ this.isTestModified(event.asyncError, event.fn)
601
1330
  if (isModified && !retriedTestsToNumAttempts.has(testFullName) && this.isEarlyFlakeDetectionEnabled) {
602
1331
  retriedTestsToNumAttempts.set(testFullName, 0)
603
1332
  testsToBeRetried.add(testFullName)
@@ -636,7 +1365,9 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
636
1365
  status = 'fail'
637
1366
  }
638
1367
  // restore in case it is retried
639
- event.test.fn = originalTestFns.get(event.test)
1368
+ if (originalTestFns.has(event.test)) {
1369
+ event.test.fn = originalTestFns.get(event.test)
1370
+ }
640
1371
  // If ATR retry is being suppressed for this test (due to EFD or Attempt to Fix taking precedence)
641
1372
  // and the test has errors for this attempt, store the errors temporarily and clear them
642
1373
  // so Jest won't treat this attempt as failed (the real status will be reported after retries).
@@ -649,7 +1380,7 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
649
1380
  let attemptToFixFailed = false
650
1381
  let failedAllTests = false
651
1382
  let isAttemptToFix = false
652
- const testName = getJestTestName(event.test, this.getShouldStripSeedFromTestName())
1383
+ const testName = getJestTestName(event.test)
653
1384
  if (this.isTestManagementTestsEnabled) {
654
1385
  isAttemptToFix = this.testManagementTestsForThisSuite?.attemptToFix?.includes(testName)
655
1386
  if (isAttemptToFix) {
@@ -705,6 +1436,7 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
705
1436
  state.currentDescribeBlock = event.test.parent ?? originalDescribeBlock
706
1437
  state.hasStarted = false
707
1438
  this.retryTest({
1439
+ forceSerial: true,
708
1440
  jestEvent: {
709
1441
  testName: event.test.name,
710
1442
  fn: event.test.fn,
@@ -753,14 +1485,31 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
753
1485
  const promises = {}
754
1486
  const numRetries = this.global[RETRY_TIMES]
755
1487
  const numTestExecutions = event.test?.invocations
756
- const willBeRetriedByFailedTestReplay = numRetries > 0 && numTestExecutions - 1 < numRetries
757
- const mightHitBreakpoint = this.isDiEnabled && numTestExecutions >= 2
1488
+ const willBeRetriedByAutoTestRetry = numRetries > 0 && numTestExecutions - 1 < numRetries
1489
+ const isFailedTestReplayAllowed = !this.hasConcurrentTests
1490
+ const willBeRetriedByFailedTestReplay = isFailedTestReplayAllowed && willBeRetriedByAutoTestRetry
1491
+ const mightHitBreakpoint = this.isDiEnabled && isFailedTestReplayAllowed && numTestExecutions >= 2
1492
+
1493
+ // For quarantined tests, track failures so the session can be marked as passing later,
1494
+ // and suppress errors so Jest does not mark the test suite as failing.
1495
+ // The actual status ('fail') is already captured above for dd-trace reporting.
1496
+ // Only suppress on the final execution — not when ATR/EFD/ATF will retry the test.
1497
+ if (!event.test?.[ATR_RETRY_SUPPRESSION_FLAG] && !willBeRetriedByAutoTestRetry) {
1498
+ const quarantineCtx = testContexts.get(event.test)
1499
+ if (quarantineCtx?.isQuarantined && !quarantineCtx.isAttemptToFix && event.test.errors?.length) {
1500
+ quarantinedFailingTests.add(`${quarantineCtx.suite} › ${quarantineCtx.name}`)
1501
+ event.test.errors = []
1502
+ }
1503
+ }
758
1504
 
759
1505
  const ctx = testContexts.get(event.test)
760
1506
  if (!ctx) {
761
1507
  log.warn('"ci:jest:test_done": no context found for test "%s"', testName)
762
1508
  return
763
1509
  }
1510
+ if (ctx.concurrentTestState && !ctx.currentStore && !ctx.isDisabled) {
1511
+ testStartCh.runStores(ctx, () => {})
1512
+ }
764
1513
 
765
1514
  const finalStatus = this.getFinalStatus(testName,
766
1515
  status,
@@ -776,18 +1525,13 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
776
1525
  ...ctx.currentStore,
777
1526
  error: formatJestError(originalError),
778
1527
  shouldSetProbe,
1528
+ shouldWaitForHitProbe: mightHitBreakpoint,
779
1529
  promises,
780
1530
  })
781
1531
  }
782
1532
 
783
- // After finishing it might take a bit for the snapshot to be handled.
784
- // This means that tests retried with DI are BREAKPOINT_HIT_GRACE_PERIOD_MS slower at least.
785
- if (status === 'fail' && mightHitBreakpoint) {
786
- await new Promise(resolve => {
787
- realSetTimeout(() => {
788
- resolve()
789
- }, BREAKPOINT_HIT_GRACE_PERIOD_MS)
790
- })
1533
+ if (promises.hitBreakpointPromise) {
1534
+ await promises.hitBreakpointPromise
791
1535
  }
792
1536
 
793
1537
  let isAtrRetry = false
@@ -805,17 +1549,40 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
805
1549
  isAtrRetry,
806
1550
  finalStatus,
807
1551
  earlyFlakeAbortReason: efdSlowAbortedTests.has(testName) ? 'slow' : undefined,
1552
+ promises,
808
1553
  })
809
1554
 
1555
+ if (promises.hitBreakpointPromise) {
1556
+ await promises.hitBreakpointPromise
1557
+ }
810
1558
  if (promises.isProbeReady) {
811
1559
  await promises.isProbeReady
812
1560
  }
1561
+ if (ctx.concurrentTestState) {
1562
+ ctx.currentStore = undefined
1563
+ }
813
1564
  }
814
1565
  if (event.name === 'run_finish') {
815
1566
  for (const [test, errors] of atrSuppressedErrors) {
816
- test.errors = errors
1567
+ // Do not restore errors for non-ATF quarantined tests — they should stay suppressed
1568
+ // so Jest doesn't see the failure (prevents --bail from stopping the run).
1569
+ const ctx = testContexts.get(test)
1570
+ if (ctx?.isQuarantined && !ctx.isAttemptToFix) {
1571
+ const testName = getJestTestName(test)
1572
+ quarantinedFailingTests.add(`${ctx.suite} › ${testName}`)
1573
+ } else {
1574
+ test.errors = errors
1575
+ }
817
1576
  }
818
1577
  atrSuppressedErrors.clear()
1578
+
1579
+ // In parallel mode, send suppressed quarantine info to the main process
1580
+ // so it can include them in the session summary.
1581
+ // In runInBand mode, keep the set — it will be consumed by the session-level code directly.
1582
+ if (quarantinedFailingTests.size > 0 && sendQuarantineInfoToMainProcess([...quarantinedFailingTests])) {
1583
+ quarantinedFailingTests.clear()
1584
+ }
1585
+
819
1586
  efdDeterminedRetries.clear()
820
1587
  efdSlowAbortedTests.clear()
821
1588
  efdNewTestCandidates.clear()
@@ -823,9 +1590,10 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
823
1590
  retriedTestsToNumAttempts.clear()
824
1591
  attemptToFixRetriedTestsStatuses.clear()
825
1592
  testsToBeRetried.clear()
1593
+ testSuiteDatadogEnvironments.delete(this.testSuiteAbsolutePath)
826
1594
  }
827
1595
  if (event.name === 'test_skip' || event.name === 'test_todo') {
828
- const testName = getJestTestName(event.test, this.getShouldStripSeedFromTestName())
1596
+ const testName = getJestTestName(event.test)
829
1597
  testSkippedCh.publish({
830
1598
  test: {
831
1599
  name: testName,
@@ -923,7 +1691,8 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
923
1691
 
924
1692
  // If the test is quarantined, regardless of its actual execution result,
925
1693
  // the final status of its last execution should be reported as 'skip'.
926
- if (this.isTestManagementTestsEnabled &&
1694
+ if (!attemptToFixResult.isAttemptToFixEnabled &&
1695
+ this.isTestManagementTestsEnabled &&
927
1696
  this.testManagementTestsForThisSuite?.quarantined?.includes(testName)) {
928
1697
  return 'skip'
929
1698
  }
@@ -939,7 +1708,19 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
939
1708
  }
940
1709
  }
941
1710
  }
942
- return super.teardown()
1711
+ const clearActiveTestSuite = () => {
1712
+ realSetTimeout(() => {
1713
+ if (activeTestSuiteAbsolutePath === this.testSuiteAbsolutePath) {
1714
+ activeTestSuiteAbsolutePath = undefined
1715
+ }
1716
+ }, 0)
1717
+ }
1718
+ const result = super.teardown()
1719
+ if (result?.then) {
1720
+ return result.finally(clearActiveTestSuite)
1721
+ }
1722
+ clearActiveTestSuite()
1723
+ return result
943
1724
  }
944
1725
  }
945
1726
  }
@@ -962,29 +1743,398 @@ function getTestEnvironment (pkg, jestVersion) {
962
1743
  return getWrappedEnvironment(pkg, jestVersion)
963
1744
  }
964
1745
 
1746
+ function getRepositoryRootFromConfig (config, fallbackRootDir) {
1747
+ return config?.testEnvironmentOptions?._ddRepositoryRoot || repositoryRoot || fallbackRootDir || process.cwd()
1748
+ }
1749
+
1750
+ function getRepositoryRootFromContexts (contexts, fallbackRootDir) {
1751
+ const [firstContext] = contexts || []
1752
+ return getRepositoryRootFromConfig(firstContext?.config, fallbackRootDir)
1753
+ }
1754
+
1755
+ function getRepositoryRootFromTest (test, fallbackRootDir) {
1756
+ return getRepositoryRootFromConfig(test?.context?.config, fallbackRootDir)
1757
+ }
1758
+
1759
+ function hasSkippableSuitesCoverage () {
1760
+ return skippableSuitesCoverage &&
1761
+ typeof skippableSuitesCoverage === 'object' &&
1762
+ Object.keys(skippableSuitesCoverage).length > 0
1763
+ }
1764
+
1765
+ function shouldCollectJestCoverageForTia () {
1766
+ return shouldReportJestSuiteCoverageForTia() ||
1767
+ (isJestCoverageBackfillSupported && isItrEnabled && isCoverageReportUploadEnabled)
1768
+ }
1769
+
1770
+ function shouldReportJestSuiteCoverageForTia () {
1771
+ return isItrEnabled && isCodeCoverageEnabled
1772
+ }
1773
+
1774
+ function hasJestCoverageMap () {
1775
+ return isUserCodeCoverageEnabled || shouldCollectJestCoverageForTia()
1776
+ }
1777
+
1778
+ // TIA coverage backfill is part of Datadog Code Coverage, not the per-suite TIA coverage upload.
1779
+ function isTiaCoverageBackfillEnabled () {
1780
+ return isJestCoverageBackfillSupported && isItrEnabled && isCoverageReportUploadEnabled && hasJestCoverageMap()
1781
+ }
1782
+
1783
+ // Non-TIA Jest coverage keeps the legacy metric. TIA only reports it when Datadog Code Coverage is enabled and
1784
+ // either the run is complete locally or the skipped suites can be backfilled.
1785
+ function shouldReportCodeCoverageLinesPct () {
1786
+ if (!hasJestCoverageMap()) return false
1787
+ if (!isItrEnabled) return true
1788
+ if (!isCoverageReportUploadEnabled) return false
1789
+
1790
+ // If no suites were actually skipped, the local Jest coverage map is complete and does not need backfill.
1791
+ return !isSuitesSkipped || isTiaCoverageBackfillEnabled()
1792
+ }
1793
+
1794
+ function getHookRequire (hookMeta) {
1795
+ if (!hookMeta?.moduleBaseDir) return
1796
+
1797
+ return createRequire(path.join(hookMeta.moduleBaseDir, 'package.json'))
1798
+ }
1799
+
1800
+ function getCoverageBackfillRequire (CoverageReporter) {
1801
+ const hookedCoverageReporterRequire = CoverageReporter && coverageReporterRequires.get(CoverageReporter)
1802
+ if (hookedCoverageReporterRequire) return hookedCoverageReporterRequire
1803
+ if (coverageReporterRequire) return coverageReporterRequire
1804
+
1805
+ const coverageReporterFilename = CoverageReporter?.filename || coverageReporterClass?.filename
1806
+ if (coverageReporterFilename) {
1807
+ return createRequire(`${path.join(path.dirname(coverageReporterFilename), 'CoverageWorker')}.js`)
1808
+ }
1809
+
1810
+ return require
1811
+ }
1812
+
1813
+ function addDatadogBailReporter (globalConfig) {
1814
+ if (!globalConfig.bail) return globalConfig
1815
+
1816
+ const reporters = globalConfig.reporters || [['default', {}]]
1817
+ for (const [reporter] of reporters) {
1818
+ if (reporter === JEST_BAIL_REPORTER_PATH) {
1819
+ return globalConfig
1820
+ }
1821
+ }
1822
+
1823
+ return {
1824
+ ...globalConfig,
1825
+ reporters: [
1826
+ ...reporters,
1827
+ [JEST_BAIL_REPORTER_PATH, {}],
1828
+ ],
1829
+ }
1830
+ }
1831
+
1832
+ function getTestContexts (tests) {
1833
+ if (!tests?.length) return
1834
+
1835
+ const contexts = new Set()
1836
+ for (const test of tests) {
1837
+ if (test.context) {
1838
+ contexts.add(test.context)
1839
+ }
1840
+ }
1841
+ return contexts.size ? contexts : undefined
1842
+ }
1843
+
1844
+ function getCoverageBackfillContexts (contexts) {
1845
+ return contexts?.size ? contexts : coverageBackfillContexts || contexts
1846
+ }
1847
+
1848
+ function resetSuiteSkippingRunState () {
1849
+ isSuitesSkipped = false
1850
+ numSkippedSuites = 0
1851
+ hasUnskippableSuites = false
1852
+ hasForcedToRunSuites = false
1853
+ hasFilteredSkippableSuites = false
1854
+ skippedSuitesCoverage = {}
1855
+ lastCoverageMap = undefined
1856
+ lastCoverageMapRootDir = undefined
1857
+ coverageBackfillContexts = undefined
1858
+ coverageBackfillFiles = undefined
1859
+ }
1860
+
1861
+ function resetLibraryConfiguration () {
1862
+ knownTests = {}
1863
+ isCodeCoverageEnabled = false
1864
+ isCoverageReportUploadEnabled = false
1865
+ isItrEnabled = false
1866
+ isSuitesSkippingEnabled = false
1867
+ isEarlyFlakeDetectionEnabled = false
1868
+ earlyFlakeDetectionNumRetries = 0
1869
+ earlyFlakeDetectionSlowTestRetries = {}
1870
+ earlyFlakeDetectionFaultyThreshold = 30
1871
+ isEarlyFlakeDetectionFaulty = false
1872
+ isKnownTestsEnabled = false
1873
+ isTestManagementTestsEnabled = false
1874
+ testManagementTests = {}
1875
+ testManagementAttemptToFixRetries = 0
1876
+ isImpactedTestsEnabled = false
1877
+ modifiedFiles = {}
1878
+ repositoryRoot = undefined
1879
+ }
1880
+
965
1881
  function applySuiteSkipping (originalTests, rootDir, frameworkVersion) {
966
- const jestSuitesToRun = getJestSuitesToRun(skippableSuites, originalTests, rootDir || process.cwd())
1882
+ if (!isItrEnabled || !isSuitesSkippingEnabled) return originalTests
1883
+
1884
+ const repositoryRoot = getRepositoryRootFromTest(originalTests[0], rootDir)
1885
+ const jestSuitesToRun = getJestSuitesToRun(skippableSuites, originalTests, repositoryRoot, rootDir)
967
1886
  hasFilteredSkippableSuites = true
968
- log.debug('%d out of %d suites are going to run.', jestSuitesToRun.suitesToRun.length, originalTests.length)
1887
+ log.debug(
1888
+ 'Jest discovered %d suites; skipped %d using %d skippable candidates; %d suites will run.',
1889
+ originalTests.length,
1890
+ jestSuitesToRun.skippedSuites.length,
1891
+ skippableSuites.length,
1892
+ jestSuitesToRun.suitesToRun.length
1893
+ )
969
1894
  hasUnskippableSuites = jestSuitesToRun.hasUnskippableSuites
970
1895
  hasForcedToRunSuites = jestSuitesToRun.hasForcedToRunSuites
971
1896
 
972
1897
  isSuitesSkipped = jestSuitesToRun.suitesToRun.length !== originalTests.length
973
1898
  numSkippedSuites = jestSuitesToRun.skippedSuites.length
1899
+ skippedSuitesCoverage = isSuitesSkipped && isTiaCoverageBackfillEnabled() && hasSkippableSuitesCoverage()
1900
+ ? skippableSuitesCoverage
1901
+ : {}
1902
+ coverageBackfillContexts = isSuitesSkipped && isTiaCoverageBackfillEnabled()
1903
+ ? getTestContexts(originalTests)
1904
+ : undefined
1905
+ coverageBackfillFiles = isSuitesSkipped && isTiaCoverageBackfillEnabled() && hasSkippableSuitesCoverage()
1906
+ ? getCoverageBackfillFiles(skippableSuitesCoverage, repositoryRoot, getTestSuitePath)
1907
+ : undefined
974
1908
 
975
1909
  itrSkippedSuitesCh.publish({ skippedSuites: jestSuitesToRun.skippedSuites, frameworkVersion })
976
1910
 
977
1911
  return jestSuitesToRun.suitesToRun
978
1912
  }
979
1913
 
1914
+ function applySkippedCoverageToJestCoverageMap (coverageMap, rootDir) {
1915
+ if (!coverageMap || !isSuitesSkipped || !isTiaCoverageBackfillEnabled()) return
1916
+ applySkippedCoverageToCoverage(
1917
+ coverageMap,
1918
+ skippedSuitesCoverage,
1919
+ rootDir || process.cwd()
1920
+ )
1921
+ }
1922
+
1923
+ function getSessionFinishError (results) {
1924
+ const numFailedTestSuites = results?.numFailedTestSuites || 0
1925
+ const numFailedTests = results?.numFailedTests || 0
1926
+
1927
+ return new Error(`Failed test suites: ${numFailedTestSuites}. Failed tests: ${numFailedTests}`)
1928
+ }
1929
+
1930
+ function getTestSessionCoveragePayload (results, fallbackRootDir) {
1931
+ const payload = {}
1932
+ if (!shouldReportCodeCoverageLinesPct()) return payload
1933
+
1934
+ try {
1935
+ const coverageMap = results?.coverageMap || lastCoverageMap
1936
+ const coverageRootDir = lastCoverageMapRootDir ||
1937
+ repositoryRoot ||
1938
+ fallbackRootDir ||
1939
+ process.cwd()
1940
+ if (isSuitesSkipped) {
1941
+ applySkippedCoverageToJestCoverageMap(coverageMap, coverageRootDir)
1942
+ }
1943
+ payload.testCodeCoverageLinesTotal = getTestCoverageLinesPercentage(
1944
+ coverageMap,
1945
+ undefined,
1946
+ coverageRootDir
1947
+ )
1948
+ if (isTiaCoverageBackfillEnabled()) {
1949
+ payload.testSessionCoverageFiles = getExecutableFilesFromCoverage(coverageMap).map(({ filename, bitmap }) => ({
1950
+ filename: getTestSuitePath(filename, coverageRootDir),
1951
+ bitmap,
1952
+ }))
1953
+ }
1954
+ } catch {
1955
+ // ignore errors
1956
+ }
1957
+
1958
+ return payload
1959
+ }
1960
+
1961
+ function getNumBailFailures (results) {
1962
+ const numFailedTests = results?.numFailedTests || 0
1963
+ const numFailedSuites = results?.numRuntimeErrorTestSuites === undefined
1964
+ ? (numFailedTests === 0 ? results?.numFailedTestSuites || 0 : 0)
1965
+ : results.numRuntimeErrorTestSuites
1966
+
1967
+ return numFailedTests + numFailedSuites
1968
+ }
1969
+
1970
+ function shouldFinishBailTestSession (globalConfig, results) {
1971
+ return !!globalConfig?.bail && getNumBailFailures(results) >= globalConfig.bail
1972
+ }
1973
+
1974
+ async function waitForTestSessionFinish (payload) {
1975
+ if (!testSessionFinishCh.hasSubscribers || hasFinishedTestSession) return
1976
+
1977
+ hasFinishedTestSession = true
1978
+
1979
+ let timeoutId
1980
+
1981
+ const flushPromise = new Promise((resolve) => {
1982
+ payload.onDone = () => {
1983
+ clearTimeout(timeoutId)
1984
+ resolve()
1985
+ }
1986
+ })
1987
+
1988
+ const timeoutPromise = new Promise((resolve) => {
1989
+ timeoutId = realSetTimeout(() => {
1990
+ resolve('timeout')
1991
+ }, FLUSH_TIMEOUT)
1992
+ timeoutId.unref?.()
1993
+ })
1994
+
1995
+ testSessionFinishCh.publish(payload)
1996
+
1997
+ const waitingResult = await Promise.race([flushPromise, timeoutPromise])
1998
+
1999
+ if (waitingResult === 'timeout') {
2000
+ log.error('Timeout waiting for the tracer to flush')
2001
+ }
2002
+ }
2003
+
2004
+ function getTestSessionFinishPayload (status, error, extra = {}) {
2005
+ return {
2006
+ status,
2007
+ isSuitesSkipped,
2008
+ isSuitesSkippingEnabled,
2009
+ isCodeCoverageEnabled,
2010
+ isCoverageReportUploadEnabled,
2011
+ numSkippedSuites,
2012
+ hasUnskippableSuites,
2013
+ hasForcedToRunSuites,
2014
+ error,
2015
+ isEarlyFlakeDetectionEnabled,
2016
+ isEarlyFlakeDetectionFaulty,
2017
+ isTestManagementTestsEnabled,
2018
+ ...extra,
2019
+ }
2020
+ }
2021
+
2022
+ async function finishBailTestSession (results, fallbackRootDir) {
2023
+ await waitForTestSessionFinish(getTestSessionFinishPayload(
2024
+ 'fail',
2025
+ getSessionFinishError(results),
2026
+ getTestSessionCoveragePayload(results, fallbackRootDir)
2027
+ ))
2028
+ }
2029
+
2030
+ jestSessionState.finishBailTestSession = finishBailTestSession
2031
+
2032
+ function reporterDispatcherWrapper (reporterDispatcherPackage) {
2033
+ const ReporterDispatcher = reporterDispatcherPackage.default ?? reporterDispatcherPackage
2034
+ if (ReporterDispatcher?.prototype?.onRunComplete) {
2035
+ shimmer.wrap(ReporterDispatcher.prototype, 'onRunComplete', onRunComplete => function (contexts, results) {
2036
+ if (isSuitesSkipped && isTiaCoverageBackfillEnabled()) {
2037
+ applySkippedCoverageToJestCoverageMap(results?.coverageMap, getRepositoryRootFromContexts(contexts))
2038
+ }
2039
+ return onRunComplete.apply(this, arguments)
2040
+ })
2041
+ }
2042
+
2043
+ return reporterDispatcherPackage
2044
+ }
2045
+
2046
+ function wrapCoverageReporter (CoverageReporter, hookMeta) {
2047
+ if (!CoverageReporter?.prototype?.onRunComplete || wrappedCoverageReporters.has(CoverageReporter)) {
2048
+ return
2049
+ }
2050
+
2051
+ coverageReporterRequire = getHookRequire(hookMeta) || coverageReporterRequire
2052
+ if (coverageReporterRequire) {
2053
+ coverageReporterRequires.set(CoverageReporter, coverageReporterRequire)
2054
+ }
2055
+ coverageReporterClass = CoverageReporter
2056
+ wrappedCoverageReporters.add(CoverageReporter)
2057
+ if (CoverageReporter.prototype._addUntestedFiles) {
2058
+ shimmer.wrap(CoverageReporter.prototype, '_addUntestedFiles', addUntestedFiles => function (...args) {
2059
+ const rootDir = repositoryRoot || this._globalConfig?.rootDir || process.cwd()
2060
+ args[0] = getCoverageBackfillContexts(args[0])
2061
+ const result = addUntestedFiles.apply(this, args)
2062
+ if (!isSuitesSkipped || !isTiaCoverageBackfillEnabled()) return result
2063
+
2064
+ const addBackfillAndApplyCoverage = () => {
2065
+ return addCoverageBackfillUntestedFiles({
2066
+ coverageMap: this._coverageMap,
2067
+ testContexts: args[0],
2068
+ rootDir,
2069
+ CoverageReporter,
2070
+ coverageBackfillFiles,
2071
+ getCoverageBackfillRequire,
2072
+ }).then(() => {
2073
+ applySkippedCoverageToJestCoverageMap(this._coverageMap, rootDir)
2074
+ })
2075
+ }
2076
+
2077
+ return Promise.resolve(result).then(value => {
2078
+ return addBackfillAndApplyCoverage().then(() => value)
2079
+ })
2080
+ })
2081
+ }
2082
+
2083
+ shimmer.wrap(CoverageReporter.prototype, 'onRunComplete', onRunComplete => async function (contexts, results) {
2084
+ const coverageContexts = getCoverageBackfillContexts(contexts)
2085
+ const rootDir = getRepositoryRootFromContexts(coverageContexts, this._globalConfig?.rootDir)
2086
+ const coverageMap = results?.coverageMap || this._coverageMap
2087
+ if (isSuitesSkipped && isTiaCoverageBackfillEnabled()) {
2088
+ await addCoverageBackfillUntestedFiles({
2089
+ coverageMap,
2090
+ testContexts: coverageContexts,
2091
+ rootDir,
2092
+ CoverageReporter,
2093
+ coverageBackfillFiles,
2094
+ getCoverageBackfillRequire,
2095
+ })
2096
+ applySkippedCoverageToJestCoverageMap(coverageMap, rootDir)
2097
+ }
2098
+ lastCoverageMap = coverageMap
2099
+ lastCoverageMapRootDir = rootDir
2100
+ const result = await onRunComplete.call(this, coverageContexts, results)
2101
+ if (shouldFinishBailTestSession(this._globalConfig, results)) {
2102
+ await finishBailTestSession(results, rootDir)
2103
+ }
2104
+ return result
2105
+ })
2106
+ }
2107
+
2108
+ function reportersWrapper (reportersPackage, _version, _isIitm, hookMeta) {
2109
+ wrapCoverageReporter(reportersPackage.CoverageReporter, hookMeta)
2110
+ return reportersPackage
2111
+ }
2112
+
2113
+ function coverageReporterWrapper (coverageReporterPackage, _version, _isIitm, hookMeta) {
2114
+ wrapCoverageReporter(coverageReporterPackage.default ?? coverageReporterPackage, hookMeta)
2115
+ return coverageReporterPackage
2116
+ }
2117
+
2118
+ addHook({
2119
+ name: 'jest-environment-node',
2120
+ versions: [MINIMUM_JEST_VERSION],
2121
+ }, getTestEnvironment)
2122
+
980
2123
  addHook({
981
2124
  name: 'jest-environment-node',
982
- versions: ['>=24.8.0'],
2125
+ file: 'build/index.js',
2126
+ versions: [MINIMUM_JEST_VERSION],
2127
+ }, getTestEnvironment)
2128
+
2129
+ addHook({
2130
+ name: 'jest-environment-jsdom',
2131
+ versions: [MINIMUM_JEST_VERSION],
983
2132
  }, getTestEnvironment)
984
2133
 
985
2134
  addHook({
986
2135
  name: 'jest-environment-jsdom',
987
- versions: ['>=24.8.0'],
2136
+ file: 'build/index.js',
2137
+ versions: [MINIMUM_JEST_VERSION],
988
2138
  }, getTestEnvironment)
989
2139
 
990
2140
  addHook({
@@ -1007,6 +2157,12 @@ function getWrappedScheduleTests (scheduleTests, frameworkVersion) {
1007
2157
  }
1008
2158
  }
1009
2159
 
2160
+ function getChannelPromise (channelToPublishTo, payload = {}) {
2161
+ return new Promise(resolve => {
2162
+ channelToPublishTo.publish({ ...payload, onDone: resolve })
2163
+ })
2164
+ }
2165
+
1010
2166
  function searchSourceWrapper (searchSourcePackage, frameworkVersion) {
1011
2167
  const SearchSource = searchSourcePackage.default ?? searchSourcePackage
1012
2168
 
@@ -1015,7 +2171,9 @@ function searchSourceWrapper (searchSourcePackage, frameworkVersion) {
1015
2171
  const [{ rootDir, shard }] = arguments
1016
2172
 
1017
2173
  if (isKnownTestsEnabled) {
1018
- const projectSuites = testPaths.tests.map(test => getTestSuitePath(test.path, test.context.config.rootDir))
2174
+ const projectSuites = testPaths.tests.map(test => {
2175
+ return getTestSuitePath(test.path, getRepositoryRootFromTest(test, test.context.config.rootDir))
2176
+ })
1019
2177
 
1020
2178
  // If the `jest` key does not exist in the known tests response, we consider the Early Flake detection faulty.
1021
2179
  const isFaulty = !knownTests?.jest ||
@@ -1035,14 +2193,11 @@ function searchSourceWrapper (searchSourcePackage, frameworkVersion) {
1035
2193
  }
1036
2194
  }
1037
2195
 
2196
+ // When Jest sharding is enabled, filter after Jest picks this process's shard. Different shards usually run in
2197
+ // different CI jobs, so their skippable requests can happen at different times and receive different responses.
2198
+ // Filtering before Jest shards would make each job shard a different base test list, which can cause duplicate
2199
+ // suite execution across shards.
1038
2200
  if (shard?.shardCount > 1 || !isSuitesSkippingEnabled || !skippableSuites.length) {
1039
- // If the user is using jest sharding, we want to apply the filtering of tests in the shard process.
1040
- // The reason for this is the following:
1041
- // The tests for different shards are likely being run in different CI jobs so
1042
- // the requests to the skippable endpoint might be done at different times and their responses might be different.
1043
- // If the skippable endpoint is returning different suites and we filter the list of tests here,
1044
- // the base list of tests that is used for sharding might be different,
1045
- // causing the shards to potentially run the same suite.
1046
2201
  return testPaths
1047
2202
  }
1048
2203
  const { tests } = testPaths
@@ -1056,6 +2211,10 @@ function searchSourceWrapper (searchSourcePackage, frameworkVersion) {
1056
2211
 
1057
2212
  function getCliWrapper (isNewJestVersion) {
1058
2213
  return function cliWrapper (cli, jestVersion) {
2214
+ warnDeprecatedJestVersion(jestVersion)
2215
+ isJestCoverageBackfillSupported = !!jestVersion &&
2216
+ satisfies(jestVersion, MINIMUM_JEST_COVERAGE_BACKFILL_VERSION)
2217
+
1059
2218
  if (isNewJestVersion) {
1060
2219
  cli = shimmer.wrap(
1061
2220
  cli,
@@ -1065,23 +2224,24 @@ function getCliWrapper (isNewJestVersion) {
1065
2224
  )
1066
2225
  }
1067
2226
  return shimmer.wrap(cli, 'runCLI', runCLI => async function () {
1068
- let onDone
1069
- const configurationPromise = new Promise((resolve) => {
1070
- onDone = resolve
1071
- })
1072
2227
  if (!libraryConfigurationCh.hasSubscribers) {
1073
2228
  return runCLI.apply(this, arguments)
1074
2229
  }
1075
2230
 
1076
- libraryConfigurationCh.publish({ onDone, frameworkVersion: jestVersion })
2231
+ resetSuiteSkippingRunState()
2232
+ hasFinishedTestSession = false
1077
2233
 
2234
+ let shouldResetLibraryConfiguration = true
1078
2235
  try {
1079
- const { err, libraryConfig } = await configurationPromise
2236
+ const { err, libraryConfig } = await getChannelPromise(libraryConfigurationCh, {
2237
+ frameworkVersion: jestVersion,
2238
+ })
1080
2239
  if (!err) {
2240
+ shouldResetLibraryConfiguration = false
1081
2241
  isCodeCoverageEnabled = libraryConfig.isCodeCoverageEnabled
1082
- isSuitesSkippingEnabled = libraryConfig.isSuitesSkippingEnabled
1083
- isKeepingCoverageConfiguration =
1084
- libraryConfig.isKeepingCoverageConfiguration ?? isKeepingCoverageConfiguration
2242
+ isCoverageReportUploadEnabled = libraryConfig.isCoverageReportUploadEnabled
2243
+ isItrEnabled = libraryConfig.isItrEnabled
2244
+ isSuitesSkippingEnabled = isItrEnabled && libraryConfig.isSuitesSkippingEnabled
1085
2245
  isEarlyFlakeDetectionEnabled = libraryConfig.isEarlyFlakeDetectionEnabled
1086
2246
  earlyFlakeDetectionNumRetries = libraryConfig.earlyFlakeDetectionNumRetries
1087
2247
  earlyFlakeDetectionSlowTestRetries = libraryConfig.earlyFlakeDetectionSlowTestRetries ?? {}
@@ -1093,17 +2253,28 @@ function getCliWrapper (isNewJestVersion) {
1093
2253
  }
1094
2254
  } catch (err) {
1095
2255
  log.error('Jest library configuration error', err)
2256
+ } finally {
2257
+ if (shouldResetLibraryConfiguration) {
2258
+ resetLibraryConfiguration()
2259
+ }
1096
2260
  }
1097
2261
 
1098
- if (isKnownTestsEnabled) {
1099
- const knownTestsPromise = new Promise((resolve) => {
1100
- onDone = resolve
1101
- })
1102
-
1103
- knownTestsCh.publish({ onDone })
2262
+ const {
2263
+ knownTestsResponse,
2264
+ testManagementTestsResponse,
2265
+ skippableSuitesResponse,
2266
+ } = await getTestOptimizationRequestResults({
2267
+ isKnownTestsEnabled,
2268
+ isTestManagementTestsEnabled,
2269
+ isSuitesSkippingEnabled,
2270
+ getKnownTests: () => getChannelPromise(knownTestsCh),
2271
+ getTestManagementTests: () => getChannelPromise(testManagementTestsCh),
2272
+ getSkippableSuites: () => getChannelPromise(skippableSuitesCh),
2273
+ })
1104
2274
 
2275
+ if (isKnownTestsEnabled) {
1105
2276
  try {
1106
- const { err, knownTests: receivedKnownTests } = await knownTestsPromise
2277
+ const { err, knownTests: receivedKnownTests } = knownTestsResponse || await getChannelPromise(knownTestsCh)
1107
2278
  if (err) {
1108
2279
  // We disable EFD if there has been an error in the known tests request
1109
2280
  isEarlyFlakeDetectionEnabled = false
@@ -1117,16 +2288,19 @@ function getCliWrapper (isNewJestVersion) {
1117
2288
  }
1118
2289
 
1119
2290
  if (isSuitesSkippingEnabled) {
1120
- const skippableSuitesPromise = new Promise((resolve) => {
1121
- onDone = resolve
1122
- })
1123
-
1124
- skippableSuitesCh.publish({ onDone })
1125
-
1126
2291
  try {
1127
- const { err, skippableSuites: receivedSkippableSuites } = await skippableSuitesPromise
1128
- if (!err) {
2292
+ const {
2293
+ err,
2294
+ skippableSuites: receivedSkippableSuites,
2295
+ skippableSuitesCoverage: receivedSkippableSuitesCoverage,
2296
+ } = skippableSuitesResponse || await getChannelPromise(skippableSuitesCh)
2297
+ if (err) {
2298
+ skippableSuitesCoverage = {}
2299
+ skippedSuitesCoverage = {}
2300
+ } else {
1129
2301
  skippableSuites = receivedSkippableSuites
2302
+ skippableSuitesCoverage = receivedSkippableSuitesCoverage || {}
2303
+ skippedSuitesCoverage = {}
1130
2304
  }
1131
2305
  } catch (err) {
1132
2306
  log.error('Jest test-suite skippable error', err)
@@ -1134,14 +2308,9 @@ function getCliWrapper (isNewJestVersion) {
1134
2308
  }
1135
2309
 
1136
2310
  if (isTestManagementTestsEnabled) {
1137
- const testManagementTestsPromise = new Promise((resolve) => {
1138
- onDone = resolve
1139
- })
1140
-
1141
- testManagementTestsCh.publish({ onDone })
1142
-
1143
2311
  try {
1144
- const { err, testManagementTests: receivedTestManagementTests } = await testManagementTestsPromise
2312
+ const { err, testManagementTests: receivedTestManagementTests } =
2313
+ testManagementTestsResponse || await getChannelPromise(testManagementTestsCh)
1145
2314
  if (err) {
1146
2315
  isTestManagementTestsEnabled = false
1147
2316
  testManagementTests = {}
@@ -1155,14 +2324,8 @@ function getCliWrapper (isNewJestVersion) {
1155
2324
  }
1156
2325
 
1157
2326
  if (isImpactedTestsEnabled) {
1158
- const impactedTestsPromise = new Promise((resolve) => {
1159
- onDone = resolve
1160
- })
1161
-
1162
- modifiedFilesCh.publish({ onDone })
1163
-
1164
2327
  try {
1165
- const { err, modifiedFiles: receivedModifiedFiles } = await impactedTestsPromise
2328
+ const { err, modifiedFiles: receivedModifiedFiles } = await getChannelPromise(modifiedFilesCh)
1166
2329
  if (!err) {
1167
2330
  modifiedFiles = receivedModifiedFiles
1168
2331
  }
@@ -1172,13 +2335,15 @@ function getCliWrapper (isNewJestVersion) {
1172
2335
  }
1173
2336
 
1174
2337
  const processArgv = process.argv.slice(2).join(' ')
1175
- testSessionStartCh.publish({ command: `jest ${processArgv}`, frameworkVersion: jestVersion })
2338
+ testSessionStartCh.publish({
2339
+ command: `jest ${processArgv}`,
2340
+ frameworkVersion: jestVersion,
2341
+ })
1176
2342
 
1177
2343
  const result = await runCLI.apply(this, arguments)
1178
2344
 
1179
2345
  const {
1180
2346
  results: {
1181
- coverageMap,
1182
2347
  numFailedTestSuites,
1183
2348
  numFailedTests,
1184
2349
  numRuntimeErrorTestSuites = 0,
@@ -1193,17 +2358,6 @@ function getCliWrapper (isNewJestVersion) {
1193
2358
  const hasRunLevelFailure = runExecError != null || wasInterrupted === true
1194
2359
  const mustNotFlipSuccess = hasSuiteLevelFailures || hasRunLevelFailure
1195
2360
 
1196
- let testCodeCoverageLinesTotal
1197
-
1198
- if (isUserCodeCoverageEnabled) {
1199
- try {
1200
- const { pct, total } = coverageMap.getCoverageSummary().lines
1201
- testCodeCoverageLinesTotal = total === 0 ? 0 : pct
1202
- } catch {
1203
- // ignore errors
1204
- }
1205
- }
1206
-
1207
2361
  /**
1208
2362
  * If Early Flake Detection (EFD) is enabled the logic is as follows:
1209
2363
  * - If all attempts for a test are failing, the test has failed and we will let the test process fail.
@@ -1220,9 +2374,7 @@ function getCliWrapper (isNewJestVersion) {
1220
2374
  for (const { testResults, testFilePath } of result.results.testResults) {
1221
2375
  const suite = getTestSuitePath(testFilePath, result.globalConfig.rootDir)
1222
2376
  for (const { fullName } of testResults) {
1223
- const name = testSuiteAbsolutePathsWithFastCheck.has(testFilePath)
1224
- ? fullName.replace(SEED_SUFFIX_RE, '')
1225
- : fullName
2377
+ const name = removeSeedSuffixFromTestName(fullName)
1226
2378
  fullNameToSuite.set(name, suite)
1227
2379
  }
1228
2380
  }
@@ -1254,17 +2406,15 @@ function getCliWrapper (isNewJestVersion) {
1254
2406
  }
1255
2407
 
1256
2408
  let numFailedQuarantinedTests = 0
1257
- let numFailedQuarantinedOrDisabledAttemptedToFixTests = 0
2409
+ let numSuppressedQuarantinedTests = 0
1258
2410
  if (isTestManagementTestsEnabled) {
1259
2411
  const failedTests = result
1260
2412
  .results
1261
2413
  .testResults.flatMap(({ testResults, testFilePath: testSuiteAbsolutePath }) => (
1262
2414
  testResults.map(({ fullName: testName, status }) => (
1263
2415
  {
1264
- // Strip @fast-check/jest seed suffix so the name matches what was reported via TEST_NAME
1265
- testName: testSuiteAbsolutePathsWithFastCheck.has(testSuiteAbsolutePath)
1266
- ? testName.replace(SEED_SUFFIX_RE, '')
1267
- : testName,
2416
+ // Strip seed suffix so the name matches what was reported via TEST_NAME.
2417
+ testName: removeSeedSuffixFromTestName(testName),
1268
2418
  testSuiteAbsolutePath,
1269
2419
  status,
1270
2420
  }
@@ -1281,55 +2431,73 @@ function getCliWrapper (isNewJestVersion) {
1281
2431
  ?.tests
1282
2432
  ?.[testName]
1283
2433
  ?.properties
1284
- // This uses `attempt_to_fix` because this is always the main process and it's not formatted in camelCase
1285
- if (testManagementTest?.attempt_to_fix && (testManagementTest?.quarantined || testManagementTest?.disabled)) {
1286
- numFailedQuarantinedOrDisabledAttemptedToFixTests++
1287
- quarantineIgnoredNames.push(`${testSuite} › ${testName}`)
1288
- } else if (testManagementTest?.quarantined) {
2434
+ if (testManagementTest?.quarantined && !testManagementTest?.attempt_to_fix) {
1289
2435
  numFailedQuarantinedTests++
1290
2436
  quarantineIgnoredNames.push(`${testSuite} › ${testName}`)
1291
2437
  }
1292
2438
  }
1293
2439
 
2440
+ // Include quarantined tests whose errors were suppressed at test_done time.
2441
+ // These tests don't appear as failed in Jest's results because their errors were cleared
2442
+ // to prevent --bail from stopping the run, but they should still be counted for the summary.
2443
+ for (const name of quarantinedFailingTests) {
2444
+ if (!quarantineIgnoredNames.includes(name)) {
2445
+ numSuppressedQuarantinedTests++
2446
+ quarantineIgnoredNames.push(name)
2447
+ }
2448
+ }
2449
+ quarantinedFailingTests.clear()
2450
+
1294
2451
  // If every test that failed was quarantined, we'll consider the suite passed
1295
- // Note that if a test is attempted to fix,
1296
- // it's considered quarantined both if it's disabled and if it's quarantined
1297
- // (it'll run but its status is ignored)
2452
+ // Attempt-to-fix tests ignore quarantine/disabled suppression and keep their framework result.
1298
2453
  // Skip if EFD block already flipped (to avoid logging twice)
2454
+ // Only use visible failures (from Jest results) for the flip check.
2455
+ // Suppressed quarantine failures are not in numFailedTests.
2456
+ const visibleQuarantineFailures = numFailedQuarantinedTests
1299
2457
  if (
1300
2458
  !result.results.success &&
1301
2459
  !mustNotFlipSuccess &&
1302
- (numFailedQuarantinedOrDisabledAttemptedToFixTests !== 0 || numFailedQuarantinedTests !== 0) &&
1303
- result.results.numFailedTests ===
1304
- numFailedQuarantinedTests + numFailedQuarantinedOrDisabledAttemptedToFixTests
2460
+ visibleQuarantineFailures !== 0 &&
2461
+ result.results.numFailedTests === visibleQuarantineFailures
1305
2462
  ) {
1306
2463
  result.results.success = true
1307
- ignoredFailuresSummary = {
1308
- efdNames: [],
1309
- quarantineNames: quarantineIgnoredNames,
1310
- totalCount: numFailedQuarantinedTests + numFailedQuarantinedOrDisabledAttemptedToFixTests,
2464
+ }
2465
+
2466
+ const totalQuarantineFailures = visibleQuarantineFailures + numSuppressedQuarantinedTests
2467
+ if (totalQuarantineFailures > 0) {
2468
+ if (ignoredFailuresSummary) {
2469
+ ignoredFailuresSummary.quarantineNames = quarantineIgnoredNames
2470
+ ignoredFailuresSummary.totalCount += totalQuarantineFailures
2471
+ } else {
2472
+ ignoredFailuresSummary = {
2473
+ efdNames: [],
2474
+ quarantineNames: quarantineIgnoredNames,
2475
+ totalCount: totalQuarantineFailures,
2476
+ }
1311
2477
  }
1312
2478
  }
1313
2479
  }
1314
2480
 
1315
2481
  // Combined check: if all failed tests are accounted for by EFD (flaky retries) and/or quarantine,
1316
2482
  // we should consider the suite passed even when neither check alone covers all failures.
2483
+ // Only visible failures (in Jest results) are compared — suppressed quarantine failures
2484
+ // are already removed from numFailedTests at test_done time.
1317
2485
  if (
1318
2486
  !result.results.success &&
1319
2487
  !mustNotFlipSuccess &&
1320
2488
  (isEarlyFlakeDetectionEnabled || isTestManagementTestsEnabled)
1321
2489
  ) {
1322
- const totalIgnoredFailures =
1323
- numEfdFailedTestsToIgnore + numFailedQuarantinedTests + numFailedQuarantinedOrDisabledAttemptedToFixTests
2490
+ const visibleIgnoredFailures =
2491
+ numEfdFailedTestsToIgnore + numFailedQuarantinedTests
1324
2492
  if (
1325
- totalIgnoredFailures !== 0 &&
1326
- result.results.numFailedTests === totalIgnoredFailures
2493
+ visibleIgnoredFailures !== 0 &&
2494
+ result.results.numFailedTests === visibleIgnoredFailures
1327
2495
  ) {
1328
2496
  result.results.success = true
1329
2497
  ignoredFailuresSummary = {
1330
2498
  efdNames: efdIgnoredNames,
1331
2499
  quarantineNames: quarantineIgnoredNames,
1332
- totalCount: totalIgnoredFailures,
2500
+ totalCount: visibleIgnoredFailures + numSuppressedQuarantinedTests,
1333
2501
  }
1334
2502
  }
1335
2503
  }
@@ -1343,43 +2511,9 @@ function getCliWrapper (isNewJestVersion) {
1343
2511
  error = new Error(`Failed test suites: ${numFailedTestSuites}. Failed tests: ${numFailedTests}`)
1344
2512
  }
1345
2513
 
1346
- let timeoutId
1347
-
1348
- // Pass the resolve callback to defer it to DC listener
1349
- const flushPromise = new Promise((resolve) => {
1350
- onDone = () => {
1351
- clearTimeout(timeoutId)
1352
- resolve()
1353
- }
1354
- })
1355
-
1356
- const timeoutPromise = new Promise((resolve) => {
1357
- timeoutId = realSetTimeout(() => {
1358
- resolve('timeout')
1359
- }, FLUSH_TIMEOUT).unref()
1360
- })
1361
-
1362
- testSessionFinishCh.publish({
1363
- status,
1364
- isSuitesSkipped,
1365
- isSuitesSkippingEnabled,
1366
- isCodeCoverageEnabled,
1367
- testCodeCoverageLinesTotal,
1368
- numSkippedSuites,
1369
- hasUnskippableSuites,
1370
- hasForcedToRunSuites,
1371
- error,
1372
- isEarlyFlakeDetectionEnabled,
1373
- isEarlyFlakeDetectionFaulty,
1374
- isTestManagementTestsEnabled,
1375
- onDone,
1376
- })
1377
-
1378
- const waitingResult = await Promise.race([flushPromise, timeoutPromise])
1379
-
1380
- if (waitingResult === 'timeout') {
1381
- log.error('Timeout waiting for the tracer to flush')
1382
- }
2514
+ await waitForTestSessionFinish(getTestSessionFinishPayload(status, error, {
2515
+ ...getTestSessionCoveragePayload(result.results, result.globalConfig?.rootDir),
2516
+ }))
1383
2517
 
1384
2518
  if (codeCoverageReportCh.hasSubscribers) {
1385
2519
  const rootDir = result.globalConfig?.rootDir || process.cwd()
@@ -1388,9 +2522,9 @@ function getCliWrapper (isNewJestVersion) {
1388
2522
  })
1389
2523
  }
1390
2524
 
1391
- logSessionSummary(ignoredFailuresSummary)
2525
+ logSessionSummary(ignoredFailuresSummary, getAttemptToFixExecutionsFromJestResults(result))
1392
2526
 
1393
- numSkippedSuites = 0
2527
+ resetSuiteSkippingRunState()
1394
2528
 
1395
2529
  return result
1396
2530
  }, {
@@ -1399,32 +2533,49 @@ function getCliWrapper (isNewJestVersion) {
1399
2533
  }
1400
2534
  }
1401
2535
 
1402
- function coverageReporterWrapper (coverageReporter) {
1403
- const CoverageReporter = coverageReporter.default ?? coverageReporter
2536
+ function shouldWaitForTestSuiteFinish (environment) {
2537
+ return isJestWorker && environment.globalConfig?.workerIdleMemoryLimit !== undefined
2538
+ }
1404
2539
 
1405
- /**
1406
- * If ITR is active, we're running fewer tests, so of course the total code coverage is reduced.
1407
- * This calculation adds no value, so we'll skip it, as long as the user has not manually opted in to code coverage,
1408
- * in which case we'll leave it.
1409
- */
1410
- // `_addUntestedFiles` is an async function
1411
- shimmer.wrap(CoverageReporter.prototype, '_addUntestedFiles', addUntestedFiles => function () {
1412
- if (isKeepingCoverageConfiguration) {
1413
- return addUntestedFiles.apply(this, arguments)
1414
- }
1415
- if (isCodeCoverageEnabledBecauseOfUs) {
1416
- return Promise.resolve()
1417
- }
1418
- return addUntestedFiles.apply(this, arguments)
2540
+ function publishTestSuiteFinish (payload, waitForFinish) {
2541
+ if (!testSuiteFinishCh.hasSubscribers) return
2542
+
2543
+ if (!waitForFinish) {
2544
+ testSuiteFinishCh.publish(payload)
2545
+ return
2546
+ }
2547
+
2548
+ return new Promise(resolve => {
2549
+ testSuiteFinishCh.publish({
2550
+ ...payload,
2551
+ waitForFinish,
2552
+ onDone: resolve,
2553
+ })
1419
2554
  })
2555
+ }
1420
2556
 
1421
- return coverageReporter
2557
+ function cleanupTestSuiteState (testSuiteAbsolutePath) {
2558
+ testSuiteMockedFiles.delete(testSuiteAbsolutePath)
2559
+ testSuiteJestObjects.delete(testSuiteAbsolutePath)
2560
+ }
2561
+
2562
+ /**
2563
+ * Rechecks custom handlers after Jest has finished constructing the environment.
2564
+ *
2565
+ * @param {object} environment
2566
+ * @returns {void}
2567
+ */
2568
+ function wrapEnvironmentCustomHandleTestEvent (environment) {
2569
+ const datadogHandleTestEvent = environment[DD_JEST_HANDLE_TEST_EVENT_DATADOG]
2570
+ if (typeof environment.wrapCustomHandleTestEvent === 'function' && datadogHandleTestEvent) {
2571
+ environment.wrapCustomHandleTestEvent(datadogHandleTestEvent)
2572
+ }
1422
2573
  }
1423
2574
 
1424
2575
  addHook({
1425
2576
  name: '@jest/core',
1426
2577
  file: 'build/TestScheduler.js',
1427
- versions: ['>=27.0.0'],
2578
+ versions: [MINIMUM_JEST_TEST_SCHEDULER_VERSION],
1428
2579
  }, (testSchedulerPackage, frameworkVersion) => {
1429
2580
  const oldCreateTestScheduler = testSchedulerPackage.createTestScheduler
1430
2581
  const newCreateTestScheduler = async function () {
@@ -1440,24 +2591,23 @@ addHook({
1440
2591
  return testSchedulerPackage
1441
2592
  })
1442
2593
 
1443
- addHook({
1444
- name: '@jest/core',
1445
- file: 'build/TestScheduler.js',
1446
- versions: ['>=24.8.0 <27.0.0'],
1447
- }, (testSchedulerPackage, frameworkVersion) => {
1448
- shimmer.wrap(
1449
- testSchedulerPackage.default.prototype,
1450
- 'scheduleTests', scheduleTests => getWrappedScheduleTests(scheduleTests, frameworkVersion)
1451
- )
1452
- return testSchedulerPackage
1453
- })
2594
+ if (DD_MAJOR < 6) {
2595
+ addHook({
2596
+ name: '@jest/core',
2597
+ file: 'build/TestScheduler.js',
2598
+ versions: ['>=24.8.0 <27.0.0'],
2599
+ }, (testSchedulerPackage, frameworkVersion) => {
2600
+ shimmer.wrap(
2601
+ testSchedulerPackage.default.prototype,
2602
+ 'scheduleTests', scheduleTests => getWrappedScheduleTests(scheduleTests, frameworkVersion)
2603
+ )
2604
+ return testSchedulerPackage
2605
+ })
2606
+ }
1454
2607
 
1455
- addHook({
1456
- name: '@jest/test-sequencer',
1457
- versions: ['>=28'],
1458
- }, (sequencerPackage, frameworkVersion) => {
1459
- shimmer.wrap(sequencerPackage.default.prototype, 'shard', shard => function () {
1460
- const shardedTests = shard.apply(this, arguments)
2608
+ function testSequencerWrapper (sequencerPackage, frameworkVersion) {
2609
+ shimmer.wrap(sequencerPackage.default.prototype, 'shard', shard => function (...args) {
2610
+ const shardedTests = shard.apply(this, args)
1461
2611
 
1462
2612
  if (!shardedTests.length || !isSuitesSkippingEnabled || !skippableSuites.length) {
1463
2613
  return shardedTests
@@ -1468,31 +2618,23 @@ addHook({
1468
2618
  return applySuiteSkipping(shardedTests, rootDir, frameworkVersion)
1469
2619
  })
1470
2620
  return sequencerPackage
1471
- })
1472
-
1473
- addHook({
1474
- name: '@jest/reporters',
1475
- file: 'build/coverage_reporter.js',
1476
- versions: ['>=24.8.0 <26.6.2'],
1477
- }, coverageReporterWrapper)
2621
+ }
1478
2622
 
1479
2623
  addHook({
1480
- name: '@jest/reporters',
1481
- file: 'build/CoverageReporter.js',
1482
- versions: ['>=26.6.2'],
1483
- }, coverageReporterWrapper)
2624
+ name: '@jest/test-sequencer',
2625
+ versions: ['>=28'],
2626
+ }, testSequencerWrapper)
1484
2627
 
1485
2628
  addHook({
1486
- name: '@jest/reporters',
1487
- versions: ['>=30.0.0'],
1488
- }, (reporters) => {
1489
- return shimmer.wrap(reporters, 'CoverageReporter', coverageReporterWrapper, { replaceGetter: true })
1490
- })
2629
+ name: '@jest/test-sequencer',
2630
+ file: 'build/index.js',
2631
+ versions: ['>=28'],
2632
+ }, testSequencerWrapper)
1491
2633
 
1492
2634
  addHook({
1493
2635
  name: '@jest/core',
1494
2636
  file: 'build/cli/index.js',
1495
- versions: ['>=24.8.0 <30.0.0'],
2637
+ versions: [MINIMUM_JEST_VERSION_BEFORE_30],
1496
2638
  }, getCliWrapper(false))
1497
2639
 
1498
2640
  addHook({
@@ -1500,13 +2642,41 @@ addHook({
1500
2642
  versions: ['>=30.0.0'],
1501
2643
  }, getCliWrapper(true))
1502
2644
 
2645
+ addHook({
2646
+ name: '@jest/core',
2647
+ file: 'build/ReporterDispatcher.js',
2648
+ versions: [MINIMUM_JEST_VERSION],
2649
+ }, reporterDispatcherWrapper)
2650
+
2651
+ if (DD_MAJOR < 6) {
2652
+ addHook({
2653
+ name: '@jest/reporters',
2654
+ file: 'build/coverage_reporter.js',
2655
+ versions: ['>=24.8.0 <26.6.2'],
2656
+ }, coverageReporterWrapper)
2657
+ }
2658
+
2659
+ addHook({
2660
+ name: '@jest/reporters',
2661
+ versions: ['>=30.0.0'],
2662
+ }, reportersWrapper)
2663
+
2664
+ addHook({
2665
+ name: '@jest/reporters',
2666
+ file: 'build/CoverageReporter.js',
2667
+ versions: [DD_MAJOR >= 6 ? '>=28.0.0' : '>=26.6.2'],
2668
+ }, coverageReporterWrapper)
2669
+
1503
2670
  function jestAdapterWrapper (jestAdapter, jestVersion) {
1504
2671
  const adapter = jestAdapter.default ?? jestAdapter
1505
- const newAdapter = shimmer.wrapFunction(adapter, adapter => function () {
1506
- const environment = arguments[2]
2672
+ const newAdapter = shimmer.wrapFunction(adapter, adapter => function (...args) {
2673
+ const environment = args[2]
1507
2674
  if (!environment || !environment.testEnvironmentOptions) {
1508
- return adapter.apply(this, arguments)
2675
+ return adapter.apply(this, args)
1509
2676
  }
2677
+
2678
+ wrapEnvironmentCustomHandleTestEvent(environment)
2679
+
1510
2680
  testSuiteStartCh.publish({
1511
2681
  testSuite: environment.testSuite,
1512
2682
  testEnvironmentOptions: environment.testEnvironmentOptions,
@@ -1515,7 +2685,7 @@ function jestAdapterWrapper (jestAdapter, jestVersion) {
1515
2685
  frameworkVersion: jestVersion,
1516
2686
  testSuiteAbsolutePath: environment.testSuiteAbsolutePath,
1517
2687
  })
1518
- return adapter.apply(this, arguments).then(suiteResults => {
2688
+ return adapter.apply(this, args).then(suiteResults => {
1519
2689
  const { numFailingTests, skipped, failureMessage: errorMessage } = suiteResults
1520
2690
  let status = 'pass'
1521
2691
  if (skipped) {
@@ -1532,10 +2702,13 @@ function jestAdapterWrapper (jestAdapter, jestVersion) {
1532
2702
  if (environment.testEnvironmentOptions?._ddTestCodeCoverageEnabled) {
1533
2703
  const root = environment.repositoryRoot || environment.rootDir
1534
2704
 
1535
- const getFilesWithPath = (files) => files.map(file => getTestSuitePath(file, root))
1536
-
1537
- const coverageFiles = getFilesWithPath(getCoveredFilenamesFromCoverage(environment.global.__coverage__))
1538
- const mockedFiles = getFilesWithPath(testSuiteMockedFiles.get(environment.testSuiteAbsolutePath) || [])
2705
+ const coverageFiles = getCoveredFilesFromCoverage(environment.global.__coverage__)
2706
+ .map(file => ({
2707
+ ...file,
2708
+ filename: getTestSuitePath(file.filename, root),
2709
+ }))
2710
+ const mockedFiles = getMockedFiles(environment.testSuiteAbsolutePath)
2711
+ .map(file => getTestSuitePath(file, root))
1539
2712
 
1540
2713
  testSuiteCodeCoverageCh.publish({
1541
2714
  coverageFiles,
@@ -1544,19 +2717,51 @@ function jestAdapterWrapper (jestAdapter, jestVersion) {
1544
2717
  testSuiteAbsolutePath: environment.testSuiteAbsolutePath,
1545
2718
  })
1546
2719
  }
1547
- testSuiteFinishCh.publish({ status, errorMessage, testSuiteAbsolutePath: environment.testSuiteAbsolutePath })
2720
+ const waitForFinish = shouldWaitForTestSuiteFinish(environment)
2721
+ const finishPayload = {
2722
+ status,
2723
+ errorMessage,
2724
+ testSuiteAbsolutePath: environment.testSuiteAbsolutePath,
2725
+ }
2726
+ if (waitForFinish) {
2727
+ const finishPromise = publishTestSuiteFinish(finishPayload, waitForFinish)
2728
+ if (finishPromise) {
2729
+ return finishPromise.then(() => {
2730
+ // Cleanup per-suite state to avoid memory leaks
2731
+ cleanupTestSuiteState(environment.testSuiteAbsolutePath)
2732
+
2733
+ return suiteResults
2734
+ })
2735
+ }
2736
+ }
2737
+ publishTestSuiteFinish(finishPayload, waitForFinish)
1548
2738
 
1549
2739
  // Cleanup per-suite state to avoid memory leaks
1550
- testSuiteMockedFiles.delete(environment.testSuiteAbsolutePath)
1551
- testSuiteJestObjects.delete(environment.testSuiteAbsolutePath)
2740
+ cleanupTestSuiteState(environment.testSuiteAbsolutePath)
1552
2741
 
1553
2742
  return suiteResults
1554
2743
  }).catch(error => {
1555
- testSuiteFinishCh.publish({ status: 'fail', error, testSuiteAbsolutePath: environment.testSuiteAbsolutePath })
2744
+ const waitForFinish = shouldWaitForTestSuiteFinish(environment)
2745
+ const finishPayload = {
2746
+ status: 'fail',
2747
+ error,
2748
+ testSuiteAbsolutePath: environment.testSuiteAbsolutePath,
2749
+ }
2750
+ if (waitForFinish) {
2751
+ const finishPromise = publishTestSuiteFinish(finishPayload, waitForFinish)
2752
+ if (finishPromise) {
2753
+ return finishPromise.then(() => {
2754
+ // Cleanup per-suite state to avoid memory leaks
2755
+ cleanupTestSuiteState(environment.testSuiteAbsolutePath)
2756
+
2757
+ throw error
2758
+ })
2759
+ }
2760
+ }
2761
+ publishTestSuiteFinish(finishPayload, waitForFinish)
1556
2762
 
1557
2763
  // Cleanup per-suite state to avoid memory leaks
1558
- testSuiteMockedFiles.delete(environment.testSuiteAbsolutePath)
1559
- testSuiteJestObjects.delete(environment.testSuiteAbsolutePath)
2764
+ cleanupTestSuiteState(environment.testSuiteAbsolutePath)
1560
2765
 
1561
2766
  throw error
1562
2767
  })
@@ -1579,45 +2784,54 @@ addHook({
1579
2784
  addHook({
1580
2785
  name: 'jest-circus',
1581
2786
  file: 'build/legacy-code-todo-rewrite/jestAdapter.js',
1582
- versions: ['>=24.8.0'],
2787
+ versions: [MINIMUM_JEST_VERSION],
1583
2788
  }, jestAdapterWrapper)
1584
2789
 
1585
2790
  function configureTestEnvironment (readConfigsResult) {
1586
- const { configs } = readConfigsResult
1587
- testSessionConfigurationCh.publish(configs.map(config => config.testEnvironmentOptions))
1588
- // We can't directly use isCodeCoverageEnabled when reporting coverage in `jestAdapterWrapper`
1589
- // because `jestAdapterWrapper` runs in a different process. We have to go through `testEnvironmentOptions`
1590
- for (const config of configs) {
1591
- config.testEnvironmentOptions._ddTestCodeCoverageEnabled = isCodeCoverageEnabled
1592
- }
1593
-
2791
+ repositoryRoot = getJestRepositoryRoot(readConfigsResult)
1594
2792
  isUserCodeCoverageEnabled = !!readConfigsResult.globalConfig.collectCoverage
1595
- isCodeCoverageEnabledBecauseOfUs = isCodeCoverageEnabled && !isUserCodeCoverageEnabled
1596
-
1597
- if (readConfigsResult.globalConfig.forceExit) {
1598
- log.warn("Jest's '--forceExit' flag has been passed. This may cause loss of data.")
1599
- }
2793
+ const isCodeCoverageEnabledBecauseOfUs = shouldCollectJestCoverageForTia() && !isUserCodeCoverageEnabled
1600
2794
 
1601
2795
  if (isCodeCoverageEnabledBecauseOfUs) {
1602
- const globalConfig = {
2796
+ readConfigsResult.globalConfig = {
1603
2797
  ...readConfigsResult.globalConfig,
1604
2798
  collectCoverage: true,
2799
+ coverageReporters: ['none'],
1605
2800
  }
1606
- readConfigsResult.globalConfig = globalConfig
2801
+ readConfigsResult.configs = readConfigsResult.configs.map(config => ({
2802
+ ...config,
2803
+ coverageReporters: ['none'],
2804
+ }))
1607
2805
  }
2806
+
2807
+ // We can't directly use the parent process flags when reporting suite coverage in `jestAdapterWrapper`
2808
+ // because `jestAdapterWrapper` runs in a different process. We have to go through `testEnvironmentOptions`.
2809
+ const configs = readConfigsResult.configs.map(config => {
2810
+ const testEnvironmentOptions = config.testEnvironmentOptions || {}
2811
+ testEnvironmentOptions._ddRepositoryRoot = repositoryRoot
2812
+ testEnvironmentOptions._ddTestCodeCoverageEnabled = shouldReportJestSuiteCoverageForTia()
2813
+
2814
+ return {
2815
+ ...config,
2816
+ testEnvironmentOptions,
2817
+ }
2818
+ })
2819
+ readConfigsResult.configs = configs
2820
+ testSessionConfigurationCh.publish(readConfigsResult.configs.map(config => config.testEnvironmentOptions))
2821
+ repositoryRoot = getJestRepositoryRoot(readConfigsResult)
2822
+
2823
+ if (readConfigsResult.globalConfig.forceExit) {
2824
+ log.warn("Jest's '--forceExit' flag has been passed. This may cause loss of data.")
2825
+ }
2826
+
2827
+ readConfigsResult.globalConfig = addDatadogBailReporter(readConfigsResult.globalConfig)
2828
+
1608
2829
  if (isSuitesSkippingEnabled) {
1609
2830
  // If suite skipping is enabled, we pass `passWithNoTests` in case every test gets skipped.
1610
2831
  const globalConfig = {
1611
2832
  ...readConfigsResult.globalConfig,
1612
2833
  passWithNoTests: true,
1613
2834
  }
1614
- if (isCodeCoverageEnabledBecauseOfUs && !isKeepingCoverageConfiguration) {
1615
- globalConfig.coverageReporters = ['none']
1616
- readConfigsResult.configs = configs.map(config => ({
1617
- ...config,
1618
- coverageReporters: ['none'],
1619
- }))
1620
- }
1621
2835
  readConfigsResult.globalConfig = globalConfig
1622
2836
  }
1623
2837
 
@@ -1633,8 +2847,8 @@ function jestConfigAsyncWrapper (jestConfig) {
1633
2847
  }
1634
2848
 
1635
2849
  function jestConfigSyncWrapper (jestConfig) {
1636
- return shimmer.wrap(jestConfig, 'readConfigs', readConfigs => function () {
1637
- const readConfigsResult = readConfigs.apply(this, arguments)
2850
+ return shimmer.wrap(jestConfig, 'readConfigs', readConfigs => function (...args) {
2851
+ const readConfigsResult = readConfigs.apply(this, args)
1638
2852
  configureTestEnvironment(readConfigsResult)
1639
2853
  return readConfigsResult
1640
2854
  })
@@ -1652,8 +2866,10 @@ const DD_TEST_ENVIRONMENT_OPTION_KEYS = [
1652
2866
  '_ddIsEarlyFlakeDetectionEnabled',
1653
2867
  '_ddEarlyFlakeDetectionSlowTestRetries',
1654
2868
  '_ddRepositoryRoot',
2869
+ '_ddTestCodeCoverageEnabled',
1655
2870
  '_ddIsFlakyTestRetriesEnabled',
1656
2871
  '_ddFlakyTestRetriesCount',
2872
+ '_ddItrSkippingEnabledTags',
1657
2873
  '_ddIsDiEnabled',
1658
2874
  '_ddIsKnownTestsEnabled',
1659
2875
  '_ddIsTestManagementTestsEnabled',
@@ -1716,7 +2932,7 @@ function wrapCreateScriptTransformer (createScriptTransformer) {
1716
2932
 
1717
2933
  addHook({
1718
2934
  name: '@jest/transform',
1719
- versions: ['>=24.8.0 <30.0.0'],
2935
+ versions: [MINIMUM_JEST_VERSION_BEFORE_30],
1720
2936
  file: 'build/ScriptTransformer.js',
1721
2937
  }, transformPackage => {
1722
2938
  transformPackage.createScriptTransformer = wrapCreateScriptTransformer(transformPackage.createScriptTransformer)
@@ -1736,20 +2952,30 @@ addHook({
1736
2952
  */
1737
2953
  addHook({
1738
2954
  name: '@jest/core',
1739
- versions: ['>=24.8.0 <30.0.0'],
2955
+ versions: [MINIMUM_JEST_VERSION_BEFORE_30],
1740
2956
  file: 'build/SearchSource.js',
1741
2957
  }, searchSourceWrapper)
1742
2958
 
2959
+ addHook({
2960
+ name: 'jest-each',
2961
+ versions: [MINIMUM_JEST_VERSION],
2962
+ }, jestEach => {
2963
+ cacheJestEachBind(jestEach)
2964
+ return jestEach
2965
+ })
2966
+
1743
2967
  // from 25.1.0 on, readConfigs becomes async
1744
2968
  addHook({
1745
2969
  name: 'jest-config',
1746
- versions: ['>=25.1.0'],
2970
+ versions: [MINIMUM_JEST_CONFIG_ASYNC_VERSION],
1747
2971
  }, jestConfigAsyncWrapper)
1748
2972
 
1749
- addHook({
1750
- name: 'jest-config',
1751
- versions: ['24.8.0 - 24.9.0'],
1752
- }, jestConfigSyncWrapper)
2973
+ if (DD_MAJOR < 6) {
2974
+ addHook({
2975
+ name: 'jest-config',
2976
+ versions: ['24.8.0 - 24.9.0'],
2977
+ }, jestConfigSyncWrapper)
2978
+ }
1753
2979
 
1754
2980
  const LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE = new Set([
1755
2981
  'selenium-webdriver',
@@ -1762,39 +2988,180 @@ const LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE = new Set([
1762
2988
  'winston',
1763
2989
  ])
1764
2990
 
2991
+ function recordMockedFile (suiteFilePath, moduleName) {
2992
+ if (!suiteFilePath || typeof moduleName !== 'string') return
2993
+
2994
+ const existingMockedFiles = testSuiteMockedFiles.get(suiteFilePath) || []
2995
+ const suiteDir = path.dirname(suiteFilePath)
2996
+ const mockPath = path.resolve(suiteDir, moduleName)
2997
+ existingMockedFiles.push(mockPath)
2998
+ testSuiteMockedFiles.set(suiteFilePath, existingMockedFiles)
2999
+ }
3000
+
3001
+ const JEST_STATIC_MOCK_CALL_RE = /\bjest\.(?:mock|doMock|unstable_mockModule)\(\s*(['"`])([^'"`]+)\1/g
3002
+
3003
+ function getStaticMockedFiles (suiteFilePath) {
3004
+ if (!suiteFilePath) return []
3005
+
3006
+ const mockedFiles = []
3007
+ try {
3008
+ const source = readFileSync(suiteFilePath, 'utf8')
3009
+ let match
3010
+ JEST_STATIC_MOCK_CALL_RE.lastIndex = 0
3011
+ while ((match = JEST_STATIC_MOCK_CALL_RE.exec(source)) !== null) {
3012
+ mockedFiles.push(path.resolve(path.dirname(suiteFilePath), match[2]))
3013
+ }
3014
+ } catch {
3015
+ // ignore errors
3016
+ }
3017
+
3018
+ return mockedFiles
3019
+ }
3020
+
3021
+ function getMockedFiles (suiteFilePath) {
3022
+ const mockedFiles = testSuiteMockedFiles.get(suiteFilePath)
3023
+ const staticMockedFiles = getStaticMockedFiles(suiteFilePath)
3024
+
3025
+ if (mockedFiles?.length) {
3026
+ return [...new Set([...mockedFiles, ...staticMockedFiles])]
3027
+ }
3028
+ return staticMockedFiles
3029
+ }
3030
+
3031
+ function wrapJestObject (jestObject, suiteFilePath) {
3032
+ if (!jestObject || !suiteFilePath || wrappedJestObjects.has(jestObject)) return
3033
+
3034
+ testSuiteJestObjects.set(suiteFilePath, jestObject)
3035
+ wrappedJestObjects.add(jestObject)
3036
+
3037
+ shimmer.wrap(jestObject, 'mock', mock => function (moduleName) {
3038
+ // If the library is mocked with `jest.mock`, we don't want to bypass jest's own require engine
3039
+ if (LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE.has(moduleName)) {
3040
+ LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE.delete(moduleName)
3041
+ }
3042
+ recordMockedFile(suiteFilePath, moduleName)
3043
+ return mock.apply(this, arguments)
3044
+ })
3045
+ }
3046
+
3047
+ function wrapJestGlobalsForRuntime (runtime) {
3048
+ const jestGlobals = runtime?.jestGlobals
3049
+ if (!jestGlobals || wrappedJestGlobals.has(jestGlobals) || typeof jestGlobals.jestObjectFor !== 'function') {
3050
+ return
3051
+ }
3052
+
3053
+ wrappedJestGlobals.add(jestGlobals)
3054
+ shimmer.wrap(jestGlobals, 'jestObjectFor', jestObjectFor => function (from) {
3055
+ const jestObject = jestObjectFor.apply(this, arguments)
3056
+ wrapJestObject(jestObject, from)
3057
+ return jestObject
3058
+ })
3059
+ }
3060
+
3061
+ function wrapConcurrentJestGlobalsForRuntime (runtime, jestGlobals) {
3062
+ const environment = testSuiteDatadogEnvironments.get(runtime?._testPath)
3063
+ environment?.wrapConcurrentTestGlobals(jestGlobals?.test, environment.concurrentTestState)
3064
+ }
3065
+
3066
+ function cacheJestEachBind (jestEach) {
3067
+ if (typeof jestEach?.bind === 'function') {
3068
+ jestEachBind = jestEach.bind
3069
+ }
3070
+ }
3071
+
3072
+ function getLastLoggedReferenceError (runtime) {
3073
+ const loggedReferenceErrors = runtime?.loggedReferenceErrors
3074
+ if (!loggedReferenceErrors?.size) return
3075
+ return [...loggedReferenceErrors].pop()
3076
+ }
3077
+
3078
+ function publishRuntimeReferenceError (runtime, errorMessage) {
3079
+ if (!errorMessage || !runtime?._testPath) return
3080
+
3081
+ let publishedErrors = publishedRuntimeReferenceErrors.get(runtime)
3082
+ if (!publishedErrors) {
3083
+ publishedErrors = new Set()
3084
+ publishedRuntimeReferenceErrors.set(runtime, publishedErrors)
3085
+ }
3086
+ if (publishedErrors.has(errorMessage)) return
3087
+
3088
+ publishedErrors.add(errorMessage)
3089
+ testSuiteErrorCh.publish({
3090
+ errorMessage,
3091
+ testSuiteAbsolutePath: runtime._testPath,
3092
+ })
3093
+ }
3094
+
3095
+ function isBetweenTestsReferenceError (error) {
3096
+ return error?.name === 'ReferenceError' &&
3097
+ typeof error.message === 'string' &&
3098
+ error.message.includes('outside of the scope of the test code')
3099
+ }
3100
+
3101
+ function reportBetweenTestsReferenceError (runtime, moduleName, originalErrorMessage) {
3102
+ if (typeof moduleName !== 'string') return false
3103
+
3104
+ const fallbackErrorMessage = moduleName.startsWith('node:') || builtinModules.includes(moduleName)
3105
+ ? 'You are trying to access a Node.js module outside of the scope of the test code.'
3106
+ : 'You are trying to `require` a file after the Jest environment has been torn down.'
3107
+ const errorMessage = originalErrorMessage || fallbackErrorMessage
3108
+
3109
+ if (typeof runtime._logFormattedReferenceError === 'function') {
3110
+ runtime._logFormattedReferenceError(errorMessage)
3111
+ }
3112
+ publishRuntimeReferenceError(runtime, getLastLoggedReferenceError(runtime) || errorMessage)
3113
+ process.exitCode = 1
3114
+ return true
3115
+ }
3116
+
3117
+ function requireOutsideJestRequireEngine (runtime, moduleName) {
3118
+ if (typeof runtime._requireCoreModule === 'function') {
3119
+ return runtime._requireCoreModule(moduleName)
3120
+ }
3121
+ return require(moduleName)
3122
+ }
3123
+
3124
+ function formatDefaultStackTrace (error, structuredStackTrace) {
3125
+ const errorString = Error.prototype.toString.call(error)
3126
+ if (structuredStackTrace.length === 0) return errorString
3127
+
3128
+ return `${errorString}\n at ${structuredStackTrace.join('\n at ')}`
3129
+ }
3130
+
1765
3131
  addHook({
1766
3132
  name: 'jest-runtime',
1767
- versions: ['>=24.8.0'],
3133
+ versions: [MINIMUM_JEST_VERSION],
1768
3134
  }, (runtimePackage) => {
1769
3135
  const Runtime = runtimePackage.default ?? runtimePackage
1770
3136
 
1771
- shimmer.wrap(Runtime.prototype, '_createJestObjectFor', _createJestObjectFor => function (from) {
1772
- const result = _createJestObjectFor.apply(this, arguments)
1773
- const suiteFilePath = this._testPath || from
3137
+ if (typeof Runtime.prototype._createJestObjectFor === 'function') {
3138
+ shimmer.wrap(Runtime.prototype, '_createJestObjectFor', _createJestObjectFor => function (from) {
3139
+ const result = _createJestObjectFor.apply(this, arguments)
3140
+ const suiteFilePath = this._testPath || from
1774
3141
 
1775
- // Store the jest object so we can access it later for resetting mock state
1776
- if (suiteFilePath) {
1777
- testSuiteJestObjects.set(suiteFilePath, result)
1778
- }
3142
+ wrapJestObject(result, suiteFilePath)
3143
+ return result
3144
+ })
3145
+ }
1779
3146
 
1780
- shimmer.wrap(result, 'mock', mock => function (moduleName) {
1781
- // If the library is mocked with `jest.mock`, we don't want to bypass jest's own require engine
1782
- if (LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE.has(moduleName)) {
1783
- LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE.delete(moduleName)
3147
+ shimmer.wrap(Runtime.prototype, 'requireModule', requireModule => function (from, moduleName) {
3148
+ wrapJestGlobalsForRuntime(this)
3149
+ try {
3150
+ const returnedValue = requireModule.apply(this, arguments)
3151
+ if (moduleName === '@jest/globals') {
3152
+ wrapConcurrentJestGlobalsForRuntime(this, returnedValue)
1784
3153
  }
1785
- if (suiteFilePath) {
1786
- const existingMockedFiles = testSuiteMockedFiles.get(suiteFilePath) || []
1787
- const suiteDir = path.dirname(suiteFilePath)
1788
- const mockPath = path.resolve(suiteDir, moduleName)
1789
- existingMockedFiles.push(mockPath)
1790
- testSuiteMockedFiles.set(suiteFilePath, existingMockedFiles)
3154
+ return returnedValue
3155
+ } catch (error) {
3156
+ if (isBetweenTestsReferenceError(error)) {
3157
+ reportBetweenTestsReferenceError(this, moduleName, error.message)
1791
3158
  }
1792
- return mock.apply(this, arguments)
1793
- })
1794
- return result
3159
+ throw error
3160
+ }
1795
3161
  })
1796
3162
 
1797
3163
  shimmer.wrap(Runtime.prototype, 'requireModuleOrMock', requireModuleOrMock => function (from, moduleName) {
3164
+ wrapJestGlobalsForRuntime(this)
1798
3165
  // `requireModuleOrMock` may log errors to the console. If we don't remove ourselves
1799
3166
  // from the stack trace, the user might see a useless stack trace rather than the error
1800
3167
  // that `jest` tries to show.
@@ -1803,32 +3170,34 @@ addHook({
1803
3170
  const filteredStackTrace = structuredStackTrace
1804
3171
  .filter(callSite => !callSite.getFileName()?.includes('datadog-instrumentations/src/jest.js'))
1805
3172
 
1806
- return originalPrepareStackTrace(error, filteredStackTrace)
3173
+ if (typeof originalPrepareStackTrace === 'function') {
3174
+ return originalPrepareStackTrace(error, filteredStackTrace)
3175
+ }
3176
+ return formatDefaultStackTrace(error, filteredStackTrace)
1807
3177
  }
1808
3178
  try {
1809
3179
  // TODO: do this for every library that we instrument
1810
3180
  if (LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE.has(moduleName)) {
1811
3181
  // To bypass jest's own require engine
1812
- return this._requireCoreModule(moduleName)
3182
+ return requireOutsideJestRequireEngine(this, moduleName)
1813
3183
  }
1814
- // This means that `@fast-check/jest` is used in the test file.
1815
- if (moduleName === '@fast-check/jest') {
1816
- testSuiteAbsolutePathsWithFastCheck.add(this._testPath)
3184
+ let returnedValue
3185
+ try {
3186
+ returnedValue = requireModuleOrMock.apply(this, arguments)
3187
+ if (moduleName === '@jest/globals') {
3188
+ wrapConcurrentJestGlobalsForRuntime(this, returnedValue)
3189
+ }
3190
+ } catch (error) {
3191
+ if (isBetweenTestsReferenceError(error)) {
3192
+ reportBetweenTestsReferenceError(this, moduleName, error.message)
3193
+ }
3194
+ throw error
1817
3195
  }
1818
- const returnedValue = requireModuleOrMock.apply(this, arguments)
1819
3196
  if (process.exitCode === 1) {
1820
- if (this.loggedReferenceErrors?.size > 0) {
1821
- const errorMessage = [...this.loggedReferenceErrors][0]
1822
- testSuiteErrorCh.publish({
1823
- errorMessage,
1824
- testSuiteAbsolutePath: this._testPath,
1825
- })
1826
- } else {
1827
- testSuiteErrorCh.publish({
1828
- errorMessage: 'An error occurred while importing a module',
1829
- testSuiteAbsolutePath: this._testPath,
1830
- })
1831
- }
3197
+ publishRuntimeReferenceError(
3198
+ this,
3199
+ getLastLoggedReferenceError(this) || 'An error occurred while importing a module'
3200
+ )
1832
3201
  }
1833
3202
  return returnedValue
1834
3203
  } finally {
@@ -1837,14 +3206,35 @@ addHook({
1837
3206
  }
1838
3207
  })
1839
3208
 
3209
+ if (Runtime.prototype._logFormattedReferenceError) {
3210
+ shimmer.wrap(Runtime.prototype, '_logFormattedReferenceError', logFormattedReferenceError => function () {
3211
+ // eslint-disable-next-line no-console
3212
+ const originalConsoleError = console.error
3213
+ let loggedReferenceError
3214
+ // eslint-disable-next-line no-console
3215
+ console.error = function () {
3216
+ loggedReferenceError = arguments[0]
3217
+ return originalConsoleError.apply(this, arguments)
3218
+ }
3219
+ try {
3220
+ const result = logFormattedReferenceError.apply(this, arguments)
3221
+ publishRuntimeReferenceError(this, getLastLoggedReferenceError(this) || loggedReferenceError)
3222
+ return result
3223
+ } finally {
3224
+ // eslint-disable-next-line no-console
3225
+ console.error = originalConsoleError
3226
+ }
3227
+ })
3228
+ }
3229
+
1840
3230
  return runtimePackage
1841
3231
  })
1842
3232
 
1843
3233
  function onMessageWrapper (onMessage) {
1844
- return function () {
1845
- const response = arguments[0]
3234
+ return function (...args) {
3235
+ const response = args[0]
1846
3236
  if (!Array.isArray(response)) {
1847
- return onMessage.apply(this, arguments)
3237
+ return onMessage.apply(this, args)
1848
3238
  }
1849
3239
 
1850
3240
  const [code, data] = response
@@ -1865,7 +3255,13 @@ function onMessageWrapper (onMessage) {
1865
3255
  workerReportTelemetryCh.publish(data)
1866
3256
  return
1867
3257
  }
1868
- return onMessage.apply(this, arguments)
3258
+ if (code === JEST_WORKER_QUARANTINE_PAYLOAD_CODE) { // quarantined test failures suppressed in worker
3259
+ for (const name of JSON.parse(data)) {
3260
+ quarantinedFailingTests.add(name)
3261
+ }
3262
+ return
3263
+ }
3264
+ return onMessage.apply(this, args)
1869
3265
  }
1870
3266
  }
1871
3267
 
@@ -1917,11 +3313,23 @@ function wrapWorkerChannel (worker) {
1917
3313
  shimmer.wrap(workerChannel, worker._child ? 'send' : 'postMessage', sendWrapper)
1918
3314
  }
1919
3315
 
3316
+ function wrapWorkerInitializer (worker) {
3317
+ if (wrappedWorkerInitializers.has(worker) || typeof worker.initialize !== 'function') return
3318
+
3319
+ wrappedWorkerInitializers.add(worker)
3320
+ shimmer.wrap(worker, 'initialize', initialize => function () {
3321
+ const result = initialize.apply(this, arguments)
3322
+ wrapWorkerChannel(this)
3323
+ return result
3324
+ })
3325
+ }
3326
+
1920
3327
  function wrapWorker (worker) {
1921
3328
  // ChildProcessWorker uses _child (child_process), ExperimentalWorker uses _worker (worker_threads)
1922
3329
  const workerChannel = worker._child || worker._worker
1923
3330
  if (!workerChannel) return
1924
3331
 
3332
+ wrapWorkerInitializer(worker)
1925
3333
  wrapWorkerChannel(worker)
1926
3334
  shimmer.wrap(worker, '_onMessage', onMessageWrapper)
1927
3335
  workerChannel.removeAllListeners('message')
@@ -1929,8 +3337,8 @@ function wrapWorker (worker) {
1929
3337
  }
1930
3338
 
1931
3339
  function enqueueWrapper (enqueue) {
1932
- return function () {
1933
- shimmer.wrap(arguments[0], 'onStart', onStart => function (worker) {
3340
+ return function (...args) {
3341
+ shimmer.wrap(args[0], 'onStart', onStart => function (worker) {
1934
3342
  if (worker) {
1935
3343
  const currentChannel = worker._child || worker._worker
1936
3344
  const previousChannel = wrappedWorkerChannels.get(worker)
@@ -1947,7 +3355,7 @@ function enqueueWrapper (enqueue) {
1947
3355
  }
1948
3356
  return onStart.apply(this, arguments)
1949
3357
  })
1950
- return enqueue.apply(this, arguments)
3358
+ return enqueue.apply(this, args)
1951
3359
  }
1952
3360
  }
1953
3361
 
@@ -1959,7 +3367,7 @@ function enqueueWrapper (enqueue) {
1959
3367
  */
1960
3368
  addHook({
1961
3369
  name: 'jest-worker',
1962
- versions: ['>=24.9.0 <30.0.0'],
3370
+ versions: [MINIMUM_JEST_WORKER_VERSION_BEFORE_30],
1963
3371
  file: 'build/workers/ChildProcessWorker.js',
1964
3372
  }, (childProcessWorker) => {
1965
3373
  const ChildProcessWorker = childProcessWorker.default
@@ -1974,7 +3382,7 @@ addHook({
1974
3382
 
1975
3383
  addHook({
1976
3384
  name: 'jest-worker',
1977
- versions: ['>=24.9.0 <30.0.0'],
3385
+ versions: [MINIMUM_JEST_WORKER_VERSION_BEFORE_30],
1978
3386
  file: 'build/workers/NodeThreadsWorker.js',
1979
3387
  }, (nodeThreadsWorker) => {
1980
3388
  const ExperimentalWorker = nodeThreadsWorker.default