@depup/dd-trace 5.97.0-depup.0 → 6.4.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 (633) hide show
  1. package/LICENSE-3rdparty.csv +89 -104
  2. package/README.md +9 -3
  3. package/changes.json +8 -3
  4. package/ci/init.js +25 -5
  5. package/ci/vitest-no-worker-init-setup.mjs +430 -0
  6. package/ext/exporters.js +1 -0
  7. package/ext/tags.js +3 -0
  8. package/index.d.ts +315 -244
  9. package/index.electron.js +3 -0
  10. package/initialize.mjs +9 -8
  11. package/loader-hook.mjs +154 -47
  12. package/package.json +118 -78
  13. package/packages/datadog-core/src/storage.js +47 -48
  14. package/packages/datadog-esbuild/index.js +32 -1
  15. package/packages/datadog-esbuild/src/utils.js +46 -3
  16. package/packages/datadog-instrumentations/src/aerospike.js +3 -3
  17. package/packages/datadog-instrumentations/src/ai.js +131 -76
  18. package/packages/datadog-instrumentations/src/amqplib.js +6 -7
  19. package/packages/datadog-instrumentations/src/anthropic.js +10 -10
  20. package/packages/datadog-instrumentations/src/apollo-server-core.js +3 -3
  21. package/packages/datadog-instrumentations/src/apollo-server.js +10 -18
  22. package/packages/datadog-instrumentations/src/avsc.js +6 -6
  23. package/packages/datadog-instrumentations/src/aws-durable-execution-sdk-js-context-methods.js +18 -0
  24. package/packages/datadog-instrumentations/src/aws-durable-execution-sdk-js.js +111 -0
  25. package/packages/datadog-instrumentations/src/aws-sdk.js +172 -72
  26. package/packages/datadog-instrumentations/src/azure-cosmos.js +7 -0
  27. package/packages/datadog-instrumentations/src/azure-durable-functions.js +8 -8
  28. package/packages/datadog-instrumentations/src/azure-functions.js +3 -0
  29. package/packages/datadog-instrumentations/src/bluebird.js +2 -2
  30. package/packages/datadog-instrumentations/src/body-parser.js +5 -2
  31. package/packages/datadog-instrumentations/src/cassandra-driver.js +12 -9
  32. package/packages/datadog-instrumentations/src/child_process.js +15 -15
  33. package/packages/datadog-instrumentations/src/claude-agent-sdk.js +587 -0
  34. package/packages/datadog-instrumentations/src/confluentinc-kafka-javascript.js +41 -24
  35. package/packages/datadog-instrumentations/src/connect.js +14 -12
  36. package/packages/datadog-instrumentations/src/cookie-parser.js +5 -4
  37. package/packages/datadog-instrumentations/src/cookie.js +9 -3
  38. package/packages/datadog-instrumentations/src/couchbase.js +73 -238
  39. package/packages/datadog-instrumentations/src/crypto.js +49 -4
  40. package/packages/datadog-instrumentations/src/cucumber-worker-threads.js +19 -0
  41. package/packages/datadog-instrumentations/src/cucumber.js +747 -187
  42. package/packages/datadog-instrumentations/src/cypress-config.js +164 -56
  43. package/packages/datadog-instrumentations/src/cypress.js +5 -3
  44. package/packages/datadog-instrumentations/src/dns.js +60 -59
  45. package/packages/datadog-instrumentations/src/elasticsearch.js +9 -12
  46. package/packages/datadog-instrumentations/src/electron/preload.js +42 -0
  47. package/packages/datadog-instrumentations/src/electron.js +240 -0
  48. package/packages/datadog-instrumentations/src/express-mongo-sanitize.js +11 -9
  49. package/packages/datadog-instrumentations/src/express-session.js +14 -13
  50. package/packages/datadog-instrumentations/src/express.js +52 -30
  51. package/packages/datadog-instrumentations/src/fastify.js +169 -86
  52. package/packages/datadog-instrumentations/src/fetch.js +5 -5
  53. package/packages/datadog-instrumentations/src/fs.js +22 -20
  54. package/packages/datadog-instrumentations/src/google-cloud-pubsub.js +5 -7
  55. package/packages/datadog-instrumentations/src/google-genai.js +4 -4
  56. package/packages/datadog-instrumentations/src/graphql.js +26 -362
  57. package/packages/datadog-instrumentations/src/grpc/client.js +48 -32
  58. package/packages/datadog-instrumentations/src/grpc/server.js +20 -2
  59. package/packages/datadog-instrumentations/src/hapi.js +2 -2
  60. package/packages/datadog-instrumentations/src/helpers/callback-instrumentor.js +74 -0
  61. package/packages/datadog-instrumentations/src/helpers/check-require-cache.js +85 -9
  62. package/packages/datadog-instrumentations/src/helpers/hook.js +4 -1
  63. package/packages/datadog-instrumentations/src/helpers/hooks.js +12 -0
  64. package/packages/datadog-instrumentations/src/helpers/instrument.js +36 -3
  65. package/packages/datadog-instrumentations/src/helpers/kafka.js +58 -0
  66. package/packages/datadog-instrumentations/src/helpers/optional-peer-bundler.js +65 -0
  67. package/packages/datadog-instrumentations/src/helpers/promise-instrumentor.js +42 -0
  68. package/packages/datadog-instrumentations/src/helpers/promise.js +2 -2
  69. package/packages/datadog-instrumentations/src/helpers/register.js +7 -5
  70. package/packages/datadog-instrumentations/src/helpers/require-optional-peer.js +17 -0
  71. package/packages/datadog-instrumentations/src/helpers/rewriter/compiler.js +13 -5
  72. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +24 -7
  73. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/ai.js +6 -6
  74. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/aws-durable-execution-sdk-js.js +31 -0
  75. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/azure-cosmos.js +50 -0
  76. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/claude-agent-sdk.js +17 -0
  77. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +201 -0
  78. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/index.js +7 -0
  79. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/langgraph.js +4 -2
  80. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/mercurius.js +31 -0
  81. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-sdk.js +35 -0
  82. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/playwright.js +85 -0
  83. package/packages/datadog-instrumentations/src/helpers/rewriter/loader.mjs +18 -2
  84. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +49 -224
  85. package/packages/datadog-instrumentations/src/helpers/router-helper.js +8 -8
  86. package/packages/datadog-instrumentations/src/hono.js +71 -9
  87. package/packages/datadog-instrumentations/src/http/client.js +48 -24
  88. package/packages/datadog-instrumentations/src/http/server.js +75 -29
  89. package/packages/datadog-instrumentations/src/http2/client.js +15 -12
  90. package/packages/datadog-instrumentations/src/http2/server.js +156 -23
  91. package/packages/datadog-instrumentations/src/ioredis.js +17 -14
  92. package/packages/datadog-instrumentations/src/iovalkey.js +1 -2
  93. package/packages/datadog-instrumentations/src/jest/bail-reporter.js +42 -0
  94. package/packages/datadog-instrumentations/src/jest/coverage-backfill.js +163 -0
  95. package/packages/datadog-instrumentations/src/jest.js +1783 -401
  96. package/packages/datadog-instrumentations/src/kafkajs.js +284 -170
  97. package/packages/datadog-instrumentations/src/knex.js +17 -17
  98. package/packages/datadog-instrumentations/src/koa.js +15 -14
  99. package/packages/datadog-instrumentations/src/ldapjs.js +5 -5
  100. package/packages/datadog-instrumentations/src/light-my-request.js +2 -2
  101. package/packages/datadog-instrumentations/src/limitd-client.js +4 -4
  102. package/packages/datadog-instrumentations/src/lodash.js +4 -4
  103. package/packages/datadog-instrumentations/src/mariadb.js +18 -16
  104. package/packages/datadog-instrumentations/src/memcached.js +4 -3
  105. package/packages/datadog-instrumentations/src/mercurius.js +11 -0
  106. package/packages/datadog-instrumentations/src/microgateway-core.js +2 -2
  107. package/packages/datadog-instrumentations/src/mocha/common.js +7 -4
  108. package/packages/datadog-instrumentations/src/mocha/main.js +557 -118
  109. package/packages/datadog-instrumentations/src/mocha/utils.js +531 -131
  110. package/packages/datadog-instrumentations/src/mocha/worker.js +27 -9
  111. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +254 -0
  112. package/packages/datadog-instrumentations/src/mongodb-core.js +43 -31
  113. package/packages/datadog-instrumentations/src/mongodb.js +79 -5
  114. package/packages/datadog-instrumentations/src/mongoose.js +43 -34
  115. package/packages/datadog-instrumentations/src/mquery.js +5 -5
  116. package/packages/datadog-instrumentations/src/multer.js +5 -4
  117. package/packages/datadog-instrumentations/src/mysql.js +17 -17
  118. package/packages/datadog-instrumentations/src/mysql2.js +39 -5
  119. package/packages/datadog-instrumentations/src/nats.js +182 -0
  120. package/packages/datadog-instrumentations/src/net.js +19 -11
  121. package/packages/datadog-instrumentations/src/next.js +44 -10
  122. package/packages/datadog-instrumentations/src/nyc.js +43 -6
  123. package/packages/datadog-instrumentations/src/openai.js +124 -38
  124. package/packages/datadog-instrumentations/src/oracledb.js +12 -7
  125. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +27 -6
  126. package/packages/datadog-instrumentations/src/passport-utils.js +5 -5
  127. package/packages/datadog-instrumentations/src/path-to-regexp.js +44 -0
  128. package/packages/datadog-instrumentations/src/pg.js +58 -25
  129. package/packages/datadog-instrumentations/src/pino.js +25 -41
  130. package/packages/datadog-instrumentations/src/playwright-browser-scripts.js +27 -0
  131. package/packages/datadog-instrumentations/src/playwright.js +1086 -350
  132. package/packages/datadog-instrumentations/src/protobufjs.js +16 -16
  133. package/packages/datadog-instrumentations/src/redis.js +28 -15
  134. package/packages/datadog-instrumentations/src/restify.js +6 -5
  135. package/packages/datadog-instrumentations/src/router.js +243 -87
  136. package/packages/datadog-instrumentations/src/selenium.js +1 -2
  137. package/packages/datadog-instrumentations/src/stripe.js +47 -33
  138. package/packages/datadog-instrumentations/src/tedious.js +28 -0
  139. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +1297 -0
  140. package/packages/datadog-instrumentations/src/vitest-main.js +1592 -0
  141. package/packages/datadog-instrumentations/src/vitest-util.js +251 -0
  142. package/packages/datadog-instrumentations/src/vitest-worker.js +822 -0
  143. package/packages/datadog-instrumentations/src/vitest.js +11 -1262
  144. package/packages/datadog-instrumentations/src/winston.js +4 -4
  145. package/packages/datadog-instrumentations/src/ws.js +7 -7
  146. package/packages/datadog-instrumentations/src/zlib.js +29 -0
  147. package/packages/datadog-plugin-ai/src/index.js +1 -1
  148. package/packages/datadog-plugin-ai/src/tracing.js +66 -3
  149. package/packages/datadog-plugin-ai/src/utils.js +17 -4
  150. package/packages/datadog-plugin-apollo/src/gateway/request.js +1 -21
  151. package/packages/datadog-plugin-avsc/src/schema_iterator.js +3 -3
  152. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/checkpoint.js +31 -0
  153. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/client.js +55 -0
  154. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/context.js +123 -0
  155. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/handler.js +129 -0
  156. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/index.js +19 -0
  157. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/trace-checkpoint.js +224 -0
  158. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/util.js +79 -0
  159. package/packages/datadog-plugin-aws-sdk/src/base.js +86 -50
  160. package/packages/datadog-plugin-aws-sdk/src/services/bedrockruntime/tracing.js +1 -1
  161. package/packages/datadog-plugin-aws-sdk/src/services/bedrockruntime/utils.js +218 -4
  162. package/packages/datadog-plugin-aws-sdk/src/services/cloudwatchlogs.js +1 -1
  163. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +2 -1
  164. package/packages/datadog-plugin-aws-sdk/src/services/eventbridge.js +59 -14
  165. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +174 -75
  166. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +34 -23
  167. package/packages/datadog-plugin-aws-sdk/src/services/redshift.js +2 -1
  168. package/packages/datadog-plugin-aws-sdk/src/services/s3.js +1 -1
  169. package/packages/datadog-plugin-aws-sdk/src/services/sns.js +26 -26
  170. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +187 -101
  171. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +20 -18
  172. package/packages/datadog-plugin-azure-cosmos/src/index.js +144 -0
  173. package/packages/datadog-plugin-azure-event-hubs/src/producer.js +8 -15
  174. package/packages/datadog-plugin-azure-functions/src/index.js +7 -3
  175. package/packages/datadog-plugin-azure-service-bus/src/producer.js +5 -10
  176. package/packages/datadog-plugin-bullmq/src/consumer.js +5 -4
  177. package/packages/datadog-plugin-bullmq/src/filter.js +35 -0
  178. package/packages/datadog-plugin-bullmq/src/producer.js +121 -33
  179. package/packages/datadog-plugin-bunyan/src/index.js +28 -0
  180. package/packages/datadog-plugin-child_process/src/index.js +13 -2
  181. package/packages/datadog-plugin-child_process/src/scrub-cmd-params.js +6 -6
  182. package/packages/datadog-plugin-claude-agent-sdk/src/index.js +31 -0
  183. package/packages/datadog-plugin-claude-agent-sdk/src/tracing.js +107 -0
  184. package/packages/datadog-plugin-claude-agent-sdk/src/util.js +15 -0
  185. package/packages/datadog-plugin-couchbase/src/index.js +58 -52
  186. package/packages/datadog-plugin-cucumber/src/index.js +46 -28
  187. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +961 -92
  188. package/packages/datadog-plugin-cypress/src/index.js +104 -2
  189. package/packages/datadog-plugin-cypress/src/plugin.js +6 -14
  190. package/packages/datadog-plugin-cypress/src/source-map-utils.js +48 -1
  191. package/packages/datadog-plugin-cypress/src/support.js +180 -25
  192. package/packages/datadog-plugin-dd-trace-api/src/index.js +1 -1
  193. package/packages/datadog-plugin-dns/src/lookup.js +8 -6
  194. package/packages/datadog-plugin-elasticsearch/src/index.js +28 -8
  195. package/packages/datadog-plugin-electron/src/index.js +17 -0
  196. package/packages/datadog-plugin-electron/src/ipc.js +143 -0
  197. package/packages/datadog-plugin-electron/src/net.js +82 -0
  198. package/packages/datadog-plugin-express/src/code_origin.js +1 -1
  199. package/packages/datadog-plugin-fastify/src/code_origin.js +1 -1
  200. package/packages/datadog-plugin-fs/src/index.js +2 -1
  201. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +2 -5
  202. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +27 -18
  203. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +5 -8
  204. package/packages/datadog-plugin-graphql/src/execute.js +706 -34
  205. package/packages/datadog-plugin-graphql/src/index.js +43 -9
  206. package/packages/datadog-plugin-graphql/src/parse.js +45 -4
  207. package/packages/datadog-plugin-graphql/src/request.js +135 -0
  208. package/packages/datadog-plugin-graphql/src/tools/signature.js +32 -7
  209. package/packages/datadog-plugin-graphql/src/tools/transforms.js +118 -100
  210. package/packages/datadog-plugin-graphql/src/utils.js +261 -3
  211. package/packages/datadog-plugin-graphql/src/validate.js +53 -7
  212. package/packages/datadog-plugin-grpc/src/client.js +7 -8
  213. package/packages/datadog-plugin-grpc/src/server.js +1 -1
  214. package/packages/datadog-plugin-grpc/src/util.js +57 -22
  215. package/packages/datadog-plugin-http/src/client.js +12 -14
  216. package/packages/datadog-plugin-http/src/index.js +6 -8
  217. package/packages/datadog-plugin-http/src/server.js +63 -20
  218. package/packages/datadog-plugin-http2/src/client.js +6 -3
  219. package/packages/datadog-plugin-http2/src/server.js +48 -8
  220. package/packages/datadog-plugin-jest/src/index.js +133 -67
  221. package/packages/datadog-plugin-jest/src/util.js +37 -16
  222. package/packages/datadog-plugin-kafkajs/src/batch-consumer.js +1 -1
  223. package/packages/datadog-plugin-kafkajs/src/consumer.js +2 -9
  224. package/packages/datadog-plugin-kafkajs/src/producer.js +37 -8
  225. package/packages/datadog-plugin-langgraph/src/stream.js +1 -1
  226. package/packages/datadog-plugin-memcached/src/index.js +1 -1
  227. package/packages/datadog-plugin-mocha/src/index.js +66 -20
  228. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/index.js +24 -0
  229. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +173 -0
  230. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +30 -0
  231. package/packages/datadog-plugin-mongodb-core/src/bulk-write.js +43 -0
  232. package/packages/datadog-plugin-mongodb-core/src/index.js +8 -206
  233. package/packages/datadog-plugin-mongodb-core/src/query.js +452 -0
  234. package/packages/datadog-plugin-mysql/src/index.js +9 -4
  235. package/packages/datadog-plugin-nats/src/consumer.js +43 -0
  236. package/packages/datadog-plugin-nats/src/index.js +20 -0
  237. package/packages/datadog-plugin-nats/src/producer.js +62 -0
  238. package/packages/datadog-plugin-nats/src/util.js +33 -0
  239. package/packages/datadog-plugin-next/src/index.js +12 -4
  240. package/packages/datadog-plugin-openai/src/services.js +4 -3
  241. package/packages/datadog-plugin-openai/src/tracing.js +27 -25
  242. package/packages/datadog-plugin-oracledb/src/index.js +13 -2
  243. package/packages/datadog-plugin-pg/src/index.js +13 -3
  244. package/packages/datadog-plugin-pino/src/index.js +42 -0
  245. package/packages/datadog-plugin-playwright/src/index.js +21 -11
  246. package/packages/datadog-plugin-protobufjs/src/schema_iterator.js +3 -3
  247. package/packages/datadog-plugin-redis/src/index.js +54 -25
  248. package/packages/datadog-plugin-rhea/src/producer.js +1 -1
  249. package/packages/datadog-plugin-router/src/index.js +46 -44
  250. package/packages/datadog-plugin-selenium/src/index.js +1 -1
  251. package/packages/datadog-plugin-tedious/src/index.js +1 -1
  252. package/packages/datadog-plugin-undici/src/index.js +24 -2
  253. package/packages/datadog-plugin-vitest/src/index.js +160 -90
  254. package/packages/datadog-plugin-winston/src/index.js +30 -0
  255. package/packages/datadog-plugin-ws/src/close.js +3 -1
  256. package/packages/datadog-plugin-ws/src/producer.js +2 -0
  257. package/packages/datadog-plugin-ws/src/receiver.js +2 -1
  258. package/packages/datadog-shimmer/src/shimmer.js +101 -39
  259. package/packages/datadog-webpack/index.js +17 -1
  260. package/packages/datadog-webpack/src/optional-peer-loader.js +17 -0
  261. package/packages/dd-trace/index.electron.js +3 -0
  262. package/packages/dd-trace/index.js +2 -36
  263. package/packages/dd-trace/src/aiguard/channels.js +7 -0
  264. package/packages/dd-trace/src/aiguard/index.js +16 -34
  265. package/packages/dd-trace/src/aiguard/integrations/evaluate.js +46 -0
  266. package/packages/dd-trace/src/aiguard/integrations/index.js +34 -0
  267. package/packages/dd-trace/src/aiguard/integrations/openai.js +80 -0
  268. package/packages/dd-trace/src/aiguard/integrations/vercel-ai.js +92 -0
  269. package/packages/dd-trace/src/aiguard/messages/openai.js +382 -0
  270. package/packages/{datadog-instrumentations/src/helpers/ai-messages.js → dd-trace/src/aiguard/messages/vercel-ai.js} +30 -27
  271. package/packages/dd-trace/src/aiguard/sdk.js +147 -54
  272. package/packages/dd-trace/src/aiguard/tags.js +26 -10
  273. package/packages/dd-trace/src/appsec/api_security/index.js +55 -0
  274. package/packages/dd-trace/src/appsec/api_security/sampler.js +147 -0
  275. package/packages/dd-trace/src/appsec/blocked_templates.js +4 -3
  276. package/packages/dd-trace/src/appsec/blocking.js +82 -42
  277. package/packages/dd-trace/src/appsec/channels.js +5 -1
  278. package/packages/dd-trace/src/appsec/downstream_requests.js +116 -62
  279. package/packages/dd-trace/src/appsec/graphql.js +20 -17
  280. package/packages/dd-trace/src/appsec/iast/analyzers/hardcoded-password-rules.js +1 -1
  281. package/packages/dd-trace/src/appsec/iast/analyzers/hardcoded-secret-rules.js +81 -81
  282. package/packages/dd-trace/src/appsec/iast/analyzers/nosql-injection-mongodb-analyzer.js +23 -23
  283. package/packages/dd-trace/src/appsec/iast/index.js +3 -2
  284. package/packages/dd-trace/src/appsec/iast/security-controls/index.js +4 -4
  285. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugins/kafka.js +2 -2
  286. package/packages/dd-trace/src/appsec/iast/taint-tracking/rewriter.js +4 -4
  287. package/packages/dd-trace/src/appsec/iast/taint-tracking/taint-tracking-impl.js +2 -2
  288. package/packages/dd-trace/src/appsec/iast/telemetry/index.js +2 -1
  289. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-analyzers/ldap-sensitive-analyzer.js +54 -12
  290. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-analyzers/url-sensitive-analyzer.js +5 -1
  291. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-handler.js +31 -4
  292. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/index.js +1 -3
  293. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/utils.js +83 -48
  294. package/packages/dd-trace/src/appsec/iast/vulnerability-reporter.js +1 -1
  295. package/packages/dd-trace/src/appsec/index.js +65 -47
  296. package/packages/dd-trace/src/appsec/lambda.js +135 -0
  297. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -5
  298. package/packages/dd-trace/src/appsec/rasp/lfi.js +8 -4
  299. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +5 -10
  300. package/packages/dd-trace/src/appsec/rasp/ssrf.js +26 -18
  301. package/packages/dd-trace/src/appsec/recommended.json +2438 -13
  302. package/packages/dd-trace/src/appsec/reporter.js +87 -28
  303. package/packages/dd-trace/src/appsec/rule_manager.js +4 -2
  304. package/packages/dd-trace/src/appsec/sdk/set_user.js +1 -1
  305. package/packages/dd-trace/src/appsec/sdk/track_event.js +5 -5
  306. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +7 -11
  307. package/packages/dd-trace/src/appsec/sdk/utils.js +5 -3
  308. package/packages/dd-trace/src/appsec/store.js +50 -0
  309. package/packages/dd-trace/src/appsec/telemetry/api_security.js +34 -0
  310. package/packages/dd-trace/src/appsec/telemetry/index.js +27 -1
  311. package/packages/dd-trace/src/appsec/user_tracking.js +5 -4
  312. package/packages/dd-trace/src/appsec/waf/index.js +19 -9
  313. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +35 -20
  314. package/packages/dd-trace/src/appsec/waf/waf_manager.js +1 -1
  315. package/packages/dd-trace/src/azure_metadata.js +17 -6
  316. package/packages/dd-trace/src/baggage.js +32 -13
  317. package/packages/dd-trace/src/bootstrap.js +39 -0
  318. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/index.js +30 -5
  319. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +122 -24
  320. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +22 -7
  321. package/packages/dd-trace/src/ci-visibility/exporters/agent-proxy/index.js +5 -2
  322. package/packages/dd-trace/src/ci-visibility/exporters/agentless/coverage-writer.js +2 -2
  323. package/packages/dd-trace/src/ci-visibility/exporters/agentless/di-logs-writer.js +2 -2
  324. package/packages/dd-trace/src/ci-visibility/exporters/agentless/index.js +6 -2
  325. package/packages/dd-trace/src/ci-visibility/exporters/agentless/writer.js +2 -2
  326. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +148 -25
  327. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +3 -4
  328. package/packages/dd-trace/src/ci-visibility/exporters/test-worker/index.js +28 -10
  329. package/packages/dd-trace/src/ci-visibility/exporters/test-worker/writer.js +22 -0
  330. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +105 -22
  331. package/packages/dd-trace/src/ci-visibility/lage.js +2 -1
  332. package/packages/dd-trace/src/ci-visibility/log-submission/log-submission-plugin.js +4 -5
  333. package/packages/dd-trace/src/ci-visibility/requests/fs-cache.js +4 -5
  334. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +73 -55
  335. package/packages/dd-trace/src/ci-visibility/requests/request.js +14 -50
  336. package/packages/dd-trace/src/ci-visibility/requests/upload-coverage-report.js +4 -4
  337. package/packages/dd-trace/src/ci-visibility/requests/upload-test-screenshot.js +156 -0
  338. package/packages/dd-trace/src/ci-visibility/test-api-manual/test-api-manual-plugin.js +5 -3
  339. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +24 -6
  340. package/packages/dd-trace/src/ci-visibility/test-optimization-cache.js +70 -6
  341. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +128 -0
  342. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +291 -0
  343. package/packages/dd-trace/src/config/config-types.d.ts +8 -6
  344. package/packages/dd-trace/src/config/defaults.js +71 -44
  345. package/packages/dd-trace/src/config/generated-config-types.d.ts +676 -131
  346. package/packages/dd-trace/src/config/git_properties.js +2 -2
  347. package/packages/dd-trace/src/config/helper.js +139 -33
  348. package/packages/dd-trace/src/config/index.js +117 -131
  349. package/packages/dd-trace/src/config/major-overrides.js +100 -0
  350. package/packages/dd-trace/src/config/normalize-service.js +31 -0
  351. package/packages/dd-trace/src/config/parsers.js +138 -10
  352. package/packages/dd-trace/src/config/remote_config.js +1 -1
  353. package/packages/dd-trace/src/config/supported-configurations.json +394 -203
  354. package/packages/dd-trace/src/constants.js +15 -0
  355. package/packages/dd-trace/src/crashtracking/crashtracker.js +18 -6
  356. package/packages/dd-trace/src/datastreams/checkpointer.js +6 -12
  357. package/packages/dd-trace/src/datastreams/context.js +4 -2
  358. package/packages/dd-trace/src/datastreams/encoding.js +39 -28
  359. package/packages/dd-trace/src/datastreams/index.js +2 -1
  360. package/packages/dd-trace/src/datastreams/manager.js +1 -1
  361. package/packages/dd-trace/src/datastreams/pathway.js +35 -30
  362. package/packages/dd-trace/src/datastreams/processor.js +31 -22
  363. package/packages/dd-trace/src/datastreams/size.js +6 -2
  364. package/packages/dd-trace/src/datastreams/writer.js +15 -6
  365. package/packages/dd-trace/src/debugger/config.js +9 -4
  366. package/packages/dd-trace/src/debugger/devtools_client/breakpoints.js +49 -35
  367. package/packages/dd-trace/src/debugger/devtools_client/condition.js +5 -8
  368. package/packages/dd-trace/src/debugger/devtools_client/config.js +3 -2
  369. package/packages/dd-trace/src/debugger/devtools_client/index.js +33 -71
  370. package/packages/dd-trace/src/debugger/devtools_client/probe_sampler.js +83 -0
  371. package/packages/dd-trace/src/debugger/devtools_client/send.js +27 -6
  372. package/packages/dd-trace/src/debugger/devtools_client/snapshot/collector.js +2 -2
  373. package/packages/dd-trace/src/debugger/devtools_client/snapshot/processor.js +5 -2
  374. package/packages/dd-trace/src/debugger/devtools_client/snapshot-pruner.js +1 -0
  375. package/packages/dd-trace/src/debugger/devtools_client/source-maps.js +1 -1
  376. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  377. package/packages/dd-trace/src/debugger/index.js +13 -9
  378. package/packages/dd-trace/src/debugger/probe_sampler.js +112 -0
  379. package/packages/dd-trace/src/debugger/probe_sampler_constants.js +19 -0
  380. package/packages/dd-trace/src/dogstatsd.js +34 -28
  381. package/packages/dd-trace/src/encode/0.4.js +829 -268
  382. package/packages/dd-trace/src/encode/0.5.js +158 -22
  383. package/packages/dd-trace/src/encode/agentless-ci-visibility.js +141 -65
  384. package/packages/dd-trace/src/encode/agentless-json.js +12 -6
  385. package/packages/dd-trace/src/encode/coverage-ci-visibility.js +52 -15
  386. package/packages/dd-trace/src/encode/span-stats.js +19 -16
  387. package/packages/dd-trace/src/encode/tags-processors.js +30 -25
  388. package/packages/dd-trace/src/exporter.js +3 -1
  389. package/packages/dd-trace/src/exporters/agent/index.js +4 -5
  390. package/packages/dd-trace/src/exporters/agent/writer.js +1 -2
  391. package/packages/dd-trace/src/exporters/agentless/index.js +12 -13
  392. package/packages/dd-trace/src/exporters/agentless/intake.js +43 -0
  393. package/packages/dd-trace/src/exporters/agentless/writer.js +12 -11
  394. package/packages/dd-trace/src/exporters/common/agents.js +3 -1
  395. package/packages/dd-trace/src/exporters/common/buffering-exporter.js +3 -3
  396. package/packages/dd-trace/src/exporters/common/request.js +48 -28
  397. package/packages/dd-trace/src/exporters/common/retry.js +104 -0
  398. package/packages/dd-trace/src/exporters/common/url.js +34 -0
  399. package/packages/dd-trace/src/exporters/common/util.js +2 -2
  400. package/packages/dd-trace/src/exporters/common/writer.js +17 -1
  401. package/packages/dd-trace/src/exporters/electron/index.js +49 -0
  402. package/packages/dd-trace/src/exporters/span-stats/index.js +1 -2
  403. package/packages/dd-trace/src/exporters/span-stats/writer.js +1 -3
  404. package/packages/dd-trace/src/external-logger/src/index.js +2 -1
  405. package/packages/dd-trace/src/feature-registry.js +22 -0
  406. package/packages/dd-trace/src/git_metadata.js +68 -0
  407. package/packages/dd-trace/src/git_metadata_tagger.js +13 -5
  408. package/packages/dd-trace/src/guardrails/index.js +11 -6
  409. package/packages/dd-trace/src/guardrails/telemetry.js +40 -3
  410. package/packages/dd-trace/src/heap_snapshots.js +4 -4
  411. package/packages/dd-trace/src/id.js +46 -27
  412. package/packages/dd-trace/src/index.js +7 -8
  413. package/packages/dd-trace/src/lambda/handler-paths.js +52 -0
  414. package/packages/dd-trace/src/lambda/handler.js +2 -6
  415. package/packages/dd-trace/src/lambda/index.js +62 -14
  416. package/packages/dd-trace/src/lambda/runtime/patch.js +21 -46
  417. package/packages/dd-trace/src/llmobs/constants/tags.js +13 -0
  418. package/packages/dd-trace/src/llmobs/index.js +37 -7
  419. package/packages/dd-trace/src/llmobs/plugins/ai/ddTelemetry.js +403 -0
  420. package/packages/dd-trace/src/llmobs/plugins/ai/index.js +8 -395
  421. package/packages/dd-trace/src/llmobs/plugins/ai/util.js +119 -7
  422. package/packages/dd-trace/src/llmobs/plugins/ai/vercelTelemetry.js +363 -0
  423. package/packages/dd-trace/src/llmobs/plugins/{anthropic.js → anthropic/index.js} +32 -79
  424. package/packages/dd-trace/src/llmobs/plugins/anthropic/util.js +109 -0
  425. package/packages/dd-trace/src/llmobs/plugins/base.js +4 -4
  426. package/packages/dd-trace/src/llmobs/plugins/bedrockruntime.js +89 -37
  427. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +270 -0
  428. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/utils.js +10 -0
  429. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +5 -1
  430. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +81 -16
  431. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/chain.js +3 -2
  432. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/chat_model.js +3 -2
  433. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/embedding.js +2 -1
  434. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/index.js +1 -50
  435. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/vectorstore.js +2 -1
  436. package/packages/dd-trace/src/llmobs/plugins/langchain/index.js +14 -8
  437. package/packages/dd-trace/src/llmobs/plugins/langchain/messages.js +76 -0
  438. package/packages/dd-trace/src/llmobs/plugins/langgraph/index.js +3 -28
  439. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +68 -0
  440. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +57 -0
  441. package/packages/dd-trace/src/llmobs/plugins/openai/index.js +21 -51
  442. package/packages/dd-trace/src/llmobs/sdk.js +56 -35
  443. package/packages/dd-trace/src/llmobs/span_processor.js +90 -11
  444. package/packages/dd-trace/src/llmobs/tagger.js +129 -4
  445. package/packages/dd-trace/src/llmobs/telemetry.js +31 -1
  446. package/packages/dd-trace/src/llmobs/util.js +202 -9
  447. package/packages/dd-trace/src/llmobs/writers/base.js +11 -5
  448. package/packages/dd-trace/src/llmobs/writers/spans.js +1 -1
  449. package/packages/dd-trace/src/llmobs/writers/util.js +1 -2
  450. package/packages/dd-trace/src/log/index.js +19 -31
  451. package/packages/dd-trace/src/log/writer.js +3 -1
  452. package/packages/dd-trace/src/msgpack/chunk.js +430 -11
  453. package/packages/dd-trace/src/msgpack/index.js +101 -2
  454. package/packages/dd-trace/src/noop/proxy.js +5 -4
  455. package/packages/dd-trace/src/noop/span.js +3 -1
  456. package/packages/dd-trace/src/openfeature/encoding.js +70 -0
  457. package/packages/dd-trace/src/openfeature/eval-metrics-hook.js +103 -0
  458. package/packages/dd-trace/src/openfeature/flagging_provider.js +26 -1
  459. package/packages/dd-trace/src/openfeature/noop.js +40 -36
  460. package/packages/dd-trace/src/openfeature/register.js +46 -0
  461. package/packages/dd-trace/src/openfeature/remote_config.js +6 -1
  462. package/packages/dd-trace/src/openfeature/span-enrichment-hook.js +143 -0
  463. package/packages/dd-trace/src/openfeature/span-enrichment.js +149 -0
  464. package/packages/dd-trace/src/openfeature/writers/base.js +3 -11
  465. package/packages/dd-trace/src/openfeature/writers/exposures.js +82 -70
  466. package/packages/dd-trace/src/openfeature/writers/util.js +1 -2
  467. package/packages/dd-trace/src/opentelemetry/active-span-proxy.js +42 -0
  468. package/packages/dd-trace/src/opentelemetry/bridge-span-base.js +107 -0
  469. package/packages/dd-trace/src/opentelemetry/context_manager.js +27 -13
  470. package/packages/dd-trace/src/opentelemetry/logs/index.js +6 -6
  471. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +3 -2
  472. package/packages/dd-trace/src/opentelemetry/metrics/index.js +61 -12
  473. package/packages/dd-trace/src/opentelemetry/metrics/instruments.js +28 -14
  474. package/packages/dd-trace/src/opentelemetry/metrics/meter.js +7 -10
  475. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +3 -2
  476. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +40 -0
  477. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_transformer.js +169 -0
  478. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +99 -5
  479. package/packages/dd-trace/src/opentelemetry/metrics/time.js +19 -0
  480. package/packages/dd-trace/src/opentelemetry/otlp/common.proto +2 -2
  481. package/packages/dd-trace/src/opentelemetry/otlp/logs.proto +1 -1
  482. package/packages/dd-trace/src/opentelemetry/otlp/logs_service.proto +1 -1
  483. package/packages/dd-trace/src/opentelemetry/otlp/metrics.proto +1 -1
  484. package/packages/dd-trace/src/opentelemetry/otlp/metrics_service.proto +1 -1
  485. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +56 -82
  486. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +1 -2
  487. package/packages/dd-trace/src/opentelemetry/otlp/protobuf_loader.js +14 -2
  488. package/packages/dd-trace/src/opentelemetry/otlp/trace.proto +358 -0
  489. package/packages/dd-trace/src/opentelemetry/otlp/trace_service.proto +78 -0
  490. package/packages/dd-trace/src/opentelemetry/span-helpers.js +325 -0
  491. package/packages/dd-trace/src/opentelemetry/span.js +59 -109
  492. package/packages/dd-trace/src/opentelemetry/span_context.js +1 -0
  493. package/packages/dd-trace/src/opentelemetry/span_processor.js +7 -5
  494. package/packages/dd-trace/src/opentelemetry/trace/index.js +75 -0
  495. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +75 -0
  496. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +375 -0
  497. package/packages/dd-trace/src/opentelemetry/tracer.js +20 -69
  498. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +33 -17
  499. package/packages/dd-trace/src/opentracing/propagation/log.js +28 -8
  500. package/packages/dd-trace/src/opentracing/propagation/text_map.js +278 -148
  501. package/packages/dd-trace/src/opentracing/propagation/text_map_dsm.js +11 -11
  502. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +98 -32
  503. package/packages/dd-trace/src/opentracing/span.js +127 -73
  504. package/packages/dd-trace/src/opentracing/span_context.js +68 -3
  505. package/packages/dd-trace/src/opentracing/tracer.js +46 -19
  506. package/packages/dd-trace/src/payload-tagging/config/index.js +2 -2
  507. package/packages/dd-trace/src/plugin_manager.js +36 -14
  508. package/packages/dd-trace/src/plugins/apollo.js +3 -1
  509. package/packages/dd-trace/src/plugins/ci_plugin.js +387 -85
  510. package/packages/dd-trace/src/plugins/database.js +61 -18
  511. package/packages/dd-trace/src/plugins/index.js +14 -0
  512. package/packages/dd-trace/src/plugins/log_injection.js +56 -0
  513. package/packages/dd-trace/src/plugins/log_plugin.js +4 -44
  514. package/packages/dd-trace/src/plugins/outbound.js +1 -1
  515. package/packages/dd-trace/src/plugins/plugin.js +19 -28
  516. package/packages/dd-trace/src/plugins/storage.js +2 -2
  517. package/packages/dd-trace/src/plugins/tracing.js +70 -13
  518. package/packages/dd-trace/src/plugins/util/ci.js +127 -40
  519. package/packages/dd-trace/src/plugins/util/git-cache.js +23 -23
  520. package/packages/dd-trace/src/plugins/util/git.js +3 -1
  521. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +276 -0
  522. package/packages/dd-trace/src/plugins/util/llm.js +6 -1
  523. package/packages/dd-trace/src/plugins/util/stacktrace.js +2 -2
  524. package/packages/dd-trace/src/plugins/util/test.js +894 -65
  525. package/packages/dd-trace/src/plugins/util/url.js +71 -5
  526. package/packages/dd-trace/src/plugins/util/user-provided-git.js +18 -16
  527. package/packages/dd-trace/src/plugins/util/web.js +116 -180
  528. package/packages/dd-trace/src/priority_sampler.js +12 -21
  529. package/packages/dd-trace/src/profiling/config.js +132 -212
  530. package/packages/dd-trace/src/profiling/constants.js +4 -7
  531. package/packages/dd-trace/src/profiling/exporter_cli.js +10 -10
  532. package/packages/dd-trace/src/profiling/exporters/agent.js +61 -28
  533. package/packages/dd-trace/src/profiling/exporters/event_serializer.js +45 -14
  534. package/packages/dd-trace/src/profiling/exporters/file.js +16 -5
  535. package/packages/dd-trace/src/profiling/oom.js +71 -0
  536. package/packages/dd-trace/src/profiling/profiler.js +84 -105
  537. package/packages/dd-trace/src/profiling/profilers/event_plugins/crypto.js +32 -0
  538. package/packages/dd-trace/src/profiling/profilers/event_plugins/zlib.js +19 -0
  539. package/packages/dd-trace/src/profiling/profilers/events.js +57 -13
  540. package/packages/dd-trace/src/profiling/profilers/space.js +27 -16
  541. package/packages/dd-trace/src/profiling/profilers/wall.js +49 -35
  542. package/packages/dd-trace/src/profiling/ssi-heuristics.js +3 -3
  543. package/packages/dd-trace/src/propagation-hash/index.js +1 -1
  544. package/packages/dd-trace/src/proxy.js +50 -36
  545. package/packages/dd-trace/src/rate_limiter.js +1 -1
  546. package/packages/dd-trace/src/remote_config/index.js +6 -5
  547. package/packages/dd-trace/src/remote_config/scheduler.js +1 -1
  548. package/packages/dd-trace/src/ritm.js +6 -3
  549. package/packages/dd-trace/src/runtime_metrics/client.js +30 -0
  550. package/packages/dd-trace/src/runtime_metrics/index.js +14 -4
  551. package/packages/dd-trace/src/runtime_metrics/otlp_runtime_metrics.js +284 -0
  552. package/packages/dd-trace/src/runtime_metrics/runtime_metrics.js +42 -41
  553. package/packages/dd-trace/src/sampling_rule.js +7 -7
  554. package/packages/dd-trace/src/scope.js +10 -15
  555. package/packages/dd-trace/src/serverless.js +6 -7
  556. package/packages/dd-trace/src/service-naming/extra-services.js +14 -0
  557. package/packages/dd-trace/src/service-naming/index.js +1 -1
  558. package/packages/dd-trace/src/service-naming/schemas/definition.js +4 -1
  559. package/packages/dd-trace/src/service-naming/schemas/util.js +48 -3
  560. package/packages/dd-trace/src/service-naming/schemas/v0/graphql.js +6 -0
  561. package/packages/dd-trace/src/service-naming/schemas/v0/messaging.js +61 -2
  562. package/packages/dd-trace/src/service-naming/schemas/v0/serverless.js +12 -0
  563. package/packages/dd-trace/src/service-naming/schemas/v0/storage.js +60 -0
  564. package/packages/dd-trace/src/service-naming/schemas/v0/web.js +25 -1
  565. package/packages/dd-trace/src/service-naming/schemas/v0/websocket.js +5 -0
  566. package/packages/dd-trace/src/service-naming/schemas/v1/graphql.js +8 -0
  567. package/packages/dd-trace/src/service-naming/schemas/v1/messaging.js +32 -0
  568. package/packages/dd-trace/src/service-naming/schemas/v1/serverless.js +12 -0
  569. package/packages/dd-trace/src/service-naming/schemas/v1/storage.js +17 -0
  570. package/packages/dd-trace/src/service-naming/schemas/v1/web.js +23 -3
  571. package/packages/dd-trace/src/service-naming/schemas/v1/websocket.js +6 -0
  572. package/packages/dd-trace/src/service-naming/source-resolver.js +50 -0
  573. package/packages/dd-trace/src/span_format.js +269 -81
  574. package/packages/dd-trace/src/span_processor.js +13 -13
  575. package/packages/dd-trace/src/span_stats.js +101 -79
  576. package/packages/dd-trace/src/spanleak.js +1 -2
  577. package/packages/dd-trace/src/standalone/index.js +3 -25
  578. package/packages/dd-trace/src/startup-log.js +3 -3
  579. package/packages/dd-trace/src/tagger.js +2 -4
  580. package/packages/dd-trace/src/telemetry/dependencies.js +2 -2
  581. package/packages/dd-trace/src/telemetry/endpoints.js +7 -5
  582. package/packages/dd-trace/src/telemetry/index.js +2 -2
  583. package/packages/dd-trace/src/telemetry/logs/index.js +1 -1
  584. package/packages/dd-trace/src/telemetry/send-data.js +20 -20
  585. package/packages/dd-trace/src/telemetry/session-propagation.js +1 -1
  586. package/packages/dd-trace/src/telemetry/telemetry.js +16 -14
  587. package/packages/dd-trace/src/tracer.js +23 -9
  588. package/packages/dd-trace/src/tracer_metadata.js +1 -1
  589. package/packages/dd-trace/src/util.js +31 -0
  590. package/register.js +58 -1
  591. package/vendor/dist/@apm-js-collab/code-transformer/index.js +94 -42
  592. package/vendor/dist/@datadog/sketches-js/LICENSE +10 -36
  593. package/vendor/dist/@datadog/sketches-js/index.js +1 -1
  594. package/vendor/dist/pprof-format/index.js +1 -1
  595. package/vendor/dist/protobufjs/index.js +1 -1
  596. package/vendor/dist/protobufjs/minimal/index.js +1 -1
  597. package/vendor/dist/shell-quote/index.js +1 -1
  598. package/packages/datadog-plugin-graphql/src/resolve.js +0 -178
  599. package/packages/dd-trace/src/agent/url.js +0 -28
  600. package/packages/dd-trace/src/appsec/api_security_sampler.js +0 -117
  601. package/packages/dd-trace/src/lambda/runtime/ritm.js +0 -133
  602. package/packages/dd-trace/src/log/utils.js +0 -16
  603. package/packages/dd-trace/src/msgpack/encoder.js +0 -308
  604. package/packages/dd-trace/src/plugins/structured_log_plugin.js +0 -9
  605. package/scripts/preinstall.js +0 -34
  606. package/vendor/dist/ignore/LICENSE +0 -21
  607. package/vendor/dist/ignore/index.js +0 -1
  608. package/vendor/dist/opentracing/LICENSE +0 -201
  609. package/vendor/dist/opentracing/binary_carrier.d.ts +0 -11
  610. package/vendor/dist/opentracing/constants.d.ts +0 -61
  611. package/vendor/dist/opentracing/examples/demo/demo.d.ts +0 -2
  612. package/vendor/dist/opentracing/ext/tags.d.ts +0 -90
  613. package/vendor/dist/opentracing/functions.d.ts +0 -20
  614. package/vendor/dist/opentracing/global_tracer.d.ts +0 -14
  615. package/vendor/dist/opentracing/index.d.ts +0 -12
  616. package/vendor/dist/opentracing/index.js +0 -1
  617. package/vendor/dist/opentracing/mock_tracer/index.d.ts +0 -5
  618. package/vendor/dist/opentracing/mock_tracer/mock_context.d.ts +0 -13
  619. package/vendor/dist/opentracing/mock_tracer/mock_report.d.ts +0 -16
  620. package/vendor/dist/opentracing/mock_tracer/mock_span.d.ts +0 -50
  621. package/vendor/dist/opentracing/mock_tracer/mock_tracer.d.ts +0 -26
  622. package/vendor/dist/opentracing/noop.d.ts +0 -8
  623. package/vendor/dist/opentracing/reference.d.ts +0 -33
  624. package/vendor/dist/opentracing/span.d.ts +0 -147
  625. package/vendor/dist/opentracing/span_context.d.ts +0 -26
  626. package/vendor/dist/opentracing/test/api_compatibility.d.ts +0 -16
  627. package/vendor/dist/opentracing/test/mocktracer_implemenation.d.ts +0 -3
  628. package/vendor/dist/opentracing/test/noop_implementation.d.ts +0 -4
  629. package/vendor/dist/opentracing/test/opentracing_api.d.ts +0 -3
  630. package/vendor/dist/opentracing/test/unittest.d.ts +0 -2
  631. package/vendor/dist/opentracing/tracer.d.ts +0 -127
  632. package/vendor/dist/path-to-regexp/LICENSE +0 -21
  633. 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,378 @@ 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
+
965
1861
  function applySuiteSkipping (originalTests, rootDir, frameworkVersion) {
966
- const jestSuitesToRun = getJestSuitesToRun(skippableSuites, originalTests, rootDir || process.cwd())
1862
+ if (!isItrEnabled || !isSuitesSkippingEnabled) return originalTests
1863
+
1864
+ const repositoryRoot = getRepositoryRootFromTest(originalTests[0], rootDir)
1865
+ const jestSuitesToRun = getJestSuitesToRun(skippableSuites, originalTests, repositoryRoot, rootDir)
967
1866
  hasFilteredSkippableSuites = true
968
- log.debug('%d out of %d suites are going to run.', jestSuitesToRun.suitesToRun.length, originalTests.length)
1867
+ log.debug(
1868
+ 'Jest discovered %d suites; skipped %d using %d skippable candidates; %d suites will run.',
1869
+ originalTests.length,
1870
+ jestSuitesToRun.skippedSuites.length,
1871
+ skippableSuites.length,
1872
+ jestSuitesToRun.suitesToRun.length
1873
+ )
969
1874
  hasUnskippableSuites = jestSuitesToRun.hasUnskippableSuites
970
1875
  hasForcedToRunSuites = jestSuitesToRun.hasForcedToRunSuites
971
1876
 
972
1877
  isSuitesSkipped = jestSuitesToRun.suitesToRun.length !== originalTests.length
973
1878
  numSkippedSuites = jestSuitesToRun.skippedSuites.length
1879
+ skippedSuitesCoverage = isSuitesSkipped && isTiaCoverageBackfillEnabled() && hasSkippableSuitesCoverage()
1880
+ ? skippableSuitesCoverage
1881
+ : {}
1882
+ coverageBackfillContexts = isSuitesSkipped && isTiaCoverageBackfillEnabled()
1883
+ ? getTestContexts(originalTests)
1884
+ : undefined
1885
+ coverageBackfillFiles = isSuitesSkipped && isTiaCoverageBackfillEnabled() && hasSkippableSuitesCoverage()
1886
+ ? getCoverageBackfillFiles(skippableSuitesCoverage, repositoryRoot, getTestSuitePath)
1887
+ : undefined
974
1888
 
975
1889
  itrSkippedSuitesCh.publish({ skippedSuites: jestSuitesToRun.skippedSuites, frameworkVersion })
976
1890
 
977
1891
  return jestSuitesToRun.suitesToRun
978
1892
  }
979
1893
 
1894
+ function applySkippedCoverageToJestCoverageMap (coverageMap, rootDir) {
1895
+ if (!coverageMap || !isSuitesSkipped || !isTiaCoverageBackfillEnabled()) return
1896
+ applySkippedCoverageToCoverage(
1897
+ coverageMap,
1898
+ skippedSuitesCoverage,
1899
+ rootDir || process.cwd()
1900
+ )
1901
+ }
1902
+
1903
+ function getSessionFinishError (results) {
1904
+ const numFailedTestSuites = results?.numFailedTestSuites || 0
1905
+ const numFailedTests = results?.numFailedTests || 0
1906
+
1907
+ return new Error(`Failed test suites: ${numFailedTestSuites}. Failed tests: ${numFailedTests}`)
1908
+ }
1909
+
1910
+ function getTestSessionCoveragePayload (results, fallbackRootDir) {
1911
+ const payload = {}
1912
+ if (!shouldReportCodeCoverageLinesPct()) return payload
1913
+
1914
+ try {
1915
+ const coverageMap = results?.coverageMap || lastCoverageMap
1916
+ const coverageRootDir = lastCoverageMapRootDir ||
1917
+ repositoryRoot ||
1918
+ fallbackRootDir ||
1919
+ process.cwd()
1920
+ if (isSuitesSkipped) {
1921
+ applySkippedCoverageToJestCoverageMap(coverageMap, coverageRootDir)
1922
+ }
1923
+ payload.testCodeCoverageLinesTotal = getTestCoverageLinesPercentage(
1924
+ coverageMap,
1925
+ undefined,
1926
+ coverageRootDir
1927
+ )
1928
+ if (isTiaCoverageBackfillEnabled()) {
1929
+ payload.testSessionCoverageFiles = getExecutableFilesFromCoverage(coverageMap).map(({ filename, bitmap }) => ({
1930
+ filename: getTestSuitePath(filename, coverageRootDir),
1931
+ bitmap,
1932
+ }))
1933
+ }
1934
+ } catch {
1935
+ // ignore errors
1936
+ }
1937
+
1938
+ return payload
1939
+ }
1940
+
1941
+ function getNumBailFailures (results) {
1942
+ const numFailedTests = results?.numFailedTests || 0
1943
+ const numFailedSuites = results?.numRuntimeErrorTestSuites === undefined
1944
+ ? (numFailedTests === 0 ? results?.numFailedTestSuites || 0 : 0)
1945
+ : results.numRuntimeErrorTestSuites
1946
+
1947
+ return numFailedTests + numFailedSuites
1948
+ }
1949
+
1950
+ function shouldFinishBailTestSession (globalConfig, results) {
1951
+ return !!globalConfig?.bail && getNumBailFailures(results) >= globalConfig.bail
1952
+ }
1953
+
1954
+ async function waitForTestSessionFinish (payload) {
1955
+ if (!testSessionFinishCh.hasSubscribers || hasFinishedTestSession) return
1956
+
1957
+ hasFinishedTestSession = true
1958
+
1959
+ let timeoutId
1960
+
1961
+ const flushPromise = new Promise((resolve) => {
1962
+ payload.onDone = () => {
1963
+ clearTimeout(timeoutId)
1964
+ resolve()
1965
+ }
1966
+ })
1967
+
1968
+ const timeoutPromise = new Promise((resolve) => {
1969
+ timeoutId = realSetTimeout(() => {
1970
+ resolve('timeout')
1971
+ }, FLUSH_TIMEOUT)
1972
+ timeoutId.unref?.()
1973
+ })
1974
+
1975
+ testSessionFinishCh.publish(payload)
1976
+
1977
+ const waitingResult = await Promise.race([flushPromise, timeoutPromise])
1978
+
1979
+ if (waitingResult === 'timeout') {
1980
+ log.error('Timeout waiting for the tracer to flush')
1981
+ }
1982
+ }
1983
+
1984
+ function getTestSessionFinishPayload (status, error, extra = {}) {
1985
+ return {
1986
+ status,
1987
+ isSuitesSkipped,
1988
+ isSuitesSkippingEnabled,
1989
+ isCodeCoverageEnabled,
1990
+ isCoverageReportUploadEnabled,
1991
+ numSkippedSuites,
1992
+ hasUnskippableSuites,
1993
+ hasForcedToRunSuites,
1994
+ error,
1995
+ isEarlyFlakeDetectionEnabled,
1996
+ isEarlyFlakeDetectionFaulty,
1997
+ isTestManagementTestsEnabled,
1998
+ ...extra,
1999
+ }
2000
+ }
2001
+
2002
+ async function finishBailTestSession (results, fallbackRootDir) {
2003
+ await waitForTestSessionFinish(getTestSessionFinishPayload(
2004
+ 'fail',
2005
+ getSessionFinishError(results),
2006
+ getTestSessionCoveragePayload(results, fallbackRootDir)
2007
+ ))
2008
+ }
2009
+
2010
+ jestSessionState.finishBailTestSession = finishBailTestSession
2011
+
2012
+ function reporterDispatcherWrapper (reporterDispatcherPackage) {
2013
+ const ReporterDispatcher = reporterDispatcherPackage.default ?? reporterDispatcherPackage
2014
+ if (ReporterDispatcher?.prototype?.onRunComplete) {
2015
+ shimmer.wrap(ReporterDispatcher.prototype, 'onRunComplete', onRunComplete => function (contexts, results) {
2016
+ if (isSuitesSkipped && isTiaCoverageBackfillEnabled()) {
2017
+ applySkippedCoverageToJestCoverageMap(results?.coverageMap, getRepositoryRootFromContexts(contexts))
2018
+ }
2019
+ return onRunComplete.apply(this, arguments)
2020
+ })
2021
+ }
2022
+
2023
+ return reporterDispatcherPackage
2024
+ }
2025
+
2026
+ function wrapCoverageReporter (CoverageReporter, hookMeta) {
2027
+ if (!CoverageReporter?.prototype?.onRunComplete || wrappedCoverageReporters.has(CoverageReporter)) {
2028
+ return
2029
+ }
2030
+
2031
+ coverageReporterRequire = getHookRequire(hookMeta) || coverageReporterRequire
2032
+ if (coverageReporterRequire) {
2033
+ coverageReporterRequires.set(CoverageReporter, coverageReporterRequire)
2034
+ }
2035
+ coverageReporterClass = CoverageReporter
2036
+ wrappedCoverageReporters.add(CoverageReporter)
2037
+ if (CoverageReporter.prototype._addUntestedFiles) {
2038
+ shimmer.wrap(CoverageReporter.prototype, '_addUntestedFiles', addUntestedFiles => function (...args) {
2039
+ const rootDir = repositoryRoot || this._globalConfig?.rootDir || process.cwd()
2040
+ args[0] = getCoverageBackfillContexts(args[0])
2041
+ const result = addUntestedFiles.apply(this, args)
2042
+ if (!isSuitesSkipped || !isTiaCoverageBackfillEnabled()) return result
2043
+
2044
+ const addBackfillAndApplyCoverage = () => {
2045
+ return addCoverageBackfillUntestedFiles({
2046
+ coverageMap: this._coverageMap,
2047
+ testContexts: args[0],
2048
+ rootDir,
2049
+ CoverageReporter,
2050
+ coverageBackfillFiles,
2051
+ getCoverageBackfillRequire,
2052
+ }).then(() => {
2053
+ applySkippedCoverageToJestCoverageMap(this._coverageMap, rootDir)
2054
+ })
2055
+ }
2056
+
2057
+ return Promise.resolve(result).then(value => {
2058
+ return addBackfillAndApplyCoverage().then(() => value)
2059
+ })
2060
+ })
2061
+ }
2062
+
2063
+ shimmer.wrap(CoverageReporter.prototype, 'onRunComplete', onRunComplete => async function (contexts, results) {
2064
+ const coverageContexts = getCoverageBackfillContexts(contexts)
2065
+ const rootDir = getRepositoryRootFromContexts(coverageContexts, this._globalConfig?.rootDir)
2066
+ const coverageMap = results?.coverageMap || this._coverageMap
2067
+ if (isSuitesSkipped && isTiaCoverageBackfillEnabled()) {
2068
+ await addCoverageBackfillUntestedFiles({
2069
+ coverageMap,
2070
+ testContexts: coverageContexts,
2071
+ rootDir,
2072
+ CoverageReporter,
2073
+ coverageBackfillFiles,
2074
+ getCoverageBackfillRequire,
2075
+ })
2076
+ applySkippedCoverageToJestCoverageMap(coverageMap, rootDir)
2077
+ }
2078
+ lastCoverageMap = coverageMap
2079
+ lastCoverageMapRootDir = rootDir
2080
+ const result = await onRunComplete.call(this, coverageContexts, results)
2081
+ if (shouldFinishBailTestSession(this._globalConfig, results)) {
2082
+ await finishBailTestSession(results, rootDir)
2083
+ }
2084
+ return result
2085
+ })
2086
+ }
2087
+
2088
+ function reportersWrapper (reportersPackage, _version, _isIitm, hookMeta) {
2089
+ wrapCoverageReporter(reportersPackage.CoverageReporter, hookMeta)
2090
+ return reportersPackage
2091
+ }
2092
+
2093
+ function coverageReporterWrapper (coverageReporterPackage, _version, _isIitm, hookMeta) {
2094
+ wrapCoverageReporter(coverageReporterPackage.default ?? coverageReporterPackage, hookMeta)
2095
+ return coverageReporterPackage
2096
+ }
2097
+
2098
+ addHook({
2099
+ name: 'jest-environment-node',
2100
+ versions: [MINIMUM_JEST_VERSION],
2101
+ }, getTestEnvironment)
2102
+
980
2103
  addHook({
981
2104
  name: 'jest-environment-node',
982
- versions: ['>=24.8.0'],
2105
+ file: 'build/index.js',
2106
+ versions: [MINIMUM_JEST_VERSION],
983
2107
  }, getTestEnvironment)
984
2108
 
985
2109
  addHook({
986
2110
  name: 'jest-environment-jsdom',
987
- versions: ['>=24.8.0'],
2111
+ versions: [MINIMUM_JEST_VERSION],
2112
+ }, getTestEnvironment)
2113
+
2114
+ addHook({
2115
+ name: 'jest-environment-jsdom',
2116
+ file: 'build/index.js',
2117
+ versions: [MINIMUM_JEST_VERSION],
988
2118
  }, getTestEnvironment)
989
2119
 
990
2120
  addHook({
@@ -1007,6 +2137,12 @@ function getWrappedScheduleTests (scheduleTests, frameworkVersion) {
1007
2137
  }
1008
2138
  }
1009
2139
 
2140
+ function getChannelPromise (channelToPublishTo, payload = {}) {
2141
+ return new Promise(resolve => {
2142
+ channelToPublishTo.publish({ ...payload, onDone: resolve })
2143
+ })
2144
+ }
2145
+
1010
2146
  function searchSourceWrapper (searchSourcePackage, frameworkVersion) {
1011
2147
  const SearchSource = searchSourcePackage.default ?? searchSourcePackage
1012
2148
 
@@ -1015,7 +2151,9 @@ function searchSourceWrapper (searchSourcePackage, frameworkVersion) {
1015
2151
  const [{ rootDir, shard }] = arguments
1016
2152
 
1017
2153
  if (isKnownTestsEnabled) {
1018
- const projectSuites = testPaths.tests.map(test => getTestSuitePath(test.path, test.context.config.rootDir))
2154
+ const projectSuites = testPaths.tests.map(test => {
2155
+ return getTestSuitePath(test.path, getRepositoryRootFromTest(test, test.context.config.rootDir))
2156
+ })
1019
2157
 
1020
2158
  // If the `jest` key does not exist in the known tests response, we consider the Early Flake detection faulty.
1021
2159
  const isFaulty = !knownTests?.jest ||
@@ -1035,14 +2173,11 @@ function searchSourceWrapper (searchSourcePackage, frameworkVersion) {
1035
2173
  }
1036
2174
  }
1037
2175
 
2176
+ // When Jest sharding is enabled, filter after Jest picks this process's shard. Different shards usually run in
2177
+ // different CI jobs, so their skippable requests can happen at different times and receive different responses.
2178
+ // Filtering before Jest shards would make each job shard a different base test list, which can cause duplicate
2179
+ // suite execution across shards.
1038
2180
  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
2181
  return testPaths
1047
2182
  }
1048
2183
  const { tests } = testPaths
@@ -1056,6 +2191,10 @@ function searchSourceWrapper (searchSourcePackage, frameworkVersion) {
1056
2191
 
1057
2192
  function getCliWrapper (isNewJestVersion) {
1058
2193
  return function cliWrapper (cli, jestVersion) {
2194
+ warnDeprecatedJestVersion(jestVersion)
2195
+ isJestCoverageBackfillSupported = !!jestVersion &&
2196
+ satisfies(jestVersion, MINIMUM_JEST_COVERAGE_BACKFILL_VERSION)
2197
+
1059
2198
  if (isNewJestVersion) {
1060
2199
  cli = shimmer.wrap(
1061
2200
  cli,
@@ -1065,23 +2204,22 @@ function getCliWrapper (isNewJestVersion) {
1065
2204
  )
1066
2205
  }
1067
2206
  return shimmer.wrap(cli, 'runCLI', runCLI => async function () {
1068
- let onDone
1069
- const configurationPromise = new Promise((resolve) => {
1070
- onDone = resolve
1071
- })
1072
2207
  if (!libraryConfigurationCh.hasSubscribers) {
1073
2208
  return runCLI.apply(this, arguments)
1074
2209
  }
1075
2210
 
1076
- libraryConfigurationCh.publish({ onDone, frameworkVersion: jestVersion })
2211
+ resetSuiteSkippingRunState()
2212
+ hasFinishedTestSession = false
1077
2213
 
1078
2214
  try {
1079
- const { err, libraryConfig } = await configurationPromise
2215
+ const { err, libraryConfig } = await getChannelPromise(libraryConfigurationCh, {
2216
+ frameworkVersion: jestVersion,
2217
+ })
1080
2218
  if (!err) {
1081
2219
  isCodeCoverageEnabled = libraryConfig.isCodeCoverageEnabled
1082
- isSuitesSkippingEnabled = libraryConfig.isSuitesSkippingEnabled
1083
- isKeepingCoverageConfiguration =
1084
- libraryConfig.isKeepingCoverageConfiguration ?? isKeepingCoverageConfiguration
2220
+ isCoverageReportUploadEnabled = libraryConfig.isCoverageReportUploadEnabled
2221
+ isItrEnabled = libraryConfig.isItrEnabled
2222
+ isSuitesSkippingEnabled = isItrEnabled && libraryConfig.isSuitesSkippingEnabled
1085
2223
  isEarlyFlakeDetectionEnabled = libraryConfig.isEarlyFlakeDetectionEnabled
1086
2224
  earlyFlakeDetectionNumRetries = libraryConfig.earlyFlakeDetectionNumRetries
1087
2225
  earlyFlakeDetectionSlowTestRetries = libraryConfig.earlyFlakeDetectionSlowTestRetries ?? {}
@@ -1095,15 +2233,22 @@ function getCliWrapper (isNewJestVersion) {
1095
2233
  log.error('Jest library configuration error', err)
1096
2234
  }
1097
2235
 
1098
- if (isKnownTestsEnabled) {
1099
- const knownTestsPromise = new Promise((resolve) => {
1100
- onDone = resolve
1101
- })
1102
-
1103
- knownTestsCh.publish({ onDone })
2236
+ const {
2237
+ knownTestsResponse,
2238
+ testManagementTestsResponse,
2239
+ skippableSuitesResponse,
2240
+ } = await getTestOptimizationRequestResults({
2241
+ isKnownTestsEnabled,
2242
+ isTestManagementTestsEnabled,
2243
+ isSuitesSkippingEnabled,
2244
+ getKnownTests: () => getChannelPromise(knownTestsCh),
2245
+ getTestManagementTests: () => getChannelPromise(testManagementTestsCh),
2246
+ getSkippableSuites: () => getChannelPromise(skippableSuitesCh),
2247
+ })
1104
2248
 
2249
+ if (isKnownTestsEnabled) {
1105
2250
  try {
1106
- const { err, knownTests: receivedKnownTests } = await knownTestsPromise
2251
+ const { err, knownTests: receivedKnownTests } = knownTestsResponse || await getChannelPromise(knownTestsCh)
1107
2252
  if (err) {
1108
2253
  // We disable EFD if there has been an error in the known tests request
1109
2254
  isEarlyFlakeDetectionEnabled = false
@@ -1117,16 +2262,19 @@ function getCliWrapper (isNewJestVersion) {
1117
2262
  }
1118
2263
 
1119
2264
  if (isSuitesSkippingEnabled) {
1120
- const skippableSuitesPromise = new Promise((resolve) => {
1121
- onDone = resolve
1122
- })
1123
-
1124
- skippableSuitesCh.publish({ onDone })
1125
-
1126
2265
  try {
1127
- const { err, skippableSuites: receivedSkippableSuites } = await skippableSuitesPromise
1128
- if (!err) {
2266
+ const {
2267
+ err,
2268
+ skippableSuites: receivedSkippableSuites,
2269
+ skippableSuitesCoverage: receivedSkippableSuitesCoverage,
2270
+ } = skippableSuitesResponse || await getChannelPromise(skippableSuitesCh)
2271
+ if (err) {
2272
+ skippableSuitesCoverage = {}
2273
+ skippedSuitesCoverage = {}
2274
+ } else {
1129
2275
  skippableSuites = receivedSkippableSuites
2276
+ skippableSuitesCoverage = receivedSkippableSuitesCoverage || {}
2277
+ skippedSuitesCoverage = {}
1130
2278
  }
1131
2279
  } catch (err) {
1132
2280
  log.error('Jest test-suite skippable error', err)
@@ -1134,14 +2282,9 @@ function getCliWrapper (isNewJestVersion) {
1134
2282
  }
1135
2283
 
1136
2284
  if (isTestManagementTestsEnabled) {
1137
- const testManagementTestsPromise = new Promise((resolve) => {
1138
- onDone = resolve
1139
- })
1140
-
1141
- testManagementTestsCh.publish({ onDone })
1142
-
1143
2285
  try {
1144
- const { err, testManagementTests: receivedTestManagementTests } = await testManagementTestsPromise
2286
+ const { err, testManagementTests: receivedTestManagementTests } =
2287
+ testManagementTestsResponse || await getChannelPromise(testManagementTestsCh)
1145
2288
  if (err) {
1146
2289
  isTestManagementTestsEnabled = false
1147
2290
  testManagementTests = {}
@@ -1155,14 +2298,8 @@ function getCliWrapper (isNewJestVersion) {
1155
2298
  }
1156
2299
 
1157
2300
  if (isImpactedTestsEnabled) {
1158
- const impactedTestsPromise = new Promise((resolve) => {
1159
- onDone = resolve
1160
- })
1161
-
1162
- modifiedFilesCh.publish({ onDone })
1163
-
1164
2301
  try {
1165
- const { err, modifiedFiles: receivedModifiedFiles } = await impactedTestsPromise
2302
+ const { err, modifiedFiles: receivedModifiedFiles } = await getChannelPromise(modifiedFilesCh)
1166
2303
  if (!err) {
1167
2304
  modifiedFiles = receivedModifiedFiles
1168
2305
  }
@@ -1172,13 +2309,15 @@ function getCliWrapper (isNewJestVersion) {
1172
2309
  }
1173
2310
 
1174
2311
  const processArgv = process.argv.slice(2).join(' ')
1175
- testSessionStartCh.publish({ command: `jest ${processArgv}`, frameworkVersion: jestVersion })
2312
+ testSessionStartCh.publish({
2313
+ command: `jest ${processArgv}`,
2314
+ frameworkVersion: jestVersion,
2315
+ })
1176
2316
 
1177
2317
  const result = await runCLI.apply(this, arguments)
1178
2318
 
1179
2319
  const {
1180
2320
  results: {
1181
- coverageMap,
1182
2321
  numFailedTestSuites,
1183
2322
  numFailedTests,
1184
2323
  numRuntimeErrorTestSuites = 0,
@@ -1193,17 +2332,6 @@ function getCliWrapper (isNewJestVersion) {
1193
2332
  const hasRunLevelFailure = runExecError != null || wasInterrupted === true
1194
2333
  const mustNotFlipSuccess = hasSuiteLevelFailures || hasRunLevelFailure
1195
2334
 
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
2335
  /**
1208
2336
  * If Early Flake Detection (EFD) is enabled the logic is as follows:
1209
2337
  * - If all attempts for a test are failing, the test has failed and we will let the test process fail.
@@ -1220,9 +2348,7 @@ function getCliWrapper (isNewJestVersion) {
1220
2348
  for (const { testResults, testFilePath } of result.results.testResults) {
1221
2349
  const suite = getTestSuitePath(testFilePath, result.globalConfig.rootDir)
1222
2350
  for (const { fullName } of testResults) {
1223
- const name = testSuiteAbsolutePathsWithFastCheck.has(testFilePath)
1224
- ? fullName.replace(SEED_SUFFIX_RE, '')
1225
- : fullName
2351
+ const name = removeSeedSuffixFromTestName(fullName)
1226
2352
  fullNameToSuite.set(name, suite)
1227
2353
  }
1228
2354
  }
@@ -1254,17 +2380,15 @@ function getCliWrapper (isNewJestVersion) {
1254
2380
  }
1255
2381
 
1256
2382
  let numFailedQuarantinedTests = 0
1257
- let numFailedQuarantinedOrDisabledAttemptedToFixTests = 0
2383
+ let numSuppressedQuarantinedTests = 0
1258
2384
  if (isTestManagementTestsEnabled) {
1259
2385
  const failedTests = result
1260
2386
  .results
1261
2387
  .testResults.flatMap(({ testResults, testFilePath: testSuiteAbsolutePath }) => (
1262
2388
  testResults.map(({ fullName: testName, status }) => (
1263
2389
  {
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,
2390
+ // Strip seed suffix so the name matches what was reported via TEST_NAME.
2391
+ testName: removeSeedSuffixFromTestName(testName),
1268
2392
  testSuiteAbsolutePath,
1269
2393
  status,
1270
2394
  }
@@ -1281,55 +2405,73 @@ function getCliWrapper (isNewJestVersion) {
1281
2405
  ?.tests
1282
2406
  ?.[testName]
1283
2407
  ?.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) {
2408
+ if (testManagementTest?.quarantined && !testManagementTest?.attempt_to_fix) {
1289
2409
  numFailedQuarantinedTests++
1290
2410
  quarantineIgnoredNames.push(`${testSuite} › ${testName}`)
1291
2411
  }
1292
2412
  }
1293
2413
 
2414
+ // Include quarantined tests whose errors were suppressed at test_done time.
2415
+ // These tests don't appear as failed in Jest's results because their errors were cleared
2416
+ // to prevent --bail from stopping the run, but they should still be counted for the summary.
2417
+ for (const name of quarantinedFailingTests) {
2418
+ if (!quarantineIgnoredNames.includes(name)) {
2419
+ numSuppressedQuarantinedTests++
2420
+ quarantineIgnoredNames.push(name)
2421
+ }
2422
+ }
2423
+ quarantinedFailingTests.clear()
2424
+
1294
2425
  // 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)
2426
+ // Attempt-to-fix tests ignore quarantine/disabled suppression and keep their framework result.
1298
2427
  // Skip if EFD block already flipped (to avoid logging twice)
2428
+ // Only use visible failures (from Jest results) for the flip check.
2429
+ // Suppressed quarantine failures are not in numFailedTests.
2430
+ const visibleQuarantineFailures = numFailedQuarantinedTests
1299
2431
  if (
1300
2432
  !result.results.success &&
1301
2433
  !mustNotFlipSuccess &&
1302
- (numFailedQuarantinedOrDisabledAttemptedToFixTests !== 0 || numFailedQuarantinedTests !== 0) &&
1303
- result.results.numFailedTests ===
1304
- numFailedQuarantinedTests + numFailedQuarantinedOrDisabledAttemptedToFixTests
2434
+ visibleQuarantineFailures !== 0 &&
2435
+ result.results.numFailedTests === visibleQuarantineFailures
1305
2436
  ) {
1306
2437
  result.results.success = true
1307
- ignoredFailuresSummary = {
1308
- efdNames: [],
1309
- quarantineNames: quarantineIgnoredNames,
1310
- totalCount: numFailedQuarantinedTests + numFailedQuarantinedOrDisabledAttemptedToFixTests,
2438
+ }
2439
+
2440
+ const totalQuarantineFailures = visibleQuarantineFailures + numSuppressedQuarantinedTests
2441
+ if (totalQuarantineFailures > 0) {
2442
+ if (ignoredFailuresSummary) {
2443
+ ignoredFailuresSummary.quarantineNames = quarantineIgnoredNames
2444
+ ignoredFailuresSummary.totalCount += totalQuarantineFailures
2445
+ } else {
2446
+ ignoredFailuresSummary = {
2447
+ efdNames: [],
2448
+ quarantineNames: quarantineIgnoredNames,
2449
+ totalCount: totalQuarantineFailures,
2450
+ }
1311
2451
  }
1312
2452
  }
1313
2453
  }
1314
2454
 
1315
2455
  // Combined check: if all failed tests are accounted for by EFD (flaky retries) and/or quarantine,
1316
2456
  // we should consider the suite passed even when neither check alone covers all failures.
2457
+ // Only visible failures (in Jest results) are compared — suppressed quarantine failures
2458
+ // are already removed from numFailedTests at test_done time.
1317
2459
  if (
1318
2460
  !result.results.success &&
1319
2461
  !mustNotFlipSuccess &&
1320
2462
  (isEarlyFlakeDetectionEnabled || isTestManagementTestsEnabled)
1321
2463
  ) {
1322
- const totalIgnoredFailures =
1323
- numEfdFailedTestsToIgnore + numFailedQuarantinedTests + numFailedQuarantinedOrDisabledAttemptedToFixTests
2464
+ const visibleIgnoredFailures =
2465
+ numEfdFailedTestsToIgnore + numFailedQuarantinedTests
1324
2466
  if (
1325
- totalIgnoredFailures !== 0 &&
1326
- result.results.numFailedTests === totalIgnoredFailures
2467
+ visibleIgnoredFailures !== 0 &&
2468
+ result.results.numFailedTests === visibleIgnoredFailures
1327
2469
  ) {
1328
2470
  result.results.success = true
1329
2471
  ignoredFailuresSummary = {
1330
2472
  efdNames: efdIgnoredNames,
1331
2473
  quarantineNames: quarantineIgnoredNames,
1332
- totalCount: totalIgnoredFailures,
2474
+ totalCount: visibleIgnoredFailures + numSuppressedQuarantinedTests,
1333
2475
  }
1334
2476
  }
1335
2477
  }
@@ -1343,43 +2485,9 @@ function getCliWrapper (isNewJestVersion) {
1343
2485
  error = new Error(`Failed test suites: ${numFailedTestSuites}. Failed tests: ${numFailedTests}`)
1344
2486
  }
1345
2487
 
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
- }
2488
+ await waitForTestSessionFinish(getTestSessionFinishPayload(status, error, {
2489
+ ...getTestSessionCoveragePayload(result.results, result.globalConfig?.rootDir),
2490
+ }))
1383
2491
 
1384
2492
  if (codeCoverageReportCh.hasSubscribers) {
1385
2493
  const rootDir = result.globalConfig?.rootDir || process.cwd()
@@ -1388,9 +2496,9 @@ function getCliWrapper (isNewJestVersion) {
1388
2496
  })
1389
2497
  }
1390
2498
 
1391
- logSessionSummary(ignoredFailuresSummary)
2499
+ logSessionSummary(ignoredFailuresSummary, getAttemptToFixExecutionsFromJestResults(result))
1392
2500
 
1393
- numSkippedSuites = 0
2501
+ resetSuiteSkippingRunState()
1394
2502
 
1395
2503
  return result
1396
2504
  }, {
@@ -1399,32 +2507,49 @@ function getCliWrapper (isNewJestVersion) {
1399
2507
  }
1400
2508
  }
1401
2509
 
1402
- function coverageReporterWrapper (coverageReporter) {
1403
- const CoverageReporter = coverageReporter.default ?? coverageReporter
2510
+ function shouldWaitForTestSuiteFinish (environment) {
2511
+ return isJestWorker && environment.globalConfig?.workerIdleMemoryLimit !== undefined
2512
+ }
2513
+
2514
+ function publishTestSuiteFinish (payload, waitForFinish) {
2515
+ if (!testSuiteFinishCh.hasSubscribers) return
1404
2516
 
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)
2517
+ if (!waitForFinish) {
2518
+ testSuiteFinishCh.publish(payload)
2519
+ return
2520
+ }
2521
+
2522
+ return new Promise(resolve => {
2523
+ testSuiteFinishCh.publish({
2524
+ ...payload,
2525
+ waitForFinish,
2526
+ onDone: resolve,
2527
+ })
1419
2528
  })
2529
+ }
1420
2530
 
1421
- return coverageReporter
2531
+ function cleanupTestSuiteState (testSuiteAbsolutePath) {
2532
+ testSuiteMockedFiles.delete(testSuiteAbsolutePath)
2533
+ testSuiteJestObjects.delete(testSuiteAbsolutePath)
2534
+ }
2535
+
2536
+ /**
2537
+ * Rechecks custom handlers after Jest has finished constructing the environment.
2538
+ *
2539
+ * @param {object} environment
2540
+ * @returns {void}
2541
+ */
2542
+ function wrapEnvironmentCustomHandleTestEvent (environment) {
2543
+ const datadogHandleTestEvent = environment[DD_JEST_HANDLE_TEST_EVENT_DATADOG]
2544
+ if (typeof environment.wrapCustomHandleTestEvent === 'function' && datadogHandleTestEvent) {
2545
+ environment.wrapCustomHandleTestEvent(datadogHandleTestEvent)
2546
+ }
1422
2547
  }
1423
2548
 
1424
2549
  addHook({
1425
2550
  name: '@jest/core',
1426
2551
  file: 'build/TestScheduler.js',
1427
- versions: ['>=27.0.0'],
2552
+ versions: [MINIMUM_JEST_TEST_SCHEDULER_VERSION],
1428
2553
  }, (testSchedulerPackage, frameworkVersion) => {
1429
2554
  const oldCreateTestScheduler = testSchedulerPackage.createTestScheduler
1430
2555
  const newCreateTestScheduler = async function () {
@@ -1440,24 +2565,23 @@ addHook({
1440
2565
  return testSchedulerPackage
1441
2566
  })
1442
2567
 
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
- })
2568
+ if (DD_MAJOR < 6) {
2569
+ addHook({
2570
+ name: '@jest/core',
2571
+ file: 'build/TestScheduler.js',
2572
+ versions: ['>=24.8.0 <27.0.0'],
2573
+ }, (testSchedulerPackage, frameworkVersion) => {
2574
+ shimmer.wrap(
2575
+ testSchedulerPackage.default.prototype,
2576
+ 'scheduleTests', scheduleTests => getWrappedScheduleTests(scheduleTests, frameworkVersion)
2577
+ )
2578
+ return testSchedulerPackage
2579
+ })
2580
+ }
1454
2581
 
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)
2582
+ function testSequencerWrapper (sequencerPackage, frameworkVersion) {
2583
+ shimmer.wrap(sequencerPackage.default.prototype, 'shard', shard => function (...args) {
2584
+ const shardedTests = shard.apply(this, args)
1461
2585
 
1462
2586
  if (!shardedTests.length || !isSuitesSkippingEnabled || !skippableSuites.length) {
1463
2587
  return shardedTests
@@ -1468,31 +2592,23 @@ addHook({
1468
2592
  return applySuiteSkipping(shardedTests, rootDir, frameworkVersion)
1469
2593
  })
1470
2594
  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)
2595
+ }
1478
2596
 
1479
2597
  addHook({
1480
- name: '@jest/reporters',
1481
- file: 'build/CoverageReporter.js',
1482
- versions: ['>=26.6.2'],
1483
- }, coverageReporterWrapper)
2598
+ name: '@jest/test-sequencer',
2599
+ versions: ['>=28'],
2600
+ }, testSequencerWrapper)
1484
2601
 
1485
2602
  addHook({
1486
- name: '@jest/reporters',
1487
- versions: ['>=30.0.0'],
1488
- }, (reporters) => {
1489
- return shimmer.wrap(reporters, 'CoverageReporter', coverageReporterWrapper, { replaceGetter: true })
1490
- })
2603
+ name: '@jest/test-sequencer',
2604
+ file: 'build/index.js',
2605
+ versions: ['>=28'],
2606
+ }, testSequencerWrapper)
1491
2607
 
1492
2608
  addHook({
1493
2609
  name: '@jest/core',
1494
2610
  file: 'build/cli/index.js',
1495
- versions: ['>=24.8.0 <30.0.0'],
2611
+ versions: [MINIMUM_JEST_VERSION_BEFORE_30],
1496
2612
  }, getCliWrapper(false))
1497
2613
 
1498
2614
  addHook({
@@ -1500,13 +2616,41 @@ addHook({
1500
2616
  versions: ['>=30.0.0'],
1501
2617
  }, getCliWrapper(true))
1502
2618
 
2619
+ addHook({
2620
+ name: '@jest/core',
2621
+ file: 'build/ReporterDispatcher.js',
2622
+ versions: [MINIMUM_JEST_VERSION],
2623
+ }, reporterDispatcherWrapper)
2624
+
2625
+ if (DD_MAJOR < 6) {
2626
+ addHook({
2627
+ name: '@jest/reporters',
2628
+ file: 'build/coverage_reporter.js',
2629
+ versions: ['>=24.8.0 <26.6.2'],
2630
+ }, coverageReporterWrapper)
2631
+ }
2632
+
2633
+ addHook({
2634
+ name: '@jest/reporters',
2635
+ versions: ['>=30.0.0'],
2636
+ }, reportersWrapper)
2637
+
2638
+ addHook({
2639
+ name: '@jest/reporters',
2640
+ file: 'build/CoverageReporter.js',
2641
+ versions: [DD_MAJOR >= 6 ? '>=28.0.0' : '>=26.6.2'],
2642
+ }, coverageReporterWrapper)
2643
+
1503
2644
  function jestAdapterWrapper (jestAdapter, jestVersion) {
1504
2645
  const adapter = jestAdapter.default ?? jestAdapter
1505
- const newAdapter = shimmer.wrapFunction(adapter, adapter => function () {
1506
- const environment = arguments[2]
2646
+ const newAdapter = shimmer.wrapFunction(adapter, adapter => function (...args) {
2647
+ const environment = args[2]
1507
2648
  if (!environment || !environment.testEnvironmentOptions) {
1508
- return adapter.apply(this, arguments)
2649
+ return adapter.apply(this, args)
1509
2650
  }
2651
+
2652
+ wrapEnvironmentCustomHandleTestEvent(environment)
2653
+
1510
2654
  testSuiteStartCh.publish({
1511
2655
  testSuite: environment.testSuite,
1512
2656
  testEnvironmentOptions: environment.testEnvironmentOptions,
@@ -1515,7 +2659,7 @@ function jestAdapterWrapper (jestAdapter, jestVersion) {
1515
2659
  frameworkVersion: jestVersion,
1516
2660
  testSuiteAbsolutePath: environment.testSuiteAbsolutePath,
1517
2661
  })
1518
- return adapter.apply(this, arguments).then(suiteResults => {
2662
+ return adapter.apply(this, args).then(suiteResults => {
1519
2663
  const { numFailingTests, skipped, failureMessage: errorMessage } = suiteResults
1520
2664
  let status = 'pass'
1521
2665
  if (skipped) {
@@ -1532,10 +2676,13 @@ function jestAdapterWrapper (jestAdapter, jestVersion) {
1532
2676
  if (environment.testEnvironmentOptions?._ddTestCodeCoverageEnabled) {
1533
2677
  const root = environment.repositoryRoot || environment.rootDir
1534
2678
 
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) || [])
2679
+ const coverageFiles = getCoveredFilesFromCoverage(environment.global.__coverage__)
2680
+ .map(file => ({
2681
+ ...file,
2682
+ filename: getTestSuitePath(file.filename, root),
2683
+ }))
2684
+ const mockedFiles = getMockedFiles(environment.testSuiteAbsolutePath)
2685
+ .map(file => getTestSuitePath(file, root))
1539
2686
 
1540
2687
  testSuiteCodeCoverageCh.publish({
1541
2688
  coverageFiles,
@@ -1544,19 +2691,51 @@ function jestAdapterWrapper (jestAdapter, jestVersion) {
1544
2691
  testSuiteAbsolutePath: environment.testSuiteAbsolutePath,
1545
2692
  })
1546
2693
  }
1547
- testSuiteFinishCh.publish({ status, errorMessage, testSuiteAbsolutePath: environment.testSuiteAbsolutePath })
2694
+ const waitForFinish = shouldWaitForTestSuiteFinish(environment)
2695
+ const finishPayload = {
2696
+ status,
2697
+ errorMessage,
2698
+ testSuiteAbsolutePath: environment.testSuiteAbsolutePath,
2699
+ }
2700
+ if (waitForFinish) {
2701
+ const finishPromise = publishTestSuiteFinish(finishPayload, waitForFinish)
2702
+ if (finishPromise) {
2703
+ return finishPromise.then(() => {
2704
+ // Cleanup per-suite state to avoid memory leaks
2705
+ cleanupTestSuiteState(environment.testSuiteAbsolutePath)
2706
+
2707
+ return suiteResults
2708
+ })
2709
+ }
2710
+ }
2711
+ publishTestSuiteFinish(finishPayload, waitForFinish)
1548
2712
 
1549
2713
  // Cleanup per-suite state to avoid memory leaks
1550
- testSuiteMockedFiles.delete(environment.testSuiteAbsolutePath)
1551
- testSuiteJestObjects.delete(environment.testSuiteAbsolutePath)
2714
+ cleanupTestSuiteState(environment.testSuiteAbsolutePath)
1552
2715
 
1553
2716
  return suiteResults
1554
2717
  }).catch(error => {
1555
- testSuiteFinishCh.publish({ status: 'fail', error, testSuiteAbsolutePath: environment.testSuiteAbsolutePath })
2718
+ const waitForFinish = shouldWaitForTestSuiteFinish(environment)
2719
+ const finishPayload = {
2720
+ status: 'fail',
2721
+ error,
2722
+ testSuiteAbsolutePath: environment.testSuiteAbsolutePath,
2723
+ }
2724
+ if (waitForFinish) {
2725
+ const finishPromise = publishTestSuiteFinish(finishPayload, waitForFinish)
2726
+ if (finishPromise) {
2727
+ return finishPromise.then(() => {
2728
+ // Cleanup per-suite state to avoid memory leaks
2729
+ cleanupTestSuiteState(environment.testSuiteAbsolutePath)
2730
+
2731
+ throw error
2732
+ })
2733
+ }
2734
+ }
2735
+ publishTestSuiteFinish(finishPayload, waitForFinish)
1556
2736
 
1557
2737
  // Cleanup per-suite state to avoid memory leaks
1558
- testSuiteMockedFiles.delete(environment.testSuiteAbsolutePath)
1559
- testSuiteJestObjects.delete(environment.testSuiteAbsolutePath)
2738
+ cleanupTestSuiteState(environment.testSuiteAbsolutePath)
1560
2739
 
1561
2740
  throw error
1562
2741
  })
@@ -1579,45 +2758,54 @@ addHook({
1579
2758
  addHook({
1580
2759
  name: 'jest-circus',
1581
2760
  file: 'build/legacy-code-todo-rewrite/jestAdapter.js',
1582
- versions: ['>=24.8.0'],
2761
+ versions: [MINIMUM_JEST_VERSION],
1583
2762
  }, jestAdapterWrapper)
1584
2763
 
1585
2764
  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
-
2765
+ repositoryRoot = getJestRepositoryRoot(readConfigsResult)
1594
2766
  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
- }
2767
+ const isCodeCoverageEnabledBecauseOfUs = shouldCollectJestCoverageForTia() && !isUserCodeCoverageEnabled
1600
2768
 
1601
2769
  if (isCodeCoverageEnabledBecauseOfUs) {
1602
- const globalConfig = {
2770
+ readConfigsResult.globalConfig = {
1603
2771
  ...readConfigsResult.globalConfig,
1604
2772
  collectCoverage: true,
2773
+ coverageReporters: ['none'],
1605
2774
  }
1606
- readConfigsResult.globalConfig = globalConfig
2775
+ readConfigsResult.configs = readConfigsResult.configs.map(config => ({
2776
+ ...config,
2777
+ coverageReporters: ['none'],
2778
+ }))
2779
+ }
2780
+
2781
+ // We can't directly use the parent process flags when reporting suite coverage in `jestAdapterWrapper`
2782
+ // because `jestAdapterWrapper` runs in a different process. We have to go through `testEnvironmentOptions`.
2783
+ const configs = readConfigsResult.configs.map(config => {
2784
+ const testEnvironmentOptions = config.testEnvironmentOptions || {}
2785
+ testEnvironmentOptions._ddRepositoryRoot = repositoryRoot
2786
+ testEnvironmentOptions._ddTestCodeCoverageEnabled = shouldReportJestSuiteCoverageForTia()
2787
+
2788
+ return {
2789
+ ...config,
2790
+ testEnvironmentOptions,
2791
+ }
2792
+ })
2793
+ readConfigsResult.configs = configs
2794
+ testSessionConfigurationCh.publish(readConfigsResult.configs.map(config => config.testEnvironmentOptions))
2795
+ repositoryRoot = getJestRepositoryRoot(readConfigsResult)
2796
+
2797
+ if (readConfigsResult.globalConfig.forceExit) {
2798
+ log.warn("Jest's '--forceExit' flag has been passed. This may cause loss of data.")
1607
2799
  }
2800
+
2801
+ readConfigsResult.globalConfig = addDatadogBailReporter(readConfigsResult.globalConfig)
2802
+
1608
2803
  if (isSuitesSkippingEnabled) {
1609
2804
  // If suite skipping is enabled, we pass `passWithNoTests` in case every test gets skipped.
1610
2805
  const globalConfig = {
1611
2806
  ...readConfigsResult.globalConfig,
1612
2807
  passWithNoTests: true,
1613
2808
  }
1614
- if (isCodeCoverageEnabledBecauseOfUs && !isKeepingCoverageConfiguration) {
1615
- globalConfig.coverageReporters = ['none']
1616
- readConfigsResult.configs = configs.map(config => ({
1617
- ...config,
1618
- coverageReporters: ['none'],
1619
- }))
1620
- }
1621
2809
  readConfigsResult.globalConfig = globalConfig
1622
2810
  }
1623
2811
 
@@ -1633,8 +2821,8 @@ function jestConfigAsyncWrapper (jestConfig) {
1633
2821
  }
1634
2822
 
1635
2823
  function jestConfigSyncWrapper (jestConfig) {
1636
- return shimmer.wrap(jestConfig, 'readConfigs', readConfigs => function () {
1637
- const readConfigsResult = readConfigs.apply(this, arguments)
2824
+ return shimmer.wrap(jestConfig, 'readConfigs', readConfigs => function (...args) {
2825
+ const readConfigsResult = readConfigs.apply(this, args)
1638
2826
  configureTestEnvironment(readConfigsResult)
1639
2827
  return readConfigsResult
1640
2828
  })
@@ -1652,8 +2840,10 @@ const DD_TEST_ENVIRONMENT_OPTION_KEYS = [
1652
2840
  '_ddIsEarlyFlakeDetectionEnabled',
1653
2841
  '_ddEarlyFlakeDetectionSlowTestRetries',
1654
2842
  '_ddRepositoryRoot',
2843
+ '_ddTestCodeCoverageEnabled',
1655
2844
  '_ddIsFlakyTestRetriesEnabled',
1656
2845
  '_ddFlakyTestRetriesCount',
2846
+ '_ddItrSkippingEnabledTags',
1657
2847
  '_ddIsDiEnabled',
1658
2848
  '_ddIsKnownTestsEnabled',
1659
2849
  '_ddIsTestManagementTestsEnabled',
@@ -1716,7 +2906,7 @@ function wrapCreateScriptTransformer (createScriptTransformer) {
1716
2906
 
1717
2907
  addHook({
1718
2908
  name: '@jest/transform',
1719
- versions: ['>=24.8.0 <30.0.0'],
2909
+ versions: [MINIMUM_JEST_VERSION_BEFORE_30],
1720
2910
  file: 'build/ScriptTransformer.js',
1721
2911
  }, transformPackage => {
1722
2912
  transformPackage.createScriptTransformer = wrapCreateScriptTransformer(transformPackage.createScriptTransformer)
@@ -1736,20 +2926,30 @@ addHook({
1736
2926
  */
1737
2927
  addHook({
1738
2928
  name: '@jest/core',
1739
- versions: ['>=24.8.0 <30.0.0'],
2929
+ versions: [MINIMUM_JEST_VERSION_BEFORE_30],
1740
2930
  file: 'build/SearchSource.js',
1741
2931
  }, searchSourceWrapper)
1742
2932
 
2933
+ addHook({
2934
+ name: 'jest-each',
2935
+ versions: [MINIMUM_JEST_VERSION],
2936
+ }, jestEach => {
2937
+ cacheJestEachBind(jestEach)
2938
+ return jestEach
2939
+ })
2940
+
1743
2941
  // from 25.1.0 on, readConfigs becomes async
1744
2942
  addHook({
1745
2943
  name: 'jest-config',
1746
- versions: ['>=25.1.0'],
2944
+ versions: [MINIMUM_JEST_CONFIG_ASYNC_VERSION],
1747
2945
  }, jestConfigAsyncWrapper)
1748
2946
 
1749
- addHook({
1750
- name: 'jest-config',
1751
- versions: ['24.8.0 - 24.9.0'],
1752
- }, jestConfigSyncWrapper)
2947
+ if (DD_MAJOR < 6) {
2948
+ addHook({
2949
+ name: 'jest-config',
2950
+ versions: ['24.8.0 - 24.9.0'],
2951
+ }, jestConfigSyncWrapper)
2952
+ }
1753
2953
 
1754
2954
  const LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE = new Set([
1755
2955
  'selenium-webdriver',
@@ -1762,39 +2962,180 @@ const LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE = new Set([
1762
2962
  'winston',
1763
2963
  ])
1764
2964
 
2965
+ function recordMockedFile (suiteFilePath, moduleName) {
2966
+ if (!suiteFilePath || typeof moduleName !== 'string') return
2967
+
2968
+ const existingMockedFiles = testSuiteMockedFiles.get(suiteFilePath) || []
2969
+ const suiteDir = path.dirname(suiteFilePath)
2970
+ const mockPath = path.resolve(suiteDir, moduleName)
2971
+ existingMockedFiles.push(mockPath)
2972
+ testSuiteMockedFiles.set(suiteFilePath, existingMockedFiles)
2973
+ }
2974
+
2975
+ const JEST_STATIC_MOCK_CALL_RE = /\bjest\.(?:mock|doMock|unstable_mockModule)\(\s*(['"`])([^'"`]+)\1/g
2976
+
2977
+ function getStaticMockedFiles (suiteFilePath) {
2978
+ if (!suiteFilePath) return []
2979
+
2980
+ const mockedFiles = []
2981
+ try {
2982
+ const source = readFileSync(suiteFilePath, 'utf8')
2983
+ let match
2984
+ JEST_STATIC_MOCK_CALL_RE.lastIndex = 0
2985
+ while ((match = JEST_STATIC_MOCK_CALL_RE.exec(source)) !== null) {
2986
+ mockedFiles.push(path.resolve(path.dirname(suiteFilePath), match[2]))
2987
+ }
2988
+ } catch {
2989
+ // ignore errors
2990
+ }
2991
+
2992
+ return mockedFiles
2993
+ }
2994
+
2995
+ function getMockedFiles (suiteFilePath) {
2996
+ const mockedFiles = testSuiteMockedFiles.get(suiteFilePath)
2997
+ const staticMockedFiles = getStaticMockedFiles(suiteFilePath)
2998
+
2999
+ if (mockedFiles?.length) {
3000
+ return [...new Set([...mockedFiles, ...staticMockedFiles])]
3001
+ }
3002
+ return staticMockedFiles
3003
+ }
3004
+
3005
+ function wrapJestObject (jestObject, suiteFilePath) {
3006
+ if (!jestObject || !suiteFilePath || wrappedJestObjects.has(jestObject)) return
3007
+
3008
+ testSuiteJestObjects.set(suiteFilePath, jestObject)
3009
+ wrappedJestObjects.add(jestObject)
3010
+
3011
+ shimmer.wrap(jestObject, 'mock', mock => function (moduleName) {
3012
+ // If the library is mocked with `jest.mock`, we don't want to bypass jest's own require engine
3013
+ if (LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE.has(moduleName)) {
3014
+ LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE.delete(moduleName)
3015
+ }
3016
+ recordMockedFile(suiteFilePath, moduleName)
3017
+ return mock.apply(this, arguments)
3018
+ })
3019
+ }
3020
+
3021
+ function wrapJestGlobalsForRuntime (runtime) {
3022
+ const jestGlobals = runtime?.jestGlobals
3023
+ if (!jestGlobals || wrappedJestGlobals.has(jestGlobals) || typeof jestGlobals.jestObjectFor !== 'function') {
3024
+ return
3025
+ }
3026
+
3027
+ wrappedJestGlobals.add(jestGlobals)
3028
+ shimmer.wrap(jestGlobals, 'jestObjectFor', jestObjectFor => function (from) {
3029
+ const jestObject = jestObjectFor.apply(this, arguments)
3030
+ wrapJestObject(jestObject, from)
3031
+ return jestObject
3032
+ })
3033
+ }
3034
+
3035
+ function wrapConcurrentJestGlobalsForRuntime (runtime, jestGlobals) {
3036
+ const environment = testSuiteDatadogEnvironments.get(runtime?._testPath)
3037
+ environment?.wrapConcurrentTestGlobals(jestGlobals?.test, environment.concurrentTestState)
3038
+ }
3039
+
3040
+ function cacheJestEachBind (jestEach) {
3041
+ if (typeof jestEach?.bind === 'function') {
3042
+ jestEachBind = jestEach.bind
3043
+ }
3044
+ }
3045
+
3046
+ function getLastLoggedReferenceError (runtime) {
3047
+ const loggedReferenceErrors = runtime?.loggedReferenceErrors
3048
+ if (!loggedReferenceErrors?.size) return
3049
+ return [...loggedReferenceErrors].pop()
3050
+ }
3051
+
3052
+ function publishRuntimeReferenceError (runtime, errorMessage) {
3053
+ if (!errorMessage || !runtime?._testPath) return
3054
+
3055
+ let publishedErrors = publishedRuntimeReferenceErrors.get(runtime)
3056
+ if (!publishedErrors) {
3057
+ publishedErrors = new Set()
3058
+ publishedRuntimeReferenceErrors.set(runtime, publishedErrors)
3059
+ }
3060
+ if (publishedErrors.has(errorMessage)) return
3061
+
3062
+ publishedErrors.add(errorMessage)
3063
+ testSuiteErrorCh.publish({
3064
+ errorMessage,
3065
+ testSuiteAbsolutePath: runtime._testPath,
3066
+ })
3067
+ }
3068
+
3069
+ function isBetweenTestsReferenceError (error) {
3070
+ return error?.name === 'ReferenceError' &&
3071
+ typeof error.message === 'string' &&
3072
+ error.message.includes('outside of the scope of the test code')
3073
+ }
3074
+
3075
+ function reportBetweenTestsReferenceError (runtime, moduleName, originalErrorMessage) {
3076
+ if (typeof moduleName !== 'string') return false
3077
+
3078
+ const fallbackErrorMessage = moduleName.startsWith('node:') || builtinModules.includes(moduleName)
3079
+ ? 'You are trying to access a Node.js module outside of the scope of the test code.'
3080
+ : 'You are trying to `require` a file after the Jest environment has been torn down.'
3081
+ const errorMessage = originalErrorMessage || fallbackErrorMessage
3082
+
3083
+ if (typeof runtime._logFormattedReferenceError === 'function') {
3084
+ runtime._logFormattedReferenceError(errorMessage)
3085
+ }
3086
+ publishRuntimeReferenceError(runtime, getLastLoggedReferenceError(runtime) || errorMessage)
3087
+ process.exitCode = 1
3088
+ return true
3089
+ }
3090
+
3091
+ function requireOutsideJestRequireEngine (runtime, moduleName) {
3092
+ if (typeof runtime._requireCoreModule === 'function') {
3093
+ return runtime._requireCoreModule(moduleName)
3094
+ }
3095
+ return require(moduleName)
3096
+ }
3097
+
3098
+ function formatDefaultStackTrace (error, structuredStackTrace) {
3099
+ const errorString = Error.prototype.toString.call(error)
3100
+ if (structuredStackTrace.length === 0) return errorString
3101
+
3102
+ return `${errorString}\n at ${structuredStackTrace.join('\n at ')}`
3103
+ }
3104
+
1765
3105
  addHook({
1766
3106
  name: 'jest-runtime',
1767
- versions: ['>=24.8.0'],
3107
+ versions: [MINIMUM_JEST_VERSION],
1768
3108
  }, (runtimePackage) => {
1769
3109
  const Runtime = runtimePackage.default ?? runtimePackage
1770
3110
 
1771
- shimmer.wrap(Runtime.prototype, '_createJestObjectFor', _createJestObjectFor => function (from) {
1772
- const result = _createJestObjectFor.apply(this, arguments)
1773
- const suiteFilePath = this._testPath || from
3111
+ if (typeof Runtime.prototype._createJestObjectFor === 'function') {
3112
+ shimmer.wrap(Runtime.prototype, '_createJestObjectFor', _createJestObjectFor => function (from) {
3113
+ const result = _createJestObjectFor.apply(this, arguments)
3114
+ const suiteFilePath = this._testPath || from
1774
3115
 
1775
- // Store the jest object so we can access it later for resetting mock state
1776
- if (suiteFilePath) {
1777
- testSuiteJestObjects.set(suiteFilePath, result)
1778
- }
3116
+ wrapJestObject(result, suiteFilePath)
3117
+ return result
3118
+ })
3119
+ }
1779
3120
 
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)
3121
+ shimmer.wrap(Runtime.prototype, 'requireModule', requireModule => function (from, moduleName) {
3122
+ wrapJestGlobalsForRuntime(this)
3123
+ try {
3124
+ const returnedValue = requireModule.apply(this, arguments)
3125
+ if (moduleName === '@jest/globals') {
3126
+ wrapConcurrentJestGlobalsForRuntime(this, returnedValue)
1784
3127
  }
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)
3128
+ return returnedValue
3129
+ } catch (error) {
3130
+ if (isBetweenTestsReferenceError(error)) {
3131
+ reportBetweenTestsReferenceError(this, moduleName, error.message)
1791
3132
  }
1792
- return mock.apply(this, arguments)
1793
- })
1794
- return result
3133
+ throw error
3134
+ }
1795
3135
  })
1796
3136
 
1797
3137
  shimmer.wrap(Runtime.prototype, 'requireModuleOrMock', requireModuleOrMock => function (from, moduleName) {
3138
+ wrapJestGlobalsForRuntime(this)
1798
3139
  // `requireModuleOrMock` may log errors to the console. If we don't remove ourselves
1799
3140
  // from the stack trace, the user might see a useless stack trace rather than the error
1800
3141
  // that `jest` tries to show.
@@ -1803,32 +3144,34 @@ addHook({
1803
3144
  const filteredStackTrace = structuredStackTrace
1804
3145
  .filter(callSite => !callSite.getFileName()?.includes('datadog-instrumentations/src/jest.js'))
1805
3146
 
1806
- return originalPrepareStackTrace(error, filteredStackTrace)
3147
+ if (typeof originalPrepareStackTrace === 'function') {
3148
+ return originalPrepareStackTrace(error, filteredStackTrace)
3149
+ }
3150
+ return formatDefaultStackTrace(error, filteredStackTrace)
1807
3151
  }
1808
3152
  try {
1809
3153
  // TODO: do this for every library that we instrument
1810
3154
  if (LIBRARIES_BYPASSING_JEST_REQUIRE_ENGINE.has(moduleName)) {
1811
3155
  // To bypass jest's own require engine
1812
- return this._requireCoreModule(moduleName)
3156
+ return requireOutsideJestRequireEngine(this, moduleName)
1813
3157
  }
1814
- // This means that `@fast-check/jest` is used in the test file.
1815
- if (moduleName === '@fast-check/jest') {
1816
- testSuiteAbsolutePathsWithFastCheck.add(this._testPath)
3158
+ let returnedValue
3159
+ try {
3160
+ returnedValue = requireModuleOrMock.apply(this, arguments)
3161
+ if (moduleName === '@jest/globals') {
3162
+ wrapConcurrentJestGlobalsForRuntime(this, returnedValue)
3163
+ }
3164
+ } catch (error) {
3165
+ if (isBetweenTestsReferenceError(error)) {
3166
+ reportBetweenTestsReferenceError(this, moduleName, error.message)
3167
+ }
3168
+ throw error
1817
3169
  }
1818
- const returnedValue = requireModuleOrMock.apply(this, arguments)
1819
3170
  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
- }
3171
+ publishRuntimeReferenceError(
3172
+ this,
3173
+ getLastLoggedReferenceError(this) || 'An error occurred while importing a module'
3174
+ )
1832
3175
  }
1833
3176
  return returnedValue
1834
3177
  } finally {
@@ -1837,14 +3180,35 @@ addHook({
1837
3180
  }
1838
3181
  })
1839
3182
 
3183
+ if (Runtime.prototype._logFormattedReferenceError) {
3184
+ shimmer.wrap(Runtime.prototype, '_logFormattedReferenceError', logFormattedReferenceError => function () {
3185
+ // eslint-disable-next-line no-console
3186
+ const originalConsoleError = console.error
3187
+ let loggedReferenceError
3188
+ // eslint-disable-next-line no-console
3189
+ console.error = function () {
3190
+ loggedReferenceError = arguments[0]
3191
+ return originalConsoleError.apply(this, arguments)
3192
+ }
3193
+ try {
3194
+ const result = logFormattedReferenceError.apply(this, arguments)
3195
+ publishRuntimeReferenceError(this, getLastLoggedReferenceError(this) || loggedReferenceError)
3196
+ return result
3197
+ } finally {
3198
+ // eslint-disable-next-line no-console
3199
+ console.error = originalConsoleError
3200
+ }
3201
+ })
3202
+ }
3203
+
1840
3204
  return runtimePackage
1841
3205
  })
1842
3206
 
1843
3207
  function onMessageWrapper (onMessage) {
1844
- return function () {
1845
- const response = arguments[0]
3208
+ return function (...args) {
3209
+ const response = args[0]
1846
3210
  if (!Array.isArray(response)) {
1847
- return onMessage.apply(this, arguments)
3211
+ return onMessage.apply(this, args)
1848
3212
  }
1849
3213
 
1850
3214
  const [code, data] = response
@@ -1865,7 +3229,13 @@ function onMessageWrapper (onMessage) {
1865
3229
  workerReportTelemetryCh.publish(data)
1866
3230
  return
1867
3231
  }
1868
- return onMessage.apply(this, arguments)
3232
+ if (code === JEST_WORKER_QUARANTINE_PAYLOAD_CODE) { // quarantined test failures suppressed in worker
3233
+ for (const name of JSON.parse(data)) {
3234
+ quarantinedFailingTests.add(name)
3235
+ }
3236
+ return
3237
+ }
3238
+ return onMessage.apply(this, args)
1869
3239
  }
1870
3240
  }
1871
3241
 
@@ -1917,11 +3287,23 @@ function wrapWorkerChannel (worker) {
1917
3287
  shimmer.wrap(workerChannel, worker._child ? 'send' : 'postMessage', sendWrapper)
1918
3288
  }
1919
3289
 
3290
+ function wrapWorkerInitializer (worker) {
3291
+ if (wrappedWorkerInitializers.has(worker) || typeof worker.initialize !== 'function') return
3292
+
3293
+ wrappedWorkerInitializers.add(worker)
3294
+ shimmer.wrap(worker, 'initialize', initialize => function () {
3295
+ const result = initialize.apply(this, arguments)
3296
+ wrapWorkerChannel(this)
3297
+ return result
3298
+ })
3299
+ }
3300
+
1920
3301
  function wrapWorker (worker) {
1921
3302
  // ChildProcessWorker uses _child (child_process), ExperimentalWorker uses _worker (worker_threads)
1922
3303
  const workerChannel = worker._child || worker._worker
1923
3304
  if (!workerChannel) return
1924
3305
 
3306
+ wrapWorkerInitializer(worker)
1925
3307
  wrapWorkerChannel(worker)
1926
3308
  shimmer.wrap(worker, '_onMessage', onMessageWrapper)
1927
3309
  workerChannel.removeAllListeners('message')
@@ -1929,8 +3311,8 @@ function wrapWorker (worker) {
1929
3311
  }
1930
3312
 
1931
3313
  function enqueueWrapper (enqueue) {
1932
- return function () {
1933
- shimmer.wrap(arguments[0], 'onStart', onStart => function (worker) {
3314
+ return function (...args) {
3315
+ shimmer.wrap(args[0], 'onStart', onStart => function (worker) {
1934
3316
  if (worker) {
1935
3317
  const currentChannel = worker._child || worker._worker
1936
3318
  const previousChannel = wrappedWorkerChannels.get(worker)
@@ -1947,7 +3329,7 @@ function enqueueWrapper (enqueue) {
1947
3329
  }
1948
3330
  return onStart.apply(this, arguments)
1949
3331
  })
1950
- return enqueue.apply(this, arguments)
3332
+ return enqueue.apply(this, args)
1951
3333
  }
1952
3334
  }
1953
3335
 
@@ -1959,7 +3341,7 @@ function enqueueWrapper (enqueue) {
1959
3341
  */
1960
3342
  addHook({
1961
3343
  name: 'jest-worker',
1962
- versions: ['>=24.9.0 <30.0.0'],
3344
+ versions: [MINIMUM_JEST_WORKER_VERSION_BEFORE_30],
1963
3345
  file: 'build/workers/ChildProcessWorker.js',
1964
3346
  }, (childProcessWorker) => {
1965
3347
  const ChildProcessWorker = childProcessWorker.default
@@ -1974,7 +3356,7 @@ addHook({
1974
3356
 
1975
3357
  addHook({
1976
3358
  name: 'jest-worker',
1977
- versions: ['>=24.9.0 <30.0.0'],
3359
+ versions: [MINIMUM_JEST_WORKER_VERSION_BEFORE_30],
1978
3360
  file: 'build/workers/NodeThreadsWorker.js',
1979
3361
  }, (nodeThreadsWorker) => {
1980
3362
  const ExperimentalWorker = nodeThreadsWorker.default