@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
@@ -0,0 +1,1592 @@
1
+ 'use strict'
2
+
3
+ const path = require('node:path')
4
+ const { fileURLToPath } = require('node:url')
5
+ const { MessagePort } = require('node:worker_threads')
6
+
7
+ const shimmer = require('../../datadog-shimmer')
8
+ const log = require('../../dd-trace/src/log')
9
+ const {
10
+ VITEST_WORKER_TRACE_PAYLOAD_CODE,
11
+ VITEST_WORKER_LOGS_PAYLOAD_CODE,
12
+ getMaxEfdRetryCount,
13
+ collectTestOptimizationSummariesFromTraces,
14
+ logTestOptimizationSummary,
15
+ getTestOptimizationRequestResults,
16
+ getTestSuitePath,
17
+ isModifiedTest,
18
+ } = require('../../dd-trace/src/plugins/util/test')
19
+ const { addHook } = require('./helpers/instrument')
20
+ const noWorkerInit = require('./vitest-main-no-worker-init')
21
+ const {
22
+ testStartCh,
23
+ testPassCh,
24
+ testErrorCh,
25
+ testSkipCh,
26
+ testSuiteStartCh,
27
+ testSuiteFinishCh,
28
+ testSuiteErrorCh,
29
+ testSessionStartCh,
30
+ testSessionFinishCh,
31
+ testSessionConfigurationCh,
32
+ libraryConfigurationCh,
33
+ knownTestsCh,
34
+ isEarlyFlakeDetectionFaultyCh,
35
+ testManagementTestsCh,
36
+ modifiedFilesCh,
37
+ workerReportTraceCh,
38
+ workerReportLogsCh,
39
+ codeCoverageReportCh,
40
+ findExportByName,
41
+ getChannelPromise,
42
+ getTypeTasks,
43
+ getWorkspaceProject,
44
+ setProvidedContext,
45
+ getVitestTestProperties,
46
+ } = require('./vitest-util')
47
+
48
+ const newTestsWithDynamicNames = new Set()
49
+ const attemptToFixExecutions = new Map()
50
+ const workerProcesses = new WeakSet()
51
+ const mainProcessSetupStates = new WeakMap()
52
+ const coverageWrappedProviders = new WeakSet()
53
+ const finishWrappedContexts = new WeakSet()
54
+ let isFlakyTestRetriesEnabled = false
55
+ let flakyTestRetriesCount = 0
56
+ let isEarlyFlakeDetectionEnabled = false
57
+ let earlyFlakeDetectionNumRetries = 0
58
+ let earlyFlakeDetectionSlowTestRetries = {}
59
+ let isEarlyFlakeDetectionFaulty = false
60
+ let isKnownTestsEnabled = false
61
+ let isTestManagementTestsEnabled = false
62
+ let isImpactedTestsEnabled = false
63
+ let testManagementAttemptToFixRetries = 0
64
+ let isDiEnabled = false
65
+ let testCodeCoverageLinesTotal
66
+ let coverageRootDir
67
+ let requestErrorTags = {}
68
+ let isSessionStarted = false
69
+ let isVitestNoWorkerInitActive = false
70
+ let vitestPool = null
71
+ let isMessagePortWrapped = false
72
+ const tinyPoolClassWrappers = new WeakMap()
73
+
74
+ function getConfiguredEfdRetryCount (slowTestRetries, fallbackRetryCount) {
75
+ if (!slowTestRetries || !Object.keys(slowTestRetries).length) {
76
+ return fallbackRetryCount
77
+ }
78
+ return getMaxEfdRetryCount(slowTestRetries)
79
+ }
80
+
81
+ function getTestCommand () {
82
+ return `vitest ${process.argv.slice(2).join(' ')}`
83
+ }
84
+
85
+ function isValidKnownTests (receivedKnownTests) {
86
+ return !!receivedKnownTests.vitest
87
+ }
88
+
89
+ function isReporterPackage (vitestPackage) {
90
+ return vitestPackage.B?.name === 'BaseSequencer'
91
+ }
92
+
93
+ function isReporterPackageNew (vitestPackage) {
94
+ return vitestPackage.e?.name === 'BaseSequencer'
95
+ }
96
+
97
+ function isReporterPackageNewest (vitestPackage) {
98
+ return vitestPackage.h?.name === 'BaseSequencer'
99
+ }
100
+
101
+ function getBaseSequencerExport (vitestPackage) {
102
+ return findExportByName(vitestPackage, 'BaseSequencer')
103
+ }
104
+
105
+ function isCliApiPackage (vitestPackage) {
106
+ return !!findExportByName(vitestPackage, 'startVitest')
107
+ }
108
+
109
+ function getVitestExport (vitestPackage) {
110
+ return findExportByName(vitestPackage, 'Vitest')
111
+ }
112
+
113
+ function getTypecheckerExport (vitestPackage) {
114
+ return findExportByName(vitestPackage, 'Typechecker')
115
+ }
116
+
117
+ function getForksPoolWorkerExport (vitestPackage) {
118
+ return findExportByName(vitestPackage, 'ForksPoolWorker')
119
+ }
120
+
121
+ function getThreadsPoolWorkerExport (vitestPackage) {
122
+ return findExportByName(vitestPackage, 'ThreadsPoolWorker')
123
+ }
124
+
125
+ function getSessionStatus (state) {
126
+ if (state.getCountOfFailedTests() > 0) {
127
+ return 'fail'
128
+ }
129
+ if (state.pathsSet.size === 0) {
130
+ return 'skip'
131
+ }
132
+ return 'pass'
133
+ }
134
+
135
+ function getTestFilepathsFromSpecifications (testSpecifications) {
136
+ if (!Array.isArray(testSpecifications) || !testSpecifications.length) {
137
+ return
138
+ }
139
+
140
+ return testSpecifications.map(testSpecification => {
141
+ const testFile = Array.isArray(testSpecification) ? testSpecification[1] : testSpecification
142
+ return testFile?.moduleId || testFile?.filepath || testFile
143
+ })
144
+ }
145
+
146
+ function getTestSpecificationsKey (testSpecifications) {
147
+ if (!Array.isArray(testSpecifications) || !testSpecifications.length) return
148
+
149
+ const keyParts = []
150
+ for (const testSpecification of testSpecifications) {
151
+ const testFile = Array.isArray(testSpecification) ? testSpecification[1] : testSpecification
152
+ const testFilepath = testFile?.moduleId || testFile?.filepath || testFile
153
+ if (!testFilepath) continue
154
+
155
+ const projectName = getProjectName(getTestSpecificationProject(testSpecification)) || ''
156
+ const pool = getTestSpecificationPool(testSpecification) || ''
157
+ keyParts.push(`${projectName}\0${pool}\0${testFilepath}`)
158
+ }
159
+
160
+ if (!keyParts.length) return
161
+
162
+ keyParts.sort()
163
+ return keyParts.join('\0')
164
+ }
165
+
166
+ function getTestFilepaths (ctx, testSpecifications) {
167
+ const testFilepaths = getTestFilepathsFromSpecifications(testSpecifications)
168
+ if (testFilepaths) {
169
+ return testFilepaths
170
+ }
171
+
172
+ const getFilePaths = ctx.getTestFilepaths || ctx._globTestFilepaths
173
+ return getFilePaths.call(ctx)
174
+ }
175
+
176
+ /**
177
+ * @typedef {{
178
+ * isAttemptToFix?: boolean,
179
+ * isDisabled?: boolean,
180
+ * isQuarantined?: boolean
181
+ * }} VitestTestManagementProperties
182
+ *
183
+ * @typedef {{
184
+ * testSuite?: string,
185
+ * knownTests?: string[],
186
+ * testManagementTests?: Record<string, VitestTestManagementProperties>,
187
+ * isModified?: boolean
188
+ * }} VitestTestProperties
189
+ */
190
+
191
+ /**
192
+ * Normalize a Vitest test file path to the test suite path used by Test Optimization APIs.
193
+ *
194
+ * @param {string} testFilepath
195
+ * @param {string} repositoryRoot
196
+ * @returns {string}
197
+ */
198
+ function getNormalizedTestSuitePath (testFilepath, repositoryRoot) {
199
+ const testSuiteAbsolutePath = path.isAbsolute(testFilepath) ? testFilepath : path.join(repositoryRoot, testFilepath)
200
+ return getTestSuitePath(testSuiteAbsolutePath, repositoryRoot)
201
+ }
202
+
203
+ /**
204
+ * Build simplified Test Management metadata grouped by normalized test suite path.
205
+ *
206
+ * @param {{ vitest?: { suites?: Record<string, { tests?: Record<string, { properties?: {
207
+ * attempt_to_fix?: boolean,
208
+ * disabled?: boolean,
209
+ * quarantined?: boolean
210
+ * } }> }> } }} testManagementTests
211
+ * @returns {Record<string, Record<string, VitestTestManagementProperties>>}
212
+ */
213
+ function getTestManagementTestsBySuite (testManagementTests) {
214
+ const testManagementTestsBySuite = {}
215
+ const suites = testManagementTests?.vitest?.suites
216
+ if (!suites) return testManagementTestsBySuite
217
+
218
+ for (const [testSuite, suite] of Object.entries(suites)) {
219
+ const tests = suite?.tests
220
+ if (!tests) continue
221
+
222
+ const testsByName = {}
223
+ let hasTests = false
224
+ for (const [testName, test] of Object.entries(tests)) {
225
+ const properties = test?.properties
226
+ const testProperties = {
227
+ isAttemptToFix: properties?.attempt_to_fix,
228
+ isDisabled: properties?.disabled,
229
+ isQuarantined: properties?.quarantined,
230
+ }
231
+ testsByName[testName] = testProperties
232
+ hasTests = true
233
+ }
234
+ if (hasTests) {
235
+ testManagementTestsBySuite[testSuite] = testsByName
236
+ }
237
+ }
238
+
239
+ return testManagementTestsBySuite
240
+ }
241
+
242
+ /**
243
+ * Build a set-like object for test suites modified in the current pull request diff.
244
+ *
245
+ * @param {Record<string, number[]>|undefined} modifiedFiles
246
+ * @returns {Record<string, boolean>}
247
+ */
248
+ function getImpactedTestSuites (modifiedFiles) {
249
+ const impactedTestSuites = {}
250
+ if (!modifiedFiles) return impactedTestSuites
251
+
252
+ for (const testSuite of Object.keys(modifiedFiles)) {
253
+ if (isModifiedTest(testSuite, 0, 0, modifiedFiles, 'vitest')) {
254
+ impactedTestSuites[testSuite] = true
255
+ }
256
+ }
257
+
258
+ return impactedTestSuites
259
+ }
260
+
261
+ /**
262
+ * Build the worker-ready test metadata map keyed by Vitest's absolute filepath.
263
+ *
264
+ * @param {string[]} testFilepaths
265
+ * @param {string} repositoryRoot
266
+ * @param {Record<string, string[]>|undefined} knownTestsBySuite
267
+ * @param {Record<string, Record<string, VitestTestManagementProperties>>|undefined} testManagementTestsBySuite
268
+ * @param {Record<string, boolean>|undefined} impactedTestSuites
269
+ * @returns {Record<string, VitestTestProperties>}
270
+ */
271
+ function getTestPropertiesByFilepath (
272
+ testFilepaths,
273
+ repositoryRoot,
274
+ knownTestsBySuite,
275
+ testManagementTestsBySuite,
276
+ impactedTestSuites
277
+ ) {
278
+ const testPropertiesByFilepath = {}
279
+ if (!Array.isArray(testFilepaths)) return testPropertiesByFilepath
280
+
281
+ for (const testFilepath of testFilepaths) {
282
+ if (typeof testFilepath !== 'string') continue
283
+
284
+ const testSuite = getNormalizedTestSuitePath(testFilepath, repositoryRoot)
285
+ const testProperties = { testSuite }
286
+ const hasProperties = knownTestsBySuite !== undefined ||
287
+ testManagementTestsBySuite !== undefined ||
288
+ impactedTestSuites !== undefined
289
+
290
+ if (knownTestsBySuite) {
291
+ testProperties.knownTests = knownTestsBySuite[testSuite] || []
292
+ }
293
+ if (testManagementTestsBySuite) {
294
+ testProperties.testManagementTests = testManagementTestsBySuite[testSuite] || {}
295
+ }
296
+ if (impactedTestSuites?.[testSuite]) {
297
+ testProperties.isModified = true
298
+ }
299
+
300
+ if (hasProperties) {
301
+ testPropertiesByFilepath[testFilepath] = testProperties
302
+ }
303
+ }
304
+
305
+ return testPropertiesByFilepath
306
+ }
307
+
308
+ function wrapCoverageProvider (ctx) {
309
+ const { coverageProvider } = ctx
310
+ if (!coverageProvider?.generateCoverage || coverageWrappedProviders.has(coverageProvider)) {
311
+ return
312
+ }
313
+ coverageWrappedProviders.add(coverageProvider)
314
+
315
+ // Capture coverage root directory from config (default is 'coverage' in cwd)
316
+ try {
317
+ const coverageConfig = ctx.config?.coverage
318
+ const reportsDirectory = coverageConfig?.reportsDirectory || 'coverage'
319
+ const rootDir = ctx.config?.root || process.cwd()
320
+ coverageRootDir = path.isAbsolute(reportsDirectory) ? reportsDirectory : path.join(rootDir, reportsDirectory)
321
+ } catch {
322
+ // Fallback to cwd if we can't get config
323
+ coverageRootDir = process.cwd()
324
+ }
325
+
326
+ shimmer.wrap(coverageProvider, 'generateCoverage', generateCoverage => async function () {
327
+ const totalCodeCoverage = await generateCoverage.apply(this, arguments)
328
+
329
+ try {
330
+ testCodeCoverageLinesTotal = totalCodeCoverage.getCoverageSummary().lines.pct
331
+ } catch {
332
+ // ignore errors
333
+ }
334
+ return totalCodeCoverage
335
+ })
336
+ }
337
+
338
+ function wrapSessionFinish (ctx) {
339
+ if (finishWrappedContexts.has(ctx)) {
340
+ return
341
+ }
342
+ finishWrappedContexts.add(ctx)
343
+
344
+ shimmer.wrap(ctx, 'exit', getFinishWrapper)
345
+ shimmer.wrap(ctx, 'close', getFinishWrapper)
346
+ }
347
+
348
+ function resetLibraryConfig () {
349
+ isFlakyTestRetriesEnabled = false
350
+ flakyTestRetriesCount = 0
351
+ isEarlyFlakeDetectionEnabled = false
352
+ earlyFlakeDetectionNumRetries = 0
353
+ earlyFlakeDetectionSlowTestRetries = {}
354
+ isEarlyFlakeDetectionFaulty = false
355
+ isDiEnabled = false
356
+ isKnownTestsEnabled = false
357
+ isTestManagementTestsEnabled = false
358
+ isImpactedTestsEnabled = false
359
+ testManagementAttemptToFixRetries = 0
360
+ }
361
+
362
+ function applyLibraryConfig (libraryConfig) {
363
+ isFlakyTestRetriesEnabled = libraryConfig.isFlakyTestRetriesEnabled
364
+ flakyTestRetriesCount = libraryConfig.flakyTestRetriesCount
365
+ isEarlyFlakeDetectionEnabled = libraryConfig.isEarlyFlakeDetectionEnabled
366
+ earlyFlakeDetectionNumRetries = libraryConfig.earlyFlakeDetectionNumRetries
367
+ earlyFlakeDetectionSlowTestRetries = libraryConfig.earlyFlakeDetectionSlowTestRetries ?? {}
368
+ isEarlyFlakeDetectionFaulty = false
369
+ isDiEnabled = libraryConfig.isDiEnabled
370
+ isKnownTestsEnabled = libraryConfig.isKnownTestsEnabled
371
+ isTestManagementTestsEnabled = libraryConfig.isTestManagementEnabled
372
+ testManagementAttemptToFixRetries = libraryConfig.testManagementAttemptToFixRetries
373
+ isImpactedTestsEnabled = libraryConfig.isImpactedTestsEnabled
374
+ }
375
+
376
+ function resetMainProcessProvidedContext (ctx) {
377
+ setProvidedContext(ctx, {
378
+ _ddIsDiEnabled: false,
379
+ _ddIsEarlyFlakeDetectionEnabled: false,
380
+ _ddEarlyFlakeDetectionNumRetries: 0,
381
+ _ddEarlyFlakeDetectionSlowTestRetries: {},
382
+ _ddIsFlakyTestRetriesEnabled: false,
383
+ _ddFlakyTestRetriesCount: 0,
384
+ _ddFlakyTestRetriesIncludesUnnamedProject: false,
385
+ _ddFlakyTestRetriesProjectNames: undefined,
386
+ _ddIsImpactedTestsEnabled: false,
387
+ _ddIsKnownTestsEnabled: false,
388
+ _ddIsTestManagementTestsEnabled: false,
389
+ _ddTestManagementAttemptToFixRetries: 0,
390
+ _ddTestPropertiesByFilepath: {},
391
+ }, 'Could not reset Test Optimization context for workers.')
392
+ }
393
+
394
+ /**
395
+ * Merges request error tags from a Test Optimization request response into the tags propagated by no-worker mode.
396
+ *
397
+ * @param {{ requestErrorTags?: Record<string, string> }|undefined} requestResponse - Request response.
398
+ */
399
+ function mergeRequestErrorTags (requestResponse) {
400
+ if (requestResponse?.requestErrorTags) {
401
+ requestErrorTags = {
402
+ ...requestErrorTags,
403
+ ...requestResponse.requestErrorTags,
404
+ }
405
+ }
406
+ }
407
+
408
+ async function runMainProcessSetup (ctx, frameworkVersion, testSpecifications, shouldInstallNoWorkerInit) {
409
+ if (!testSessionFinishCh.hasSubscribers) {
410
+ return
411
+ }
412
+
413
+ let repositoryRoot = process.cwd()
414
+ let testSessionConfiguration
415
+ let testFilepaths
416
+ let shouldSendTestProperties = false
417
+ let testPropertiesByFilepath
418
+ let knownTests
419
+ let knownTestsBySuite
420
+ let testManagementTests
421
+ let testManagementTestsBySuite
422
+ let modifiedFiles
423
+ let impactedTestSuites
424
+ const getCurrentTestFilepaths = async () => {
425
+ if (testFilepaths === undefined) {
426
+ testFilepaths = await getTestFilepaths(ctx, testSpecifications)
427
+ }
428
+ return testFilepaths
429
+ }
430
+
431
+ try {
432
+ const {
433
+ err,
434
+ libraryConfig,
435
+ requestErrorTags: receivedRequestErrorTags = {},
436
+ } = await getChannelPromise(libraryConfigurationCh, frameworkVersion, {
437
+ isVitestNoWorkerInitActive: shouldInstallNoWorkerInit,
438
+ })
439
+ requestErrorTags = receivedRequestErrorTags
440
+ if (err) {
441
+ resetLibraryConfig()
442
+ } else {
443
+ applyLibraryConfig(libraryConfig)
444
+ }
445
+ } catch {
446
+ requestErrorTags = {}
447
+ resetLibraryConfig()
448
+ }
449
+
450
+ resetMainProcessProvidedContext(ctx)
451
+
452
+ if (testSessionConfigurationCh.hasSubscribers) {
453
+ testSessionConfiguration = await getChannelPromise(testSessionConfigurationCh, frameworkVersion)
454
+ const {
455
+ testSessionId,
456
+ testModuleId,
457
+ testCommand,
458
+ repositoryRoot: receivedRepositoryRoot,
459
+ codeOwnersEntries,
460
+ } = testSessionConfiguration
461
+ repositoryRoot = receivedRepositoryRoot || repositoryRoot
462
+ if (!shouldInstallNoWorkerInit) {
463
+ setProvidedContext(ctx, {
464
+ _ddTestSessionId: testSessionId,
465
+ _ddTestModuleId: testModuleId,
466
+ _ddTestCommand: testCommand,
467
+ _ddRepositoryRoot: repositoryRoot,
468
+ _ddCodeOwnersEntries: codeOwnersEntries,
469
+ }, 'Could not send test session configuration to workers.')
470
+ }
471
+ }
472
+
473
+ const {
474
+ knownTestsResponse,
475
+ testManagementTestsResponse,
476
+ } = await getTestOptimizationRequestResults({
477
+ isKnownTestsEnabled,
478
+ isTestManagementTestsEnabled,
479
+ getKnownTests: () => getChannelPromise(knownTestsCh),
480
+ getTestManagementTests: () => getChannelPromise(testManagementTestsCh),
481
+ })
482
+ mergeRequestErrorTags(knownTestsResponse)
483
+ mergeRequestErrorTags(testManagementTestsResponse)
484
+
485
+ const flakyTestRetriesConfiguration = configureFlakyTestRetries(ctx, testSpecifications)
486
+ if (flakyTestRetriesConfiguration) {
487
+ setProvidedContext(ctx, {
488
+ _ddIsFlakyTestRetriesEnabled: isFlakyTestRetriesEnabled,
489
+ _ddFlakyTestRetriesCount: flakyTestRetriesCount,
490
+ _ddFlakyTestRetriesIncludesUnnamedProject: flakyTestRetriesConfiguration.includesUnnamedProject,
491
+ _ddFlakyTestRetriesProjectNames: flakyTestRetriesConfiguration.projectNames,
492
+ }, 'Could not send library configuration to workers.')
493
+ }
494
+
495
+ if (isKnownTestsEnabled) {
496
+ const currentKnownTestsResponse = knownTestsResponse || await getChannelPromise(knownTestsCh)
497
+ if (currentKnownTestsResponse.err) {
498
+ isEarlyFlakeDetectionEnabled = false
499
+ } else {
500
+ knownTests = currentKnownTestsResponse.knownTests
501
+ const currentTestFilepaths = await getCurrentTestFilepaths()
502
+
503
+ if (isValidKnownTests(knownTests)) {
504
+ isEarlyFlakeDetectionFaultyCh.publish({
505
+ knownTests: knownTests.vitest,
506
+ testFilepaths: currentTestFilepaths,
507
+ onDone: (isFaulty) => {
508
+ isEarlyFlakeDetectionFaulty = isFaulty
509
+ },
510
+ })
511
+ if (isEarlyFlakeDetectionFaulty) {
512
+ isEarlyFlakeDetectionEnabled = false
513
+ log.warn('New test detection is disabled because the number of new tests is too high.')
514
+ } else {
515
+ knownTestsBySuite = knownTests.vitest
516
+ shouldSendTestProperties = true
517
+ if (!shouldInstallNoWorkerInit) {
518
+ setProvidedContext(ctx, {
519
+ _ddIsKnownTestsEnabled: isKnownTestsEnabled,
520
+ _ddIsEarlyFlakeDetectionEnabled: isEarlyFlakeDetectionEnabled,
521
+ _ddEarlyFlakeDetectionNumRetries:
522
+ getConfiguredEfdRetryCount(earlyFlakeDetectionSlowTestRetries, earlyFlakeDetectionNumRetries),
523
+ _ddEarlyFlakeDetectionSlowTestRetries: earlyFlakeDetectionSlowTestRetries,
524
+ }, 'Could not send known tests to workers so Early Flake Detection will not work.')
525
+ }
526
+ }
527
+ } else {
528
+ isEarlyFlakeDetectionFaulty = true
529
+ isEarlyFlakeDetectionEnabled = false
530
+ }
531
+ }
532
+ }
533
+
534
+ if (!shouldInstallNoWorkerInit && isDiEnabled) {
535
+ setProvidedContext(ctx, {
536
+ _ddIsDiEnabled: isDiEnabled,
537
+ }, 'Could not send Dynamic Instrumentation configuration to workers.')
538
+ }
539
+
540
+ if (isTestManagementTestsEnabled) {
541
+ const { err, testManagementTests: receivedTestManagementTests } =
542
+ testManagementTestsResponse || await getChannelPromise(testManagementTestsCh)
543
+ if (err) {
544
+ isTestManagementTestsEnabled = false
545
+ log.error('Could not get test management tests.')
546
+ } else {
547
+ testManagementTests = receivedTestManagementTests
548
+ testManagementTestsBySuite = getTestManagementTestsBySuite(receivedTestManagementTests)
549
+ shouldSendTestProperties = true
550
+ if (!shouldInstallNoWorkerInit) {
551
+ setProvidedContext(ctx, {
552
+ _ddIsTestManagementTestsEnabled: isTestManagementTestsEnabled,
553
+ _ddTestManagementAttemptToFixRetries: testManagementAttemptToFixRetries,
554
+ }, 'Could not send test management tests to workers so Test Management will not work.')
555
+ }
556
+ }
557
+ }
558
+
559
+ if (isImpactedTestsEnabled) {
560
+ const modifiedFilesResponse = await getChannelPromise(modifiedFilesCh)
561
+ const { err } = modifiedFilesResponse
562
+ if (err) {
563
+ log.error('Could not get modified tests.')
564
+ } else {
565
+ modifiedFiles = modifiedFilesResponse.modifiedFiles
566
+ impactedTestSuites = getImpactedTestSuites(modifiedFiles)
567
+ shouldSendTestProperties = true
568
+ if (!shouldInstallNoWorkerInit) {
569
+ setProvidedContext(ctx, {
570
+ _ddIsImpactedTestsEnabled: isImpactedTestsEnabled,
571
+ }, 'Could not send modified tests to workers so Impacted Tests will not work.')
572
+ }
573
+ }
574
+ }
575
+
576
+ if (shouldSendTestProperties) {
577
+ testPropertiesByFilepath = getTestPropertiesByFilepath(
578
+ await getCurrentTestFilepaths(),
579
+ repositoryRoot,
580
+ knownTestsBySuite,
581
+ testManagementTestsBySuite,
582
+ impactedTestSuites
583
+ )
584
+ if (!shouldInstallNoWorkerInit) {
585
+ setProvidedContext(ctx, {
586
+ _ddTestPropertiesByFilepath: testPropertiesByFilepath,
587
+ }, 'Could not send test properties to workers so some Test Optimization features will not work.')
588
+ }
589
+ }
590
+
591
+ if (shouldInstallNoWorkerInit) {
592
+ noWorkerInit.configure(ctx, frameworkVersion, testSpecifications, {
593
+ knownTests,
594
+ knownTestsBySuite,
595
+ modifiedFiles,
596
+ repositoryRoot,
597
+ flakyTestRetriesConfiguration,
598
+ testManagementTests,
599
+ testManagementTestsBySuite,
600
+ testPropertiesByFilepath: testPropertiesByFilepath || {},
601
+ testSessionConfiguration,
602
+ }, {
603
+ getConfiguredEfdRetryCount,
604
+ state: getNoWorkerInitState(),
605
+ })
606
+ }
607
+
608
+ wrapCoverageProvider(ctx)
609
+ wrapSessionFinish(ctx)
610
+ return shouldInstallNoWorkerInit
611
+ }
612
+
613
+ function getNoWorkerInitState () {
614
+ return {
615
+ attemptToFixExecutions,
616
+ earlyFlakeDetectionNumRetries,
617
+ earlyFlakeDetectionSlowTestRetries,
618
+ isEarlyFlakeDetectionEnabled,
619
+ isEarlyFlakeDetectionFaulty,
620
+ isFlakyTestRetriesEnabled,
621
+ isKnownTestsEnabled,
622
+ newTestsWithDynamicNames,
623
+ requestErrorTags,
624
+ testManagementAttemptToFixRetries,
625
+ }
626
+ }
627
+
628
+ function ensureMainProcessSetup (ctx, frameworkVersion, testSpecifications, shouldDeactivateOnFallback = false) {
629
+ const shouldInstallNoWorkerInit = shouldUseNoWorkerInit(ctx, frameworkVersion, testSpecifications)
630
+ const specificationsKey = getTestSpecificationsKey(testSpecifications)
631
+ let setupState = mainProcessSetupStates.get(ctx)
632
+ if (shouldDeactivateOnFallback && setupState?.shouldInstallNoWorkerInit && !shouldInstallNoWorkerInit) {
633
+ noWorkerInit.deactivate(ctx)
634
+ }
635
+ if (
636
+ !setupState ||
637
+ setupState.specificationsKey !== specificationsKey ||
638
+ setupState.shouldInstallNoWorkerInit !== shouldInstallNoWorkerInit
639
+ ) {
640
+ setupState = {
641
+ setupPromise: runMainProcessSetup(ctx, frameworkVersion, testSpecifications, shouldInstallNoWorkerInit),
642
+ shouldInstallNoWorkerInit,
643
+ specificationsKey,
644
+ }
645
+ mainProcessSetupStates.set(ctx, setupState)
646
+ }
647
+ return setupState.setupPromise
648
+ }
649
+
650
+ function shouldUseNoWorkerInit (ctx, frameworkVersion, testSpecifications) {
651
+ return noWorkerInit.shouldUse(ctx, frameworkVersion, testSpecifications, {
652
+ hasVitestWorkerPoolTestSpecification,
653
+ isVitestWorkerPool,
654
+ })
655
+ }
656
+
657
+ function configureFlakyTestRetries (ctx, testSpecifications) {
658
+ if (!isFlakyTestRetriesEnabled || flakyTestRetriesCount <= 0) return
659
+
660
+ let configured = false
661
+ let includesUnnamedProject = false
662
+ const projectNames = []
663
+ for (const { config, projectName } of getVitestProjectConfigs(ctx, testSpecifications)) {
664
+ if (!config.retry) {
665
+ config.retry = flakyTestRetriesCount
666
+ configured = true
667
+ if (projectName) {
668
+ projectNames.push(projectName)
669
+ } else {
670
+ includesUnnamedProject = true
671
+ }
672
+ }
673
+ }
674
+
675
+ if (!configured) return
676
+
677
+ return {
678
+ includesUnnamedProject,
679
+ projectNames,
680
+ }
681
+ }
682
+
683
+ function getVitestProjectConfigs (ctx, testSpecifications) {
684
+ const entries = []
685
+
686
+ addTestSpecificationConfigs(entries, testSpecifications)
687
+ if (entries.length > 0) {
688
+ return entries
689
+ }
690
+
691
+ const selectedProjectNames = getSelectedProjectNames()
692
+ addSelectedInlineProjectConfigs(entries, safeConfig(ctx), selectedProjectNames)
693
+ addSelectedRuntimeProjectConfigs(entries, ctx?.projects, selectedProjectNames)
694
+ if (entries.length > 0) {
695
+ return entries
696
+ }
697
+
698
+ if (Array.isArray(ctx?.projects)) {
699
+ for (const project of ctx.projects) {
700
+ addConfig(entries, safeConfig(project), getProjectName(project))
701
+ }
702
+ if (entries.length > 0) {
703
+ return entries
704
+ }
705
+ }
706
+
707
+ addConfig(entries, safeConfig(ctx))
708
+ addConfig(entries, safeConfig(safeWorkspaceProject(ctx)))
709
+
710
+ return entries
711
+ }
712
+
713
+ function addTestSpecificationConfigs (entries, testSpecifications) {
714
+ if (!Array.isArray(testSpecifications)) return
715
+
716
+ for (const testSpecification of testSpecifications) {
717
+ const project = getTestSpecificationProject(testSpecification)
718
+ addConfig(entries, safeConfig(project), getProjectName(project))
719
+ }
720
+ }
721
+
722
+ function addSelectedInlineProjectConfigs (entries, rootConfig, selectedProjectNames) {
723
+ if (selectedProjectNames.length === 0 || !Array.isArray(rootConfig?.projects)) return
724
+
725
+ for (const project of rootConfig.projects) {
726
+ const config = getInlineProjectConfig(project)
727
+ const projectName = getProjectName(project)
728
+ if (selectedProjectNames.includes(projectName)) {
729
+ addConfig(entries, config, projectName)
730
+ }
731
+ }
732
+ }
733
+
734
+ function addSelectedRuntimeProjectConfigs (entries, projects, selectedProjectNames) {
735
+ if (selectedProjectNames.length === 0 || !Array.isArray(projects)) return
736
+
737
+ for (const project of projects) {
738
+ const projectName = getProjectName(project)
739
+ if (selectedProjectNames.includes(projectName)) {
740
+ addConfig(entries, safeConfig(project), projectName)
741
+ }
742
+ }
743
+ }
744
+
745
+ function getSelectedProjectNames () {
746
+ const names = []
747
+ for (let index = 0; index < process.argv.length; index++) {
748
+ const argument = process.argv[index]
749
+ if (argument === '--project' && process.argv[index + 1]) {
750
+ names.push(process.argv[index + 1])
751
+ index++
752
+ } else if (argument.startsWith('--project=')) {
753
+ names.push(argument.slice('--project='.length))
754
+ }
755
+ }
756
+ return names
757
+ }
758
+
759
+ function getInlineProjectConfig (project) {
760
+ return project?.test || project
761
+ }
762
+
763
+ function getProjectName (project) {
764
+ return normalizeProjectName(project?.name || project?.config?.name || project?.test?.name)
765
+ }
766
+
767
+ function normalizeProjectName (name) {
768
+ if (typeof name === 'string') return name
769
+
770
+ const label = name?.label
771
+ return typeof label === 'string' ? label : undefined
772
+ }
773
+
774
+ function addConfig (entries, config, projectName) {
775
+ if (config && !entries.some(entry => entry.config === config || (projectName && entry.projectName === projectName))) {
776
+ entries.push({ config, projectName })
777
+ }
778
+ }
779
+
780
+ function safeConfig (project) {
781
+ let config
782
+ try {
783
+ config = project?.config
784
+ } catch {}
785
+ return config
786
+ }
787
+
788
+ function safeWorkspaceProject (ctx) {
789
+ let project
790
+ try {
791
+ project = getWorkspaceProject(ctx)
792
+ } catch {}
793
+ return project
794
+ }
795
+
796
+ function getSortWrapper (sort, frameworkVersion) {
797
+ return async function () {
798
+ await ensureMainProcessSetup(this.ctx, frameworkVersion, arguments[0])
799
+ return sort.apply(this, arguments)
800
+ }
801
+ }
802
+
803
+ function getFinishWrapper (exitOrClose) {
804
+ let isClosed = false
805
+ return async function () {
806
+ if (isClosed) { // needed because exit calls close
807
+ return exitOrClose.apply(this, arguments)
808
+ }
809
+ isClosed = true
810
+
811
+ if (!testSessionFinishCh.hasSubscribers) {
812
+ return exitOrClose.apply(this, arguments)
813
+ }
814
+
815
+ let onFinish
816
+
817
+ const flushPromise = new Promise(resolve => {
818
+ onFinish = resolve
819
+ })
820
+ const failedSuites = this.state.getFailedFilepaths()
821
+ let error
822
+ if (failedSuites.length) {
823
+ error = new Error(`Test suites failed: ${failedSuites.length}.`)
824
+ }
825
+
826
+ testSessionFinishCh.publish({
827
+ status: getSessionStatus(this.state),
828
+ testCodeCoverageLinesTotal,
829
+ error,
830
+ isEarlyFlakeDetectionEnabled,
831
+ isEarlyFlakeDetectionFaulty,
832
+ isTestManagementTestsEnabled,
833
+ requestErrorTags,
834
+ vitestPool,
835
+ isVitestNoWorkerInitActive,
836
+ onFinish,
837
+ })
838
+
839
+ logTestOptimizationSummary({ attemptToFixExecutions, newTestsWithDynamicNames })
840
+
841
+ await flushPromise
842
+
843
+ // If coverage was generated, publish coverage report channel for upload
844
+ if (coverageRootDir && codeCoverageReportCh.hasSubscribers) {
845
+ await new Promise((resolve) => {
846
+ codeCoverageReportCh.publish({ rootDir: coverageRootDir, onDone: resolve })
847
+ })
848
+ }
849
+
850
+ return exitOrClose.apply(this, arguments)
851
+ }
852
+ }
853
+
854
+ function getCliOrStartVitestWrapper (frameworkVersion) {
855
+ return function (oldCliOrStartVitest) {
856
+ return function (...args) {
857
+ if (!testSessionStartCh.hasSubscribers || isSessionStarted) {
858
+ return oldCliOrStartVitest.apply(this, args)
859
+ }
860
+ isSessionStarted = true
861
+ testSessionStartCh.publish({ command: getTestCommand(), frameworkVersion })
862
+ return oldCliOrStartVitest.apply(this, args)
863
+ }
864
+ }
865
+ }
866
+
867
+ function isForkPool (pool) {
868
+ return pool === 'forks' || pool === 'vmForks'
869
+ }
870
+
871
+ function isThreadPool (pool) {
872
+ return pool === 'threads' || pool === 'vmThreads'
873
+ }
874
+
875
+ function isVitestWorkerPool (pool) {
876
+ return isForkPool(pool) || isThreadPool(pool)
877
+ }
878
+
879
+ function getTestSpecificationProject (testSpecification) {
880
+ if (Array.isArray(testSpecification)) {
881
+ return testSpecification[0]
882
+ }
883
+ return testSpecification?.project
884
+ }
885
+
886
+ function getTestSpecificationOptions (testSpecification) {
887
+ if (Array.isArray(testSpecification)) {
888
+ return testSpecification[2]
889
+ }
890
+ return testSpecification
891
+ }
892
+
893
+ function getTestSpecificationPool (testSpecification) {
894
+ const options = getTestSpecificationOptions(testSpecification)
895
+ const project = getTestSpecificationProject(testSpecification)
896
+ return options?.pool || project?.config?.pool || project?.serializedConfig?.pool || project?.pool ||
897
+ testSpecification?.pool
898
+ }
899
+
900
+ function hasVitestWorkerPoolTestSpecification (testSpecifications) {
901
+ if (!Array.isArray(testSpecifications)) {
902
+ return false
903
+ }
904
+
905
+ for (const testSpecification of testSpecifications) {
906
+ if (isVitestWorkerPool(getTestSpecificationPool(testSpecification))) {
907
+ return true
908
+ }
909
+ }
910
+
911
+ return false
912
+ }
913
+
914
+ function shouldMarkVitestWorkerEnv (pool, testSpecifications, shouldSkipWorkerInit) {
915
+ if (!shouldSkipWorkerInit) {
916
+ return isVitestWorkerPool(pool) || hasVitestWorkerPoolTestSpecification(testSpecifications) ||
917
+ (!testSpecifications && pool === undefined)
918
+ }
919
+
920
+ return isVitestWorkerPool(pool) || pool === undefined || hasVitestWorkerPoolTestSpecification(testSpecifications)
921
+ }
922
+
923
+ function markVitestWorkerEnv (ctx, testSpecifications, shouldSkipWorkerInit = false) {
924
+ const config = ctx?.config
925
+ isVitestNoWorkerInitActive = shouldSkipWorkerInit
926
+ if (!config || !shouldMarkVitestWorkerEnv(config.pool, testSpecifications, shouldSkipWorkerInit)) {
927
+ return
928
+ }
929
+ config.env = getVitestWorkerEnv(config.env, shouldSkipWorkerInit)
930
+ }
931
+
932
+ function wrapVitestRunFiles (Vitest, frameworkVersion) {
933
+ if (!Vitest?.prototype?.runFiles) {
934
+ return
935
+ }
936
+
937
+ shimmer.wrap(Vitest.prototype, 'runFiles', runFiles => async function (testSpecifications) {
938
+ const shouldSkipWorkerInit = await ensureMainProcessSetup(this, frameworkVersion, testSpecifications, true)
939
+ markVitestWorkerEnv(this, testSpecifications, shouldSkipWorkerInit)
940
+ return runFiles.apply(this, arguments)
941
+ })
942
+
943
+ if (Vitest.prototype.collectTests) {
944
+ shimmer.wrap(Vitest.prototype, 'collectTests', collectTests => function (testSpecifications) {
945
+ const shouldSkipWorkerInit = shouldUseNoWorkerInit(this, frameworkVersion, testSpecifications)
946
+ markVitestWorkerEnv(this, testSpecifications, shouldSkipWorkerInit)
947
+ return collectTests.apply(this, arguments)
948
+ })
949
+ }
950
+ }
951
+
952
+ function getTypecheckTaskStatus (task) {
953
+ const state = task.result?.state
954
+ if (state === 'fail') return 'fail'
955
+ if (state === 'skip' || task.mode === 'skip' || task.mode === 'todo') return 'skip'
956
+ return 'pass'
957
+ }
958
+
959
+ /**
960
+ * Return whether a typecheck suite name represents the synthetic file-level suite.
961
+ *
962
+ * @param {string|undefined} suiteName
963
+ * @param {string} testSuiteAbsolutePath
964
+ * @returns {boolean}
965
+ */
966
+ function isTypecheckFileSuiteName (suiteName, testSuiteAbsolutePath) {
967
+ if (!suiteName || !testSuiteAbsolutePath) return false
968
+
969
+ const normalizedSuiteName = path.normalize(suiteName).replaceAll('\\', '/')
970
+ const normalizedSuitePath = path.normalize(testSuiteAbsolutePath).replaceAll('\\', '/')
971
+
972
+ return normalizedSuitePath === normalizedSuiteName || normalizedSuitePath.endsWith(`/${normalizedSuiteName}`)
973
+ }
974
+
975
+ /**
976
+ * Return a typecheck test name with describe/suite prefixes and without the file-level suite prefix.
977
+ *
978
+ * @param {object} task
979
+ * @param {string} testSuiteAbsolutePath
980
+ * @returns {string}
981
+ */
982
+ function getTypecheckTestName (task, testSuiteAbsolutePath) {
983
+ let testName = task.name || task.fullTestName
984
+ let currentTask = task.suite
985
+
986
+ while (currentTask) {
987
+ if (currentTask.name && !isTypecheckFileSuiteName(currentTask.name, testSuiteAbsolutePath)) {
988
+ testName = `${currentTask.name} ${testName}`
989
+ }
990
+ currentTask = currentTask.suite
991
+ }
992
+
993
+ return testName
994
+ }
995
+
996
+ /**
997
+ * Return Test Optimization metadata prepared in Vitest's main process setup.
998
+ *
999
+ * @param {object|undefined} ctx
1000
+ * @returns {{ testPropertiesByFilepath: object }}
1001
+ */
1002
+ function getMainProcessProvidedContext (ctx) {
1003
+ try {
1004
+ const workspaceProject = getWorkspaceProject(ctx)
1005
+ const providedContext = workspaceProject.getProvidedContext?.() || workspaceProject._provided || {}
1006
+
1007
+ return {
1008
+ testPropertiesByFilepath: providedContext._ddTestPropertiesByFilepath || {},
1009
+ }
1010
+ } catch {
1011
+ return {
1012
+ testPropertiesByFilepath: {},
1013
+ }
1014
+ }
1015
+ }
1016
+
1017
+ /**
1018
+ * Return the Vitest context that owns a Typechecker instance.
1019
+ *
1020
+ * @param {object} typechecker
1021
+ * @returns {object|undefined}
1022
+ */
1023
+ function getTypecheckerVitestContext (typechecker) {
1024
+ return typechecker.ctx || typechecker.project?.vitest
1025
+ }
1026
+
1027
+ /**
1028
+ * Apply Test Management result semantics to Vitest's returned typecheck task result.
1029
+ *
1030
+ * @param {object} task
1031
+ * @param {string} status
1032
+ * @param {{
1033
+ * isAttemptToFix: boolean,
1034
+ * isDisabled: boolean,
1035
+ * isQuarantined: boolean
1036
+ * }} testManagement
1037
+ */
1038
+ function updateTypecheckTaskResultForTestManagement (task, status, testManagement) {
1039
+ const { isAttemptToFix, isDisabled, isQuarantined } = testManagement
1040
+ if (isAttemptToFix || !task.result) return
1041
+
1042
+ if (isDisabled) {
1043
+ task.mode = 'skip'
1044
+ task.result.state = 'skip'
1045
+ task.result.errors = []
1046
+ return
1047
+ }
1048
+
1049
+ if (isQuarantined && status === 'fail') {
1050
+ task.result.state = 'pass'
1051
+ task.result.errors = []
1052
+ }
1053
+ }
1054
+
1055
+ /**
1056
+ * Recompute suite/file typecheck results after Test Management rewrites child test results.
1057
+ *
1058
+ * @param {object} task
1059
+ * @returns {string}
1060
+ */
1061
+ function updateTypecheckTaskTreeResult (task) {
1062
+ if (!Array.isArray(task.tasks)) return getTypecheckTaskStatus(task)
1063
+
1064
+ let hasPassedTest = false
1065
+ let hasSkippedTest = false
1066
+ for (const childTask of task.tasks) {
1067
+ const status = updateTypecheckTaskTreeResult(childTask)
1068
+ if (status === 'fail') {
1069
+ task.result = {
1070
+ ...task.result,
1071
+ state: 'fail',
1072
+ }
1073
+ return 'fail'
1074
+ }
1075
+ if (status === 'skip') {
1076
+ hasSkippedTest = true
1077
+ } else {
1078
+ hasPassedTest = true
1079
+ }
1080
+ }
1081
+
1082
+ if (task.result?.errors?.length) return 'fail'
1083
+ if (!hasPassedTest && !hasSkippedTest) return getTypecheckTaskStatus(task)
1084
+
1085
+ task.result = {
1086
+ ...task.result,
1087
+ state: hasPassedTest ? 'pass' : 'skip',
1088
+ errors: [],
1089
+ }
1090
+ return task.result.state
1091
+ }
1092
+
1093
+ /**
1094
+ * Recompute the aggregate typecheck result after Test Management rewrites file results.
1095
+ *
1096
+ * @param {{
1097
+ * files?: object[],
1098
+ * errors?: object[],
1099
+ * diagnostics?: object[],
1100
+ * sourceErrors?: object[],
1101
+ * state?: string
1102
+ * }} result
1103
+ * @returns {boolean}
1104
+ */
1105
+ function updateTypecheckResult (result) {
1106
+ if (result.sourceErrors?.length) return false
1107
+
1108
+ let hasPassedFile = false
1109
+ let hasSkippedFile = false
1110
+ for (const file of result.files) {
1111
+ const status = getTypecheckTaskStatus(file)
1112
+ if (status === 'fail') return false
1113
+ if (status === 'skip') {
1114
+ hasSkippedFile = true
1115
+ } else {
1116
+ hasPassedFile = true
1117
+ }
1118
+ }
1119
+
1120
+ if (!hasPassedFile && !hasSkippedFile) return false
1121
+
1122
+ result.state = hasPassedFile ? 'pass' : 'skip'
1123
+ result.errors = []
1124
+ result.diagnostics = []
1125
+ result.sourceErrors = []
1126
+ return true
1127
+ }
1128
+
1129
+ /**
1130
+ * Clear Vitest's typechecker exit code after all typecheck failures were handled by Test Management.
1131
+ *
1132
+ * @param {{ process?: { exitCode?: number|null } }} typechecker
1133
+ */
1134
+ function clearTypecheckerExitCode (typechecker) {
1135
+ if (typechecker?.process?.exitCode == null) return
1136
+
1137
+ typechecker.process.exitCode = 0
1138
+ }
1139
+
1140
+ function reportTypecheckTest (task, testSuiteAbsolutePath, providedContext) {
1141
+ const testName = getTypecheckTestName(task, testSuiteAbsolutePath)
1142
+ const testProperties = getVitestTestProperties(providedContext, testSuiteAbsolutePath, testName)
1143
+ const isAttemptToFix = testProperties.isAttemptToFix === true
1144
+ const isDisabled = testProperties.isDisabled === true
1145
+ const isQuarantined = testProperties.isQuarantined === true
1146
+ const isModified = testProperties.isModified === true
1147
+ const isSkippedByTestManagement = !isAttemptToFix && isDisabled
1148
+ const status = getTypecheckTaskStatus(task)
1149
+
1150
+ if (status === 'skip' || isSkippedByTestManagement) {
1151
+ testSkipCh.publish({
1152
+ testName,
1153
+ testSuiteAbsolutePath,
1154
+ isNew: testProperties.isNew,
1155
+ isDisabled,
1156
+ })
1157
+ updateTypecheckTaskResultForTestManagement(task, status, { isAttemptToFix, isDisabled, isQuarantined })
1158
+ return
1159
+ }
1160
+
1161
+ const ctx = {
1162
+ testName,
1163
+ testSuiteAbsolutePath,
1164
+ isRetry: false,
1165
+ isNew: testProperties.isNew,
1166
+ hasDynamicName: false,
1167
+ mightHitProbe: false,
1168
+ isAttemptToFix,
1169
+ isDisabled,
1170
+ isQuarantined,
1171
+ isModified,
1172
+ }
1173
+ testStartCh.runStores(ctx, () => {})
1174
+
1175
+ const finalStatus = !isAttemptToFix && isQuarantined ? 'skip' : undefined
1176
+ if (status === 'fail') {
1177
+ testErrorCh.publish({
1178
+ error: task.result?.errors?.[0],
1179
+ finalStatus,
1180
+ ...ctx.currentStore,
1181
+ })
1182
+ } else {
1183
+ testPassCh.publish({
1184
+ task,
1185
+ finalStatus,
1186
+ ...ctx.currentStore,
1187
+ })
1188
+ }
1189
+ updateTypecheckTaskResultForTestManagement(task, status, { isAttemptToFix, isDisabled, isQuarantined })
1190
+ }
1191
+
1192
+ async function reportTypecheckFile (file, sessionConfiguration, frameworkVersion, providedContext) {
1193
+ const testSuiteAbsolutePath = file.filepath
1194
+ const testSuiteCtx = {
1195
+ testSuiteAbsolutePath,
1196
+ frameworkVersion,
1197
+ testSessionId: sessionConfiguration.testSessionId,
1198
+ testModuleId: sessionConfiguration.testModuleId,
1199
+ testCommand: sessionConfiguration.testCommand,
1200
+ repositoryRoot: sessionConfiguration.repositoryRoot,
1201
+ codeOwnersEntries: sessionConfiguration.codeOwnersEntries,
1202
+ }
1203
+ testSuiteStartCh.runStores(testSuiteCtx, () => {})
1204
+
1205
+ for (const task of getTypeTasks(file.tasks)) {
1206
+ reportTypecheckTest(task, testSuiteAbsolutePath, providedContext)
1207
+ }
1208
+ updateTypecheckTaskTreeResult(file)
1209
+
1210
+ const testSuiteError = file.result?.errors?.[0]
1211
+ if (testSuiteError) {
1212
+ testSuiteCtx.error = testSuiteError
1213
+ testSuiteErrorCh.runStores(testSuiteCtx, () => {})
1214
+ }
1215
+
1216
+ let onFinish
1217
+ const onFinishPromise = new Promise(resolve => {
1218
+ onFinish = resolve
1219
+ })
1220
+ testSuiteFinishCh.publish({
1221
+ status: getTypecheckTaskStatus(file),
1222
+ onFinish,
1223
+ ...testSuiteCtx.currentStore,
1224
+ })
1225
+ await onFinishPromise
1226
+ }
1227
+
1228
+ async function reportTypecheckResults (result, frameworkVersion, ctx, typechecker) {
1229
+ if (!testSuiteFinishCh.hasSubscribers) return
1230
+ if (!Array.isArray(result?.files)) return
1231
+
1232
+ if (ctx) {
1233
+ await ensureMainProcessSetup(ctx, frameworkVersion, result.files)
1234
+ }
1235
+ const providedContext = getMainProcessProvidedContext(ctx)
1236
+ const sessionConfiguration = testSessionConfigurationCh.hasSubscribers
1237
+ ? await getChannelPromise(testSessionConfigurationCh, frameworkVersion)
1238
+ : {}
1239
+
1240
+ await Promise.all(result.files.map(file => reportTypecheckFile(
1241
+ file,
1242
+ sessionConfiguration,
1243
+ frameworkVersion,
1244
+ providedContext
1245
+ )))
1246
+ if (updateTypecheckResult(result)) {
1247
+ clearTypecheckerExitCode(typechecker)
1248
+ }
1249
+ }
1250
+
1251
+ function wrapTypechecker (Typechecker, frameworkVersion) {
1252
+ if (!Typechecker?.prototype?.prepareResults) return
1253
+
1254
+ shimmer.wrap(Typechecker.prototype, 'prepareResults', prepareResults => async function () {
1255
+ const result = await prepareResults.apply(this, arguments)
1256
+ await reportTypecheckResults(result, frameworkVersion, getTypecheckerVitestContext(this), this)
1257
+ return result
1258
+ })
1259
+ }
1260
+
1261
+ function getTypecheckerWrapper (vitestPackage, frameworkVersion) {
1262
+ const typechecker = getTypecheckerExport(vitestPackage)
1263
+ if (typechecker) {
1264
+ wrapTypechecker(typechecker.value, frameworkVersion)
1265
+ }
1266
+ return vitestPackage
1267
+ }
1268
+
1269
+ function getCreateCliWrapper (vitestPackage, frameworkVersion) {
1270
+ const createCliExport = findExportByName(vitestPackage, 'createCLI')
1271
+ if (!createCliExport) {
1272
+ return vitestPackage
1273
+ }
1274
+ shimmer.wrap(vitestPackage, createCliExport.key, getCliOrStartVitestWrapper(frameworkVersion))
1275
+
1276
+ return vitestPackage
1277
+ }
1278
+
1279
+ function threadHandler (thread) {
1280
+ const { runtime } = thread
1281
+ let workerProcess
1282
+ if (runtime === 'child_process') {
1283
+ vitestPool = 'child_process'
1284
+ workerProcess = thread.process
1285
+ } else if (runtime === 'worker_threads') {
1286
+ vitestPool = 'worker_threads'
1287
+ workerProcess = thread.thread
1288
+ } else {
1289
+ vitestPool = 'unknown'
1290
+ }
1291
+ if (!workerProcess) {
1292
+ log.error('Vitest error: could not get process or thread from TinyPool#run')
1293
+ return
1294
+ }
1295
+
1296
+ if (workerProcesses.has(workerProcess)) {
1297
+ return
1298
+ }
1299
+ workerProcesses.add(workerProcess)
1300
+ workerProcess.on('message', (message) => {
1301
+ if (message.__tinypool_worker_message__ && message.data) {
1302
+ handleWorkerReport(message.interprocessCode, message.data)
1303
+ }
1304
+ })
1305
+ }
1306
+
1307
+ function isVitestTinypoolOptions (options) {
1308
+ if (options?.env?.VITEST !== 'true' || typeof options.filename !== 'string') return false
1309
+
1310
+ let filename = options.filename
1311
+ if (filename.startsWith('file:')) {
1312
+ try {
1313
+ filename = fileURLToPath(filename)
1314
+ } catch {
1315
+ return false
1316
+ }
1317
+ }
1318
+
1319
+ const workerPath = path.normalize(filename)
1320
+ const workerDir = path.dirname(workerPath)
1321
+ const packageDir = path.dirname(workerDir)
1322
+
1323
+ return path.basename(workerPath) === 'worker.js' &&
1324
+ path.basename(workerDir) === 'dist' &&
1325
+ path.basename(packageDir) === 'vitest'
1326
+ }
1327
+
1328
+ function markVitestTinypoolOptions (options) {
1329
+ if (!isVitestTinypoolOptions(options)) return
1330
+
1331
+ options.env = getVitestWorkerEnv(options.env, isVitestNoWorkerInitActive)
1332
+ }
1333
+
1334
+ function getVitestWorkerEnv (env = {}, shouldSkipWorkerInit = false) {
1335
+ return noWorkerInit.configureWorkerEnv({
1336
+ ...env,
1337
+ DD_VITEST_WORKER: '1',
1338
+ }, shouldSkipWorkerInit)
1339
+ }
1340
+
1341
+ function wrapTinyPoolRun (TinyPool) {
1342
+ if (!TinyPool?.prototype?.run) return
1343
+
1344
+ shimmer.wrap(TinyPool.prototype, 'run', run => async function () {
1345
+ // We have to do this before and after because the threads list gets recycled, that is, the processes are re-created
1346
+ // eslint-disable-next-line unicorn/no-array-for-each
1347
+ this.threads.forEach(threadHandler)
1348
+ const runResult = await run.apply(this, arguments)
1349
+ // eslint-disable-next-line unicorn/no-array-for-each
1350
+ this.threads.forEach(threadHandler)
1351
+ return runResult
1352
+ })
1353
+ }
1354
+
1355
+ function wrapTinyPoolClass (TinyPool) {
1356
+ if (typeof TinyPool !== 'function') return TinyPool
1357
+
1358
+ const wrappedTinyPool = tinyPoolClassWrappers.get(TinyPool)
1359
+ if (wrappedTinyPool) return wrappedTinyPool
1360
+
1361
+ class DatadogTinyPool extends TinyPool {
1362
+ constructor (options) {
1363
+ markVitestTinypoolOptions(options)
1364
+ super(options)
1365
+ }
1366
+ }
1367
+
1368
+ tinyPoolClassWrappers.set(TinyPool, DatadogTinyPool)
1369
+ wrapTinyPoolRun(DatadogTinyPool)
1370
+
1371
+ return DatadogTinyPool
1372
+ }
1373
+
1374
+ function wrapTinyPool (TinyPool) {
1375
+ if (typeof TinyPool === 'function') {
1376
+ return wrapTinyPoolClass(TinyPool)
1377
+ }
1378
+
1379
+ const defaultTinyPool = wrapTinyPoolClass(TinyPool?.default)
1380
+ if (defaultTinyPool) {
1381
+ TinyPool.default = defaultTinyPool
1382
+ }
1383
+
1384
+ const namedTinyPool = TinyPool?.Tinypool === TinyPool?.default
1385
+ ? defaultTinyPool
1386
+ : wrapTinyPoolClass(TinyPool?.Tinypool)
1387
+ if (namedTinyPool) {
1388
+ TinyPool.Tinypool = namedTinyPool
1389
+ }
1390
+
1391
+ return TinyPool
1392
+ }
1393
+
1394
+ function getWrappedOn (on) {
1395
+ return function (event, callback) {
1396
+ if (event !== 'message') {
1397
+ return on.apply(this, arguments)
1398
+ }
1399
+ // `arguments[1]` is the callback function, which
1400
+ // we modify to intercept our messages to not interfere
1401
+ // with vitest's own messages
1402
+ arguments[1] = shimmer.wrapFunction(callback, callback => function (message) {
1403
+ if (message.type !== 'Buffer' && Array.isArray(message)) {
1404
+ const [interprocessCode, data] = message
1405
+ if (handleWorkerReport(interprocessCode, data)) {
1406
+ // If we execute the callback vitest crashes, as the message is not supported
1407
+ return
1408
+ }
1409
+ }
1410
+ return callback.apply(this, arguments)
1411
+ })
1412
+ return on.apply(this, arguments)
1413
+ }
1414
+ }
1415
+
1416
+ function handleWorkerReport (interprocessCode, data) {
1417
+ if (interprocessCode === VITEST_WORKER_TRACE_PAYLOAD_CODE) {
1418
+ collectTestOptimizationSummariesFromTraces(data, {
1419
+ newTestsWithDynamicNames,
1420
+ attemptToFixExecutions,
1421
+ })
1422
+ workerReportTraceCh.publish(data)
1423
+ return true
1424
+ }
1425
+
1426
+ if (interprocessCode === VITEST_WORKER_LOGS_PAYLOAD_CODE) {
1427
+ workerReportLogsCh.publish(data)
1428
+ return true
1429
+ }
1430
+
1431
+ return false
1432
+ }
1433
+
1434
+ function wrapMessagePortOn () {
1435
+ if (isMessagePortWrapped) return
1436
+
1437
+ isMessagePortWrapped = true
1438
+ shimmer.wrap(MessagePort.prototype, 'on', getWrappedOn)
1439
+ shimmer.wrap(MessagePort.prototype, 'addListener', getWrappedOn)
1440
+ }
1441
+
1442
+ function getStartVitestWrapper (cliApiPackage, frameworkVersion) {
1443
+ if (!isCliApiPackage(cliApiPackage)) {
1444
+ return cliApiPackage
1445
+ }
1446
+ const startVitestExport = findExportByName(cliApiPackage, 'startVitest')
1447
+ shimmer.wrap(cliApiPackage, startVitestExport.key, getCliOrStartVitestWrapper(frameworkVersion))
1448
+ wrapMessagePortOn()
1449
+
1450
+ const vitest = getVitestExport(cliApiPackage)
1451
+ if (vitest) {
1452
+ wrapVitestRunFiles(vitest.value, frameworkVersion)
1453
+ }
1454
+
1455
+ const forksPoolWorker = getForksPoolWorkerExport(cliApiPackage)
1456
+ if (forksPoolWorker) {
1457
+ // function is async
1458
+ shimmer.wrap(forksPoolWorker.value.prototype, 'start', start => function (...args) {
1459
+ vitestPool = 'child_process'
1460
+ this.env = getVitestWorkerEnv(this.env, isVitestNoWorkerInitActive)
1461
+
1462
+ return start.apply(this, args)
1463
+ })
1464
+ shimmer.wrap(forksPoolWorker.value.prototype, 'on', getWrappedOn)
1465
+ }
1466
+
1467
+ const threadsPoolWorker = getThreadsPoolWorkerExport(cliApiPackage)
1468
+ if (threadsPoolWorker) {
1469
+ // function is async
1470
+ shimmer.wrap(threadsPoolWorker.value.prototype, 'start', start => function (...args) {
1471
+ vitestPool = 'worker_threads'
1472
+ this.env = getVitestWorkerEnv(this.env, isVitestNoWorkerInitActive)
1473
+ return start.apply(this, args)
1474
+ })
1475
+ shimmer.wrap(threadsPoolWorker.value.prototype, 'on', getWrappedOn)
1476
+ }
1477
+ return cliApiPackage
1478
+ }
1479
+
1480
+ addHook({
1481
+ name: 'tinypool',
1482
+ // version from tinypool@0.8 was used in vitest@1.6.0
1483
+ versions: ['>=0.8.0'],
1484
+ }, (TinyPool) => {
1485
+ return wrapTinyPool(TinyPool)
1486
+ })
1487
+
1488
+ // There are multiple index* files across different versions of vitest,
1489
+ // so we check for the existence of BaseSequencer to determine if we are in the right file
1490
+ addHook({
1491
+ name: 'vitest',
1492
+ versions: ['>=1.6.0 <2.0.0'],
1493
+ filePattern: 'dist/vendor/index.*',
1494
+ }, (vitestPackage) => {
1495
+ if (isReporterPackage(vitestPackage)) {
1496
+ shimmer.wrap(vitestPackage.B.prototype, 'sort', getSortWrapper)
1497
+ }
1498
+
1499
+ return vitestPackage
1500
+ })
1501
+
1502
+ addHook({
1503
+ name: 'vitest',
1504
+ versions: ['>=2.0.0 <2.0.5'],
1505
+ filePattern: 'dist/vendor/index.*',
1506
+ }, (vitestPackage) => {
1507
+ if (isReporterPackageNew(vitestPackage)) {
1508
+ shimmer.wrap(vitestPackage.e.prototype, 'sort', getSortWrapper)
1509
+ }
1510
+
1511
+ return vitestPackage
1512
+ })
1513
+
1514
+ addHook({
1515
+ name: 'vitest',
1516
+ versions: ['>=2.0.5 <2.1.0'],
1517
+ filePattern: 'dist/chunks/index.*',
1518
+ }, (vitestPackage) => {
1519
+ if (isReporterPackageNewest(vitestPackage)) {
1520
+ shimmer.wrap(vitestPackage.h.prototype, 'sort', getSortWrapper)
1521
+ }
1522
+
1523
+ return vitestPackage
1524
+ })
1525
+
1526
+ addHook({
1527
+ name: 'vitest',
1528
+ versions: ['>=3.2.0 <4.0.0'],
1529
+ filePattern: 'dist/chunks/typechecker.*',
1530
+ }, getTypecheckerWrapper)
1531
+
1532
+ addHook({
1533
+ name: 'vitest',
1534
+ versions: ['>=4.0.0'],
1535
+ filePattern: 'dist/chunks/index.*',
1536
+ }, getTypecheckerWrapper)
1537
+
1538
+ addHook({
1539
+ name: 'vitest',
1540
+ versions: ['>=2.1.0 <3.0.0'],
1541
+ filePattern: 'dist/chunks/RandomSequencer.*',
1542
+ }, (randomSequencerPackage) => {
1543
+ shimmer.wrap(randomSequencerPackage.B.prototype, 'sort', getSortWrapper)
1544
+ return randomSequencerPackage
1545
+ })
1546
+
1547
+ addHook({
1548
+ name: 'vitest',
1549
+ versions: ['>=3.0.9'],
1550
+ filePattern: 'dist/chunks/coverage.*',
1551
+ }, (coveragePackage) => {
1552
+ const baseSequencer = getBaseSequencerExport(coveragePackage)
1553
+ if (baseSequencer) {
1554
+ shimmer.wrap(baseSequencer.value.prototype, 'sort', getSortWrapper)
1555
+ }
1556
+ return coveragePackage
1557
+ })
1558
+
1559
+ addHook({
1560
+ name: 'vitest',
1561
+ versions: ['>=3.0.0 <3.0.9'],
1562
+ filePattern: 'dist/chunks/resolveConfig.*',
1563
+ }, (resolveConfigPackage) => {
1564
+ shimmer.wrap(resolveConfigPackage.B.prototype, 'sort', getSortWrapper)
1565
+ return resolveConfigPackage
1566
+ })
1567
+
1568
+ // Can't specify file because compiled vitest includes hashes in their files
1569
+ // Following 3 wrappers are for test session start
1570
+ addHook({
1571
+ name: 'vitest',
1572
+ versions: ['>=1.6.0 <2.0.5'],
1573
+ filePattern: 'dist/vendor/cac.*',
1574
+ }, getCreateCliWrapper)
1575
+
1576
+ addHook({
1577
+ name: 'vitest',
1578
+ versions: ['>=2.0.5'],
1579
+ filePattern: 'dist/chunks/cac.*',
1580
+ }, getCreateCliWrapper)
1581
+
1582
+ addHook({
1583
+ name: 'vitest',
1584
+ versions: ['>=1.6.0 <2.0.5'],
1585
+ filePattern: 'dist/vendor/cli-api.*',
1586
+ }, getStartVitestWrapper)
1587
+
1588
+ addHook({
1589
+ name: 'vitest',
1590
+ versions: ['>=2.0.5'],
1591
+ filePattern: 'dist/chunks/cli-api.*',
1592
+ }, getStartVitestWrapper)