dd-trace 6.24.0 → 6.25.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 (250) hide show
  1. package/ci/init.js +2 -22
  2. package/ext/exporters.js +0 -1
  3. package/index.d.ts +105 -5
  4. package/initialize.mjs +5 -2
  5. package/lambda.d.ts +39 -0
  6. package/lambda.js +3 -0
  7. package/package.json +11 -9
  8. package/packages/datadog-esbuild/index.js +8 -55
  9. package/packages/datadog-instrumentations/src/aws-lambda.js +88 -0
  10. package/packages/datadog-instrumentations/src/cucumber.js +5 -2
  11. package/packages/datadog-instrumentations/src/elevenlabs/activity.js +114 -0
  12. package/packages/datadog-instrumentations/src/elevenlabs/audio.js +104 -0
  13. package/packages/datadog-instrumentations/src/elevenlabs/index.js +288 -0
  14. package/packages/datadog-instrumentations/src/elevenlabs/session.js +444 -0
  15. package/packages/datadog-instrumentations/src/graphql.js +20 -17
  16. package/packages/{datadog-esbuild/src/utils.js → datadog-instrumentations/src/helpers/bundler-esm-exports.js} +282 -40
  17. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +573 -0
  18. package/packages/datadog-instrumentations/src/helpers/bundler-utils.js +104 -0
  19. package/packages/datadog-instrumentations/src/helpers/hook.js +29 -1
  20. package/packages/datadog-instrumentations/src/helpers/hooks.js +3 -7
  21. package/packages/datadog-instrumentations/src/helpers/lambda-handler.js +189 -0
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +2 -0
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +18 -1
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/async-mutex.js +41 -0
  25. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/elevenlabs.js +25 -0
  26. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +0 -36
  27. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +40 -0
  28. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/openai-agents-realtime.js +23 -0
  29. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/trpc.js +148 -0
  30. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +50 -0
  31. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +17 -3
  32. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +59 -2
  33. package/packages/datadog-instrumentations/src/ioredis.js +101 -3
  34. package/packages/datadog-instrumentations/src/next.js +19 -6
  35. package/packages/datadog-instrumentations/src/openai-agents-realtime.js +149 -0
  36. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +27 -0
  37. package/packages/datadog-instrumentations/src/openai-realtime/index.js +17 -6
  38. package/packages/datadog-instrumentations/src/openai-realtime/server-playback.js +887 -0
  39. package/packages/datadog-instrumentations/src/openai-realtime/session.js +150 -25
  40. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +29 -2
  41. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +11 -9
  42. package/packages/datadog-instrumentations/src/webdriverio.js +12 -12
  43. package/packages/datadog-plugin-async-mutex/src/index.js +50 -0
  44. package/packages/datadog-plugin-aws-lambda/src/index.js +106 -0
  45. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +22 -11
  46. package/packages/datadog-plugin-elevenlabs/src/index.js +69 -0
  47. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -7
  48. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +19 -52
  49. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +4 -2
  50. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-request-context.js +25 -4
  51. package/packages/datadog-plugin-http/src/client.js +32 -9
  52. package/packages/datadog-plugin-http2/src/client.js +38 -13
  53. package/packages/datadog-plugin-next/src/index.js +112 -14
  54. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +5 -3
  55. package/packages/datadog-plugin-trpc/src/index.js +15 -0
  56. package/packages/datadog-plugin-trpc/src/procedure.js +48 -0
  57. package/packages/datadog-plugin-trpc/src/request.js +81 -0
  58. package/packages/datadog-plugin-undici/src/index.js +22 -7
  59. package/packages/datadog-turbopack/index.js +4 -28
  60. package/packages/datadog-turbopack/src/loader.js +14 -452
  61. package/packages/datadog-webpack/index.js +3 -55
  62. package/packages/dd-trace/src/aiguard/evaluation.js +62 -1
  63. package/packages/dd-trace/src/aiguard/sdk.js +8 -2
  64. package/packages/dd-trace/src/aiguard/tags.js +2 -0
  65. package/packages/dd-trace/src/appsec/blocking/index.js +4 -0
  66. package/packages/dd-trace/src/appsec/graphql.js +91 -6
  67. package/packages/dd-trace/src/appsec/recommended.json +1287 -90
  68. package/packages/dd-trace/src/before-exit.js +32 -0
  69. package/packages/dd-trace/src/bootstrap.js +5 -3
  70. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +15 -2
  71. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +12 -34
  72. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +41 -13
  73. package/packages/dd-trace/src/ci-visibility/exporters/request.js +2 -3
  74. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +1 -2
  75. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +1 -1
  76. package/packages/dd-trace/src/ci-visibility/telemetry.js +6 -0
  77. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +1 -1
  78. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +9 -134
  79. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +11 -156
  80. package/packages/dd-trace/src/config/config-types.d.ts +3 -0
  81. package/packages/dd-trace/src/config/defaults.js +5 -0
  82. package/packages/dd-trace/src/config/generated-config-types.d.ts +42 -2
  83. package/packages/dd-trace/src/config/index.js +17 -5
  84. package/packages/dd-trace/src/config/parsers.js +9 -0
  85. package/packages/dd-trace/src/config/supported-configurations.json +158 -4
  86. package/packages/dd-trace/src/constants.js +1 -0
  87. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +2 -1
  88. package/packages/dd-trace/src/exporter.js +0 -11
  89. package/packages/dd-trace/src/exporters/common/request.js +81 -48
  90. package/packages/dd-trace/src/exporters/common/retry.js +12 -7
  91. package/packages/dd-trace/src/exporters/common/url.js +1 -1
  92. package/packages/dd-trace/src/id.js +1 -1
  93. package/packages/dd-trace/src/lambda/facade.js +74 -0
  94. package/packages/dd-trace/src/lambda/handler.js +3 -41
  95. package/packages/dd-trace/src/lambda/index.js +38 -15
  96. package/packages/dd-trace/src/lambda/runtime/patch.js +19 -3
  97. package/packages/dd-trace/src/lambda/wrap.js +44 -0
  98. package/packages/dd-trace/src/llmobs/constants/tags.js +2 -0
  99. package/packages/dd-trace/src/llmobs/experiments/experiment.js +10 -5
  100. package/packages/dd-trace/src/llmobs/plugins/elevenlabs.js +96 -0
  101. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +19 -6
  102. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +38 -11
  103. package/packages/dd-trace/src/llmobs/plugins/vertexai.js +10 -2
  104. package/packages/dd-trace/src/llmobs/sdk.js +19 -0
  105. package/packages/dd-trace/src/llmobs/span_processor.js +9 -0
  106. package/packages/dd-trace/src/llmobs/tagger.js +22 -0
  107. package/packages/dd-trace/src/log/channels.js +4 -0
  108. package/packages/dd-trace/src/log/writer.js +6 -1
  109. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +4 -0
  110. package/packages/dd-trace/src/openfeature/configuration_source.js +35 -27
  111. package/packages/dd-trace/src/openfeature/flag-selection.js +152 -0
  112. package/packages/dd-trace/src/openfeature/flagging_provider.js +19 -1
  113. package/packages/dd-trace/src/openfeature/writers/base.js +1 -3
  114. package/packages/dd-trace/src/opentelemetry/logs/index.js +11 -0
  115. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +1 -1
  116. package/packages/dd-trace/src/opentelemetry/metrics/index.js +7 -1
  117. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +1 -1
  118. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +4 -1
  119. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +19 -1
  120. package/packages/dd-trace/src/opentelemetry/span-ending-hook.js +5 -1
  121. package/packages/dd-trace/src/opentelemetry/span-helpers.js +6 -1
  122. package/packages/dd-trace/src/opentelemetry/span.js +2 -2
  123. package/packages/dd-trace/src/opentelemetry/startup-config.js +174 -0
  124. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +1 -1
  125. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +7 -1
  126. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +77 -23
  127. package/packages/dd-trace/src/opentracing/tracer.js +24 -0
  128. package/packages/dd-trace/src/otel-thread-ctx.js +28 -31
  129. package/packages/dd-trace/src/plugin_manager.js +34 -7
  130. package/packages/dd-trace/src/plugins/ci_plugin.js +41 -10
  131. package/packages/dd-trace/src/plugins/index.js +6 -0
  132. package/packages/dd-trace/src/plugins/plugin.js +4 -2
  133. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  134. package/packages/dd-trace/src/plugins/util/ci.js +18 -1
  135. package/packages/dd-trace/src/plugins/util/git-cache.js +4 -4
  136. package/packages/dd-trace/src/plugins/util/git.js +263 -82
  137. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +75 -46
  138. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +12 -4
  139. package/packages/dd-trace/src/plugins/util/status-validator.js +23 -10
  140. package/packages/dd-trace/src/plugins/util/tags.js +6 -0
  141. package/packages/dd-trace/src/plugins/util/test.js +64 -39
  142. package/packages/dd-trace/src/plugins/util/url.js +10 -2
  143. package/packages/dd-trace/src/plugins/util/user-provided-git.js +2 -2
  144. package/packages/dd-trace/src/plugins/util/web.js +65 -10
  145. package/packages/dd-trace/src/profiling/webspan-utils.js +6 -5
  146. package/packages/dd-trace/src/proxy.js +33 -53
  147. package/packages/dd-trace/src/span_processor.js +20 -0
  148. package/packages/dd-trace/src/startup-log.js +8 -6
  149. package/packages/dd-trace/src/telemetry/metrics.js +2 -1
  150. package/packages/dd-trace/src/tracer.js +0 -2
  151. package/packages/dd-trace/src/web-tags-cache.js +8 -9
  152. package/register.js +2 -1
  153. package/vendor/dist/@apm-js-collab/code-transformer/LICENSE +489 -0
  154. package/vendor/dist/@datadog/flagging-core/LICENSE +221 -0
  155. package/vendor/dist/@datadog/flagging-core/index.js +1 -0
  156. package/vendor/dist/@datadog/openfeature-node-server/LICENSE +21 -1
  157. package/vendor/dist/@datadog/openfeature-node-server/rules-based/LICENSE +3 -1
  158. package/vendor/dist/@datadog/sketches-js/LICENSE +263 -0
  159. package/vendor/dist/@datadog/source-map/LICENSE +1 -0
  160. package/vendor/dist/@isaacs/ttlcache/LICENSE +13 -0
  161. package/vendor/dist/@opentelemetry/core/LICENSE +209 -1
  162. package/vendor/dist/crypto-randomuuid/LICENSE +3 -0
  163. package/vendor/dist/escape-string-regexp/LICENSE +13 -0
  164. package/vendor/dist/esquery/LICENSE +2 -0
  165. package/vendor/dist/https-proxy-agent/LICENSE +80 -1
  166. package/vendor/dist/istanbul-lib-coverage/LICENSE +2 -0
  167. package/vendor/dist/jest-docblock/LICENSE +16 -0
  168. package/vendor/dist/jsonpath-plus/LICENSE +13 -0
  169. package/vendor/dist/limiter/LICENSE +2 -0
  170. package/vendor/dist/lodash.sortby/LICENSE +2 -0
  171. package/vendor/dist/lru-cache/LICENSE +13 -0
  172. package/vendor/dist/meriyah/LICENSE +13 -0
  173. package/vendor/dist/module-details-from-path/LICENSE +2 -0
  174. package/vendor/dist/mutexify/promise/LICENSE +28 -0
  175. package/vendor/dist/pprof-format/LICENSE +13 -0
  176. package/vendor/dist/pprof-format/index.js +1 -1
  177. package/vendor/dist/protobufjs/LICENSE +219 -0
  178. package/vendor/dist/protobufjs/minimal/LICENSE +219 -0
  179. package/vendor/dist/proxy-from-env/LICENSE +13 -0
  180. package/vendor/dist/retry/LICENSE +2 -0
  181. package/vendor/dist/rfdc/LICENSE +2 -0
  182. package/vendor/dist/semifies/LICENSE +3 -1
  183. package/vendor/dist/shell-quote/LICENSE +3 -1
  184. package/vendor/dist/source-map/LICENSE +1 -0
  185. package/vendor/dist/source-map/lib/util/LICENSE +1 -0
  186. package/vendor/dist/tlhunter-sorted-set/LICENSE +2 -0
  187. package/vendor/dist/ttl-set/LICENSE +28 -0
  188. package/ci/diagnose.js +0 -2215
  189. package/ci/runbook.md +0 -299
  190. package/ci/test-optimization-validation/approval-artifacts.js +0 -175
  191. package/ci/test-optimization-validation/approval.js +0 -386
  192. package/ci/test-optimization-validation/artifact-id.js +0 -18
  193. package/ci/test-optimization-validation/blocker-category.js +0 -24
  194. package/ci/test-optimization-validation/bounded-json.js +0 -120
  195. package/ci/test-optimization-validation/ci-command-candidate.js +0 -77
  196. package/ci/test-optimization-validation/ci-discovery.js +0 -192
  197. package/ci/test-optimization-validation/ci-package-scripts.js +0 -169
  198. package/ci/test-optimization-validation/ci-remediation.js +0 -283
  199. package/ci/test-optimization-validation/cli.js +0 -954
  200. package/ci/test-optimization-validation/command-blocker.js +0 -377
  201. package/ci/test-optimization-validation/command-output-policy.js +0 -188
  202. package/ci/test-optimization-validation/command-runner.js +0 -649
  203. package/ci/test-optimization-validation/environment.js +0 -88
  204. package/ci/test-optimization-validation/executable-approval.js +0 -47
  205. package/ci/test-optimization-validation/executable.js +0 -244
  206. package/ci/test-optimization-validation/execution-lock.js +0 -70
  207. package/ci/test-optimization-validation/framework-adapters/cucumber-validation.json +0 -3
  208. package/ci/test-optimization-validation/framework-adapters/cucumber.js +0 -767
  209. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -99
  210. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -175
  211. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -513
  212. package/ci/test-optimization-validation/generated-file-policy.js +0 -63
  213. package/ci/test-optimization-validation/generated-files.js +0 -425
  214. package/ci/test-optimization-validation/generated-test-contract.js +0 -284
  215. package/ci/test-optimization-validation/generated-verifier.js +0 -235
  216. package/ci/test-optimization-validation/literal-environment.js +0 -56
  217. package/ci/test-optimization-validation/literal-glob.js +0 -52
  218. package/ci/test-optimization-validation/manifest-loader.js +0 -116
  219. package/ci/test-optimization-validation/manifest-scaffold.js +0 -1276
  220. package/ci/test-optimization-validation/manifest-schema.js +0 -695
  221. package/ci/test-optimization-validation/offline-fixtures.js +0 -335
  222. package/ci/test-optimization-validation/offline-output.js +0 -406
  223. package/ci/test-optimization-validation/package-check.js +0 -97
  224. package/ci/test-optimization-validation/payload-normalizer.js +0 -72
  225. package/ci/test-optimization-validation/plan-writer.js +0 -541
  226. package/ci/test-optimization-validation/preflight-runner.js +0 -186
  227. package/ci/test-optimization-validation/project-build-artifact.js +0 -31
  228. package/ci/test-optimization-validation/redaction.js +0 -319
  229. package/ci/test-optimization-validation/report-writer.js +0 -666
  230. package/ci/test-optimization-validation/result-semantics.js +0 -103
  231. package/ci/test-optimization-validation/runner-command.js +0 -264
  232. package/ci/test-optimization-validation/runner-contract.js +0 -695
  233. package/ci/test-optimization-validation/safe-files.js +0 -202
  234. package/ci/test-optimization-validation/scenarios/auto-test-retries.js +0 -171
  235. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -407
  236. package/ci/test-optimization-validation/scenarios/ci-wiring.js +0 -666
  237. package/ci/test-optimization-validation/scenarios/early-flake-detection.js +0 -142
  238. package/ci/test-optimization-validation/scenarios/helpers.js +0 -621
  239. package/ci/test-optimization-validation/scenarios/test-management.js +0 -219
  240. package/ci/test-optimization-validation/source-text.js +0 -84
  241. package/ci/test-optimization-validation/static-diagnosis.js +0 -166
  242. package/ci/test-optimization-validation/test-output.js +0 -120
  243. package/ci/test-optimization-validation/validation-blocker.js +0 -21
  244. package/ci/validate-test-optimization.js +0 -3
  245. package/packages/datadog-esbuild/src/resolver.js +0 -284
  246. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -156
  247. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -287
  248. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/payload-projection.js +0 -84
  249. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -368
  250. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/writer.js +0 -59
package/ci/diagnose.js DELETED
@@ -1,2215 +0,0 @@
1
- 'use strict'
2
-
3
- /* eslint-disable eslint-rules/eslint-process-env */
4
-
5
- const fs = require('node:fs')
6
- const path = require('node:path')
7
- const { execFileSync } = require('node:child_process')
8
-
9
- const satisfies = require('../vendor/dist/semifies')
10
- const { DD_MAJOR, VERSION } = require('../version')
11
-
12
- const MAX_TEXT_FILE_SIZE = 512 * 1024
13
- const MAX_SCANNED_FILES = 1500
14
- const MAX_SCANNED_TEXT_BYTES = 32 * 1024 * 1024
15
-
16
- const PACKAGE_SECTIONS = [
17
- 'dependencies',
18
- 'devDependencies',
19
- 'optionalDependencies',
20
- 'peerDependencies',
21
- ]
22
-
23
- const SKIPPED_DIRECTORIES = new Set([
24
- '.cache',
25
- '.git',
26
- '.hg',
27
- '.next',
28
- '.nuxt',
29
- '.output',
30
- '.parcel-cache',
31
- '.serverless',
32
- '.svn',
33
- '.turbo',
34
- '.yarn',
35
- 'build',
36
- 'coverage',
37
- 'dd-test-optimization-validation-results',
38
- 'dist',
39
- 'node_modules',
40
- 'out',
41
- 'target',
42
- 'tmp',
43
- 'vendor',
44
- ])
45
-
46
- const SKIPPED_FILES = new Set([
47
- 'ci/diagnose.js',
48
- ])
49
-
50
- const TEXT_EXTENSIONS = new Set([
51
- '.cjs',
52
- '.cts',
53
- '.js',
54
- '.json',
55
- '.mjs',
56
- '.mts',
57
- '.sh',
58
- '.ts',
59
- '.tsx',
60
- '.yaml',
61
- '.yml',
62
- ])
63
-
64
- const TEXT_FILE_NAMES = new Set([
65
- 'Dockerfile',
66
- 'Jenkinsfile',
67
- 'Makefile',
68
- 'docker-compose.yml',
69
- 'docker-compose.yaml',
70
- 'package.json',
71
- ])
72
-
73
- const NODE_OPTIONS_RE = /\bNODE_OPTIONS\b/
74
- const INIT_PRELOAD_TARGET =
75
- String.raw`(?:dd-trace/ci/init|(?:[^\s'"]*[/\\])?node_modules[/\\]dd-trace[/\\]ci[/\\]init|\./ci/init)`
76
- const INIT_PRELOAD_RE =
77
- new RegExp(String.raw`(?:^|[\s='"])(?:-r|--require)(?:=|\s+)['"]?${INIT_PRELOAD_TARGET}(?:\.js)?['"]?(?=$|[\s"'])`)
78
- const REGISTER_PRELOAD_RE =
79
- /(?:^|[\s='"])(?:--import|-r|--require)(?:=|\s+)['"]?dd-trace\/register(?:\.js)?['"]?(?=$|[\s"'])/
80
- const WRONG_INIT_RE = /dd-trace\/(?:init|initialize\.mjs)\b|require\(['"]dd-trace['"]\)\.init\s*\(/
81
- const DIRECT_CI_INIT_RE = /(?:require\(|import\s+)['"]dd-trace\/ci\/init(?:\.js)?['"]/
82
- const CI_DISABLED_RE = /DD_CIVISIBILITY_ENABLED["'\s:=]+(?:false|0)\b/i
83
- const ITR_DISABLED_RE = /DD_CIVISIBILITY_ITR_ENABLED["'\s:=]+(?:false|0)\b/i
84
- const GIT_UPLOAD_DISABLED_RE = /DD_CIVISIBILITY_GIT_UPLOAD_ENABLED["'\s:=]+(?:false|0)\b/i
85
- const AGENTLESS_ENABLED_RE = /DD_CIVISIBILITY_AGENTLESS_ENABLED["'\s:=]+(?:true|1)\b/i
86
- const API_KEY_RE = /\b(?:DD_API_KEY|DATADOG_API_KEY)\b/
87
- const SERVICE_RE = /\bDD_SERVICE\b/
88
- const OTEL_OTLP_RE = /OTEL_TRACES_EXPORTER["'\s:=]+otlp\b/i
89
- const WATCH_MODE_RE = /(?:^|\s)(?:watch|--watch|--watchAll)(?!=false(?:\s|$))(?:\s|=|$)/
90
-
91
- const CYPRESS_MANUAL_PLUGIN_RE = /dd-trace\/ci\/cypress\/(?:plugin|after-run|after-spec)\b/
92
- const CYPRESS_SUPPORT_RE = /dd-trace\/ci\/cypress\/support\b/
93
- const CYPRESS_SUPPORT_DISABLED_RE = /supportFile\s*:\s*false|"supportFile"\s*:\s*false/
94
- const CUCUMBER_RUNNER_COMMAND_RE = new RegExp(
95
- String.raw`(?:^|(?:&&|\|\||[;|])\s*)` +
96
- String.raw`(?:(?:[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|[^\s"';&|][^\s;&|]*)|` +
97
- String.raw`cross-env|env|npx|nyc|c8|npm\s+exec|pnpm\s+exec|yarn\s+exec|-[^\s;&|]+)\s+)*` +
98
- String.raw`(?:(?:[^\s"';&|]+[/\\])?(?:cucumber-js(?:\.cmd)?|cucumber(?:\.cmd)?)|` +
99
- String.raw`node(?:\.exe)?\s+(?:[^\s"';&|]+[/\\])?bin[/\\]cucumber\.js)` +
100
- String.raw`(?=$|[\s"';&|])`
101
- )
102
- const CUCUMBER_PARALLEL_RE =
103
- /\bcucumber(?:-js)?\b[\s\S]{0,200}\s--parallel\b|--parallel\b[\s\S]{1,200}\bcucumber(?:-js)?\b/
104
- const JEST_FORCE_EXIT_RE = /\bforceExit\s*:\s*true\b|--forceExit\b|"forceExit"\s*:\s*true/
105
- const JEST_JASMINE_RE = /jest-jasmine2/
106
-
107
- const CURRENT_ENV_PROVIDER_KEYS = [
108
- 'GITHUB_ACTIONS',
109
- 'GITLAB_CI',
110
- 'CIRCLECI',
111
- 'JENKINS_URL',
112
- 'BUILDKITE',
113
- 'TRAVIS',
114
- 'TF_BUILD',
115
- 'BITBUCKET_BUILD_NUMBER',
116
- 'DRONE',
117
- 'TEAMCITY_VERSION',
118
- ]
119
-
120
- /**
121
- * Builds the framework support table for the tracer major version that is running this script.
122
- *
123
- * @param {number} ddMajor dd-trace major version
124
- * @returns {Array<object>} supported framework definitions
125
- */
126
- function getFrameworkDefinitions (ddMajor) {
127
- return [
128
- {
129
- id: 'jest',
130
- name: 'Jest',
131
- packages: ['jest', '@jest/core'],
132
- commandPatterns: [/\bjest\b/],
133
- configPatterns: [/^jest\.config\./, /^config-jest\./],
134
- supportedRange: ddMajor >= 6 ? '>=28.0.0' : '>=24.8.0',
135
- recommendation: 'Use a Jest and dd-trace combination whose documented support ranges overlap; this ' +
136
- `dd-trace version requires Jest ${ddMajor >= 6 ? '>=28.0.0' : '>=24.8.0'}.`,
137
- },
138
- {
139
- id: 'mocha',
140
- name: 'Mocha',
141
- packages: ['mocha'],
142
- commandPatterns: [/\bmocha\b/],
143
- configPatterns: [/^\.mocharc\./],
144
- supportedRange: ddMajor >= 6 ? '>=8.0.0' : '>=5.2.0',
145
- recommendation: 'Use a Mocha and dd-trace combination whose documented support ranges overlap; this ' +
146
- `dd-trace version requires Mocha ${ddMajor >= 6 ? '>=8.0.0' : '>=5.2.0'}.`,
147
- notes: [
148
- 'Impacted tests are detected at suite level for Mocha.',
149
- ],
150
- },
151
- {
152
- id: 'cucumber',
153
- name: 'Cucumber',
154
- packages: ['@cucumber/cucumber'],
155
- commandPatterns: [CUCUMBER_RUNNER_COMMAND_RE],
156
- configPatterns: [/^cucumber\./],
157
- supportedRange: '>=7.0.0',
158
- recommendation: 'Upgrade @cucumber/cucumber to >=7.0.0.',
159
- },
160
- {
161
- id: 'cypress',
162
- name: 'Cypress',
163
- packages: ['cypress'],
164
- commandPatterns: [/\bcypress\s+(?:run|open)\b/],
165
- configPatterns: [/^cypress\.config\./, /^cypress\.json$/],
166
- supportedRange: ddMajor >= 6 ? '>=12.0.0' : '>=6.7.0',
167
- autoInstrumentationRange: ddMajor >= 6 ? '>=12.0.0' : '>=10.2.0',
168
- recommendation: 'Use a Cypress and dd-trace combination whose documented support ranges overlap; this ' +
169
- `dd-trace version requires Cypress ${ddMajor >= 6 ? '>=12.0.0' : '>=6.7.0'}.`,
170
- },
171
- {
172
- id: 'playwright',
173
- name: 'Playwright',
174
- packages: ['@playwright/test'],
175
- commandPatterns: [/\bplaywright\s+test\b/],
176
- configPatterns: [/^playwright\.config\./],
177
- supportedRange: ddMajor >= 6 ? '>=1.38.0' : '>=1.18.0',
178
- recommendation: 'Use a Playwright and dd-trace combination whose documented support ranges overlap; this ' +
179
- `dd-trace version requires Playwright ${ddMajor >= 6 ? '>=1.38.0' : '>=1.18.0'}.`,
180
- notes: [
181
- 'Test Impact Analysis suite skipping is not supported for Playwright.',
182
- 'Impacted tests are detected at suite level for Playwright.',
183
- ],
184
- },
185
- {
186
- id: 'vitest',
187
- name: 'Vitest',
188
- packages: ['vitest'],
189
- commandPatterns: [/\bvitest\b/],
190
- configPatterns: [/^vitest\.config\./, /^vite\.config\./],
191
- supportedRange: '>=1.6.0',
192
- recommendation: 'Upgrade Vitest to >=1.6.0.',
193
- notes: [
194
- 'Test Impact Analysis suite skipping is not supported for Vitest.',
195
- 'Impacted tests are detected at suite level for Vitest.',
196
- ],
197
- esmInitialization: true,
198
- },
199
- ]
200
- }
201
-
202
- const UNSUPPORTED_FRAMEWORKS = [
203
- {
204
- id: 'node-test',
205
- name: 'Node.js test runner',
206
- packages: [],
207
- commandPatterns: [/\bnode\s+--test\b/, /\bnode\s+--experimental-test-coverage\b/, /\bbnt\b/],
208
- },
209
- { id: 'ava', name: 'AVA', packages: ['ava'], commandPatterns: [/\bava\b/] },
210
- { id: 'tap', name: 'tap', packages: ['tap'], commandPatterns: [/\btap\b/] },
211
- { id: 'jasmine', name: 'Jasmine', packages: ['jasmine'], commandPatterns: [/\bjasmine\b/] },
212
- { id: 'karma', name: 'Karma', packages: ['karma'], commandPatterns: [/\bkarma\b/] },
213
- { id: 'uvu', name: 'uvu', packages: ['uvu'], commandPatterns: [/\buvu\b/] },
214
- {
215
- id: 'testcafe',
216
- name: 'TestCafe',
217
- packages: ['testcafe'],
218
- commandPatterns: [/\btestcafe\b/],
219
- },
220
- ]
221
-
222
- /**
223
- * Runs all static checks for a repository.
224
- *
225
- * @param {object} [options] diagnosis options
226
- * @param {string} [options.root] repository path to inspect
227
- * @param {typeof process.env} [options.env] environment to inspect
228
- * @param {Function} [options.execFile] command runner used for git checks
229
- * @param {string} [options.gitExecutable] trusted git executable used for git checks
230
- * @param {number} [options.maxFiles] maximum number of text files to scan
231
- * @param {number} [options.maxTotalBytes] maximum aggregate bytes of text files to scan
232
- * @param {string[]} [options.excludePaths] repository paths to exclude from the text scan
233
- * @returns {object} diagnosis report
234
- */
235
- function runDiagnosis (options = {}) {
236
- const root = path.resolve(options.root || process.cwd())
237
- const physicalRoot = getPhysicalRoot(root)
238
- const env = options.env || process.env
239
- const execFile = options.execFile || execFileSync
240
- const maxFiles = options.maxFiles || MAX_SCANNED_FILES
241
- const maxTotalBytes = options.maxTotalBytes || MAX_SCANNED_TEXT_BYTES
242
- const results = []
243
- const files = collectTextFiles(root, physicalRoot, maxFiles, options.excludePaths)
244
- const textFiles = readTextFiles(root, physicalRoot, files, maxTotalBytes)
245
- const truncatedFileScan = files.truncated || textFiles.truncated
246
- const manifests = readPackageManifests(root, textFiles)
247
- const rootManifest = manifests.find(manifest => manifest.relativePath === 'package.json')
248
- const rootPackageJsonState = getRootPackageJsonState(root, physicalRoot)
249
- const scripts = collectScripts(manifests)
250
- const workflowFiles = textFiles.filter(file => isWorkflowFile(file.relativePath))
251
- const definitions = getFrameworkDefinitions(DD_MAJOR)
252
- const supportedFrameworks = detectSupportedFrameworks(root, definitions, manifests, scripts, textFiles)
253
- const eligibleFrameworks = getEligibleFrameworks(supportedFrameworks)
254
- const unsupportedFrameworks = detectUnsupportedFrameworks(UNSUPPORTED_FRAMEWORKS, manifests, scripts)
255
- const evidence = collectEvidence(textFiles, env)
256
-
257
- checkPackageManifest(results, rootManifest, rootPackageJsonState)
258
- checkDdTraceDependency(results, manifests, { root, truncatedFileScan, rootPackageJsonState })
259
- checkSupportedFrameworks(results, supportedFrameworks)
260
- checkUnsupportedFrameworks(results, unsupportedFrameworks, supportedFrameworks)
261
- checkInitialization(results, supportedFrameworks, evidence, env)
262
- checkFrameworkConfiguration(results, supportedFrameworks, evidence, textFiles, manifests)
263
- checkCiConfiguration(results, workflowFiles, evidence, env)
264
- const gitExecutable = options.gitExecutable || (options.execFile ? 'git' : findTrustedGitExecutable())
265
- checkGit(results, root, env, execFile, gitExecutable)
266
- checkCurrentEnvironment(results, env, evidence)
267
-
268
- return {
269
- root,
270
- ddTraceVersion: VERSION,
271
- ddTraceMajor: DD_MAJOR,
272
- scannedFileCount: textFiles.length,
273
- truncatedFileScan,
274
- supportedFrameworks: supportedFrameworks.map(serializeSupportedFramework),
275
- eligibleFrameworks: eligibleFrameworks.map(serializeEligibleFramework),
276
- unsupportedFrameworks: unsupportedFrameworks.map(serializeUnsupportedFramework),
277
- results,
278
- }
279
- }
280
-
281
- /**
282
- * Adds a normalized result to the list.
283
- *
284
- * @param {Array<object>} results mutable result list
285
- * @param {string} status result status
286
- * @param {string} title short title
287
- * @param {string} message result details
288
- * @param {object} [extra] optional fields
289
- */
290
- function addResult (results, status, title, message, extra = {}) {
291
- results.push({
292
- status,
293
- title,
294
- message,
295
- ...extra,
296
- })
297
- }
298
-
299
- /**
300
- * Reads package.json files collected by the repository scan.
301
- *
302
- * @param {string} root repository root
303
- * @param {Array<object>} textFiles scanned text files
304
- * @returns {Array<object>} parsed package manifests
305
- */
306
- function readPackageManifests (root, textFiles) {
307
- const manifests = []
308
-
309
- for (const file of textFiles) {
310
- if (path.basename(file.relativePath) !== 'package.json') continue
311
-
312
- const json = parseJson(file.content)
313
- if (!json) continue
314
-
315
- manifests.push({
316
- path: path.join(root, file.relativePath),
317
- relativePath: file.relativePath,
318
- json,
319
- })
320
- }
321
-
322
- return manifests
323
- }
324
-
325
- /**
326
- * Checks whether the repository root has a package.json independently from the text-file scan.
327
- *
328
- * @param {string} root repository root
329
- * @param {string|undefined} physicalRoot physical repository root
330
- * @returns {{ exists: boolean }} root package.json state
331
- */
332
- function getRootPackageJsonState (root, physicalRoot) {
333
- return {
334
- exists: Boolean(getSafeScannedFile(root, physicalRoot, 'package.json')),
335
- }
336
- }
337
-
338
- /**
339
- * Checks that a root package.json exists.
340
- *
341
- * @param {Array<object>} results mutable result list
342
- * @param {object|undefined} rootManifest parsed root package manifest
343
- * @param {object} rootPackageJsonState root package.json filesystem state
344
- */
345
- function checkPackageManifest (results, rootManifest, rootPackageJsonState) {
346
- if (rootManifest) {
347
- addResult(results, 'ok', 'Root package.json found', 'Dependency and script checks can inspect package metadata.')
348
- return
349
- }
350
-
351
- if (rootPackageJsonState.exists) {
352
- addResult(
353
- results,
354
- 'warning',
355
- 'Root package.json not determined',
356
- 'A root package.json file exists, but static diagnosis could not parse it as scanned text.',
357
- {
358
- recommendation:
359
- 'Check whether package.json is readable UTF-8 JSON and smaller than the static diagnosis file limit.',
360
- }
361
- )
362
- return
363
- }
364
-
365
- addResult(
366
- results,
367
- 'warning',
368
- 'No root package.json found',
369
- 'The diagnosis could not inspect root dependencies or package scripts.',
370
- { recommendation: 'Run this script from the JavaScript repository root, or pass --path <repository>.' }
371
- )
372
- }
373
-
374
- /**
375
- * Checks whether dd-trace is declared in repository manifests.
376
- *
377
- * @param {Array<object>} results mutable result list
378
- * @param {Array<object>} manifests package manifests
379
- * @param {object} options dependency check options
380
- * @param {string} [options.root] repository root
381
- * @param {boolean} [options.truncatedFileScan] whether static file discovery was truncated
382
- * @param {object} [options.rootPackageJsonState] root package manifest state
383
- */
384
- function checkDdTraceDependency (results, manifests, options = {}) {
385
- const entries = findDependencyEntries(manifests, ['dd-trace'])
386
-
387
- if (entries.length) {
388
- addResult(
389
- results,
390
- 'ok',
391
- 'dd-trace dependency found',
392
- `Detected dd-trace in ${formatLocations(entries.map(entry => entry.relativePath))}.`
393
- )
394
- return
395
- }
396
-
397
- const installedPackageJson = options.root && path.join(options.root, 'node_modules', 'dd-trace', 'package.json')
398
- let installed = false
399
- try {
400
- installed = installedPackageJson && fs.statSync(installedPackageJson).isFile()
401
- } catch {}
402
- if (installed) {
403
- addResult(
404
- results,
405
- 'ok',
406
- 'dd-trace package installed',
407
- 'Detected an installed dd-trace package even though it was not declared in the scanned package manifests.'
408
- )
409
- return
410
- }
411
-
412
- if (options.truncatedFileScan || (options.rootPackageJsonState?.exists && !hasParsedRootManifest(manifests))) {
413
- addResult(
414
- results,
415
- 'warning',
416
- 'dd-trace dependency not determined',
417
- 'Static diagnosis did not confirm a dd-trace dependency, but the file scan was incomplete or root package ' +
418
- 'metadata could not be parsed.',
419
- { recommendation: 'Inspect the package that runs tests and install dd-trace there if it is absent.' }
420
- )
421
- return
422
- }
423
-
424
- addResult(
425
- results,
426
- 'warning',
427
- 'dd-trace dependency not found in package.json',
428
- 'The script did not find dd-trace in dependencies or devDependencies.',
429
- { recommendation: 'Install dd-trace in the project that runs the tests.' }
430
- )
431
- }
432
-
433
- /**
434
- * Checks whether static diagnosis parsed the repository root package manifest.
435
- *
436
- * @param {Array<object>} manifests parsed package manifests
437
- */
438
- function hasParsedRootManifest (manifests) {
439
- return manifests.some(manifest => manifest.relativePath === 'package.json')
440
- }
441
-
442
- /**
443
- * Checks supported framework detections and versions.
444
- *
445
- * @param {Array<object>} results mutable result list
446
- * @param {Array<object>} frameworks detected supported frameworks
447
- */
448
- function checkSupportedFrameworks (results, frameworks) {
449
- if (!frameworks.length) {
450
- addResult(
451
- results,
452
- 'warning',
453
- 'No supported test framework detected',
454
- 'No supported Test Optimization framework was found in dependencies, scripts, or config files.',
455
- {
456
- recommendation:
457
- 'Use Jest, Mocha, Cucumber, Cypress, Playwright, or Vitest with a supported version.',
458
- }
459
- )
460
- return
461
- }
462
-
463
- for (const framework of frameworks) {
464
- if (!framework.versionDetections.length) {
465
- addResult(
466
- results,
467
- 'warning',
468
- `${framework.name} detected but version is unknown`,
469
- `${framework.name} appears in scripts or config, but no package version could be determined.`,
470
- {
471
- locations: framework.locations,
472
- recommendation:
473
- `Ensure ${framework.packages.join(' or ')} is installed and matches ${framework.supportedRange}.`,
474
- }
475
- )
476
- }
477
-
478
- for (const detection of framework.versionDetections) {
479
- if (!detection.version) {
480
- addResult(
481
- results,
482
- 'warning',
483
- `${framework.name} version could not be determined`,
484
- `Detected ${detection.packageName}@${detection.rawVersion}, but the version is not statically comparable.`,
485
- {
486
- locations: [detection.relativePath],
487
- recommendation: `Verify ${framework.name} satisfies ${framework.supportedRange}.`,
488
- }
489
- )
490
- continue
491
- }
492
-
493
- const status = satisfies(detection.version, framework.supportedRange) ? 'ok' : 'error'
494
- const source = detection.source === 'installed' ? 'installed package' : 'package manifest'
495
- addResult(
496
- results,
497
- status,
498
- `${framework.name} ${detection.version} ${status === 'ok' ? 'is supported' : 'is not supported'}`,
499
- `Detected ${detection.packageName}@${detection.rawVersion} from ${source}; supported range is ` +
500
- `${framework.supportedRange}.`,
501
- {
502
- locations: detection.relativePath ? [detection.relativePath] : undefined,
503
- recommendation: status === 'error' ? framework.recommendation : undefined,
504
- }
505
- )
506
- }
507
-
508
- if (framework.notes) {
509
- for (const note of framework.notes) {
510
- addResult(results, 'info', `${framework.name} capability note`, note)
511
- }
512
- }
513
- }
514
- }
515
-
516
- /**
517
- * Checks unsupported framework detections.
518
- *
519
- * @param {Array<object>} results mutable result list
520
- * @param {Array<object>} unsupported detected unsupported frameworks
521
- * @param {Array<object>} supported detected supported frameworks
522
- */
523
- function checkUnsupportedFrameworks (results, unsupported, supported) {
524
- for (const framework of unsupported) {
525
- const status = supported.length ? 'warning' : 'error'
526
- addResult(
527
- results,
528
- status,
529
- `${framework.name} is not supported by Test Optimization`,
530
- `${framework.name} was detected in dependencies or test scripts.`,
531
- {
532
- locations: framework.locations,
533
- recommendation:
534
- 'Use a supported JavaScript test framework for automatic Test Optimization instrumentation.',
535
- }
536
- )
537
- }
538
- }
539
-
540
- /**
541
- * Checks Test Optimization initialization.
542
- *
543
- * @param {Array<object>} results mutable result list
544
- * @param {Array<object>} frameworks detected supported frameworks
545
- * @param {object} evidence repository evidence
546
- * @param {typeof process.env} env environment
547
- */
548
- function checkInitialization (results, frameworks, evidence, env) {
549
- if (!frameworks.length) return
550
-
551
- const hasCiInit = evidence.hasCiInit || hasCiInitInNodeOptions(env.NODE_OPTIONS)
552
- const hasCypressOnly = frameworks.length === 1 && frameworks[0].id === 'cypress'
553
- const hasCypressManualPlugin = evidence.cypressManualPluginLocations.length > 0
554
-
555
- if (hasCiInit) {
556
- addResult(
557
- results,
558
- 'ok',
559
- 'Test Optimization initialization found',
560
- 'Found dd-trace/ci/init preloaded through NODE_OPTIONS in repository files or the current environment.',
561
- { locations: evidence.ciInitLocations }
562
- )
563
- } else if (hasCypressOnly && hasCypressManualPlugin) {
564
- addResult(
565
- results,
566
- 'ok',
567
- 'Cypress manual plugin initialization found',
568
- 'Found the Cypress-specific dd-trace Test Optimization plugin setup.',
569
- { locations: evidence.cypressManualPluginLocations }
570
- )
571
- } else {
572
- addResult(
573
- results,
574
- 'error',
575
- 'Missing Test Optimization initialization',
576
- 'No NODE_OPTIONS preload for dd-trace/ci/init was found in repository files or the current environment.',
577
- {
578
- recommendation:
579
- 'Run tests with NODE_OPTIONS="-r dd-trace/ci/init". For ESM test runners, also include ' +
580
- '--import dd-trace/register.js.',
581
- }
582
- )
583
- }
584
-
585
- if (evidence.directCiInitLocations.length) {
586
- addResult(
587
- results,
588
- 'error',
589
- 'Test Optimization initialization is imported directly',
590
- 'The diagnosis found require("dd-trace/ci/init") or import "dd-trace/ci/init". ' +
591
- 'That does not preload the tracer early enough for Test Optimization setup.',
592
- {
593
- locations: evidence.directCiInitLocations,
594
- recommendation: 'Set NODE_OPTIONS="-r dd-trace/ci/init" on the test process instead.',
595
- }
596
- )
597
- }
598
-
599
- if (evidence.wrongInitLocations.length) {
600
- addResult(
601
- results,
602
- 'error',
603
- 'Plain dd-trace initialization found in test setup',
604
- 'The diagnosis found dd-trace/init, dd-trace/initialize.mjs, or require("dd-trace").init(). ' +
605
- 'That does not initialize the tracer in Test Optimization mode.',
606
- {
607
- locations: evidence.wrongInitLocations,
608
- recommendation: 'Use dd-trace/ci/init for test commands instead of the plain tracing initializer.',
609
- }
610
- )
611
- }
612
-
613
- if (frameworks.some(framework => framework.esmInitialization) && hasCiInit && !evidence.hasRegister &&
614
- !hasRegisterInNodeOptions(env.NODE_OPTIONS)) {
615
- addResult(
616
- results,
617
- 'warning',
618
- 'ESM loader registration not found',
619
- 'Vitest and other ESM-heavy test runners often need dd-trace/register.js before dd-trace/ci/init.',
620
- {
621
- recommendation:
622
- 'Use NODE_OPTIONS="--import dd-trace/register.js -r dd-trace/ci/init" for ESM test runs.',
623
- }
624
- )
625
- }
626
- }
627
-
628
- /**
629
- * Checks framework-specific configuration pitfalls.
630
- *
631
- * @param {Array<object>} results mutable result list
632
- * @param {Array<object>} frameworks detected supported frameworks
633
- * @param {object} evidence repository evidence
634
- * @param {Array<object>} textFiles scanned text files
635
- * @param {Array<object>} manifests package manifests
636
- */
637
- function checkFrameworkConfiguration (results, frameworks, evidence, textFiles, manifests) {
638
- if (hasFramework(frameworks, 'vitest') && !hasFramework(frameworks, 'playwright') &&
639
- findDependencyEntries(manifests, ['playwright']).length > 0) {
640
- addResult(
641
- results,
642
- 'info',
643
- 'Playwright package is not a Playwright Test runner',
644
- 'The repository uses Vitest and has the playwright package, but no @playwright/test runner was detected. ' +
645
- 'Treat Playwright as Vitest browser-provider infrastructure, not as another test framework.',
646
- {}
647
- )
648
- }
649
-
650
- if (hasFramework(frameworks, 'cypress')) {
651
- checkCypressConfiguration(results, evidence)
652
- }
653
-
654
- if (hasFramework(frameworks, 'jest')) {
655
- const jestLocations = findLocations(textFiles, JEST_FORCE_EXIT_RE)
656
- if (jestLocations.length) {
657
- addResult(
658
- results,
659
- 'warning',
660
- 'Jest forceExit can drop Test Optimization data',
661
- 'Jest\'s forceExit option can terminate before dd-trace flushes all test data.',
662
- {
663
- locations: jestLocations,
664
- recommendation: 'Remove --forceExit or forceExit: true from Jest configuration when possible.',
665
- }
666
- )
667
- }
668
-
669
- const jasmineLocations = findLocations(textFiles, JEST_JASMINE_RE)
670
- if (jasmineLocations.length) {
671
- addResult(
672
- results,
673
- 'info',
674
- 'Jest is configured with jest-jasmine2',
675
- 'dd-trace can avoid crashing with jest-jasmine2, but jest-circus is the better-supported runner.',
676
- {
677
- locations: jasmineLocations,
678
- recommendation: 'Prefer the default jest-circus runner on supported Jest versions.',
679
- }
680
- )
681
- }
682
-
683
- const tsConfigLocations = findJestTypescriptConfigLocations(textFiles)
684
- const hasTsNode = findDependencyEntries(manifests, ['ts-node']).length > 0
685
- if (tsConfigLocations.length && !hasTsNode) {
686
- addResult(
687
- results,
688
- 'warning',
689
- 'Jest TypeScript config may need ts-node',
690
- 'Jest loads TypeScript configuration files before test transforms. Without ts-node or an equivalent ' +
691
- 'precompiled config, the selected command can fail before collecting tests.',
692
- {
693
- locations: tsConfigLocations,
694
- recommendation:
695
- 'Install ts-node for the diagnostic run, or use a temporary JSON/CommonJS Jest config generated ' +
696
- 'from the repository config.',
697
- }
698
- )
699
- }
700
- }
701
-
702
- if (hasFramework(frameworks, 'cucumber')) {
703
- const cucumber = frameworks.find(framework => framework.id === 'cucumber')
704
- const parallelLocations = findLocations(textFiles, CUCUMBER_PARALLEL_RE)
705
- const hasOldParallel = cucumber.versionDetections.some(detection =>
706
- detection.version && !satisfies(detection.version, '>=11.0.0')
707
- )
708
-
709
- if (parallelLocations.length && hasOldParallel) {
710
- addResult(
711
- results,
712
- 'warning',
713
- 'Cucumber parallel mode has feature limits before version 11',
714
- 'Some Test Optimization features for Cucumber parallel mode require @cucumber/cucumber >=11.0.0.',
715
- {
716
- locations: parallelLocations,
717
- recommendation: 'Upgrade @cucumber/cucumber to >=11.0.0 when using --parallel.',
718
- }
719
- )
720
- }
721
- }
722
- }
723
-
724
- /**
725
- * Checks Cypress-specific setup.
726
- *
727
- * @param {Array<object>} results mutable result list
728
- * @param {object} evidence repository evidence
729
- */
730
- function checkCypressConfiguration (results, evidence) {
731
- if (evidence.cypressSupportDisabledLocations.length) {
732
- addResult(
733
- results,
734
- 'warning',
735
- 'Cypress support file is disabled',
736
- 'Cypress browser-side hooks cannot be injected when supportFile is false.',
737
- {
738
- locations: evidence.cypressSupportDisabledLocations,
739
- recommendation: 'Use a Cypress support file, or manually require dd-trace/ci/cypress/support.',
740
- }
741
- )
742
- return
743
- }
744
-
745
- if (evidence.cypressSupportLocations.length) {
746
- addResult(
747
- results,
748
- 'ok',
749
- 'Cypress support hook found',
750
- 'Found dd-trace/ci/cypress/support in the repository.',
751
- { locations: evidence.cypressSupportLocations }
752
- )
753
- } else {
754
- addResult(
755
- results,
756
- 'info',
757
- 'Cypress support hook not explicitly configured',
758
- 'For supported Cypress versions, dd-trace can inject a temporary support wrapper when dd-trace/ci/init is used.',
759
- {
760
- recommendation:
761
- 'If browser-side test events are missing, add require("dd-trace/ci/cypress/support") to the ' +
762
- 'Cypress support file.',
763
- }
764
- )
765
- }
766
- }
767
-
768
- /**
769
- * Checks static CI workflow files.
770
- *
771
- * @param {Array<object>} results mutable result list
772
- * @param {Array<object>} workflowFiles scanned CI workflow files
773
- * @param {object} evidence repository evidence
774
- * @param {typeof process.env} env environment
775
- */
776
- function checkCiConfiguration (results, workflowFiles, evidence, env) {
777
- if (!workflowFiles.length) {
778
- addResult(
779
- results,
780
- 'info',
781
- 'No CI workflow files found',
782
- 'The diagnosis did not find common CI configuration files to inspect.'
783
- )
784
- return
785
- }
786
-
787
- addResult(
788
- results,
789
- 'ok',
790
- 'CI workflow files found',
791
- `Inspected ${workflowFiles.length} CI workflow file(s).`,
792
- { locations: workflowFiles.map(file => file.relativePath) }
793
- )
794
-
795
- if (!evidence.hasCiInit && !hasCiInitInNodeOptions(env.NODE_OPTIONS)) {
796
- addResult(
797
- results,
798
- 'warning',
799
- 'CI workflows do not show Test Optimization initialization',
800
- 'No CI workflow file shows NODE_OPTIONS preloading dd-trace/ci/init.',
801
- {
802
- recommendation:
803
- 'Set NODE_OPTIONS="-r dd-trace/ci/init" in the CI job that runs the supported JavaScript test framework.',
804
- }
805
- )
806
- }
807
-
808
- const shallowGithubLocations = []
809
- const containerGithubLocations = []
810
-
811
- for (const file of workflowFiles) {
812
- if (!file.relativePath.startsWith('.github/workflows/')) continue
813
-
814
- if (/actions\/checkout/.test(file.content) && !/fetch-depth\s*:\s*0\b/.test(file.content)) {
815
- shallowGithubLocations.push(file.relativePath)
816
- }
817
-
818
- if (/\bcontainer\s*:/.test(file.content) && !/safe\.directory/.test(file.content)) {
819
- containerGithubLocations.push(file.relativePath)
820
- }
821
- }
822
-
823
- if (shallowGithubLocations.length) {
824
- addResult(
825
- results,
826
- 'warning',
827
- 'GitHub Actions checkout may be shallow',
828
- 'actions/checkout defaults to a shallow checkout, which can limit git metadata and impacted-test detection.',
829
- {
830
- locations: shallowGithubLocations,
831
- recommendation: 'Set fetch-depth: 0 for the checkout step, or keep git unshallowing enabled.',
832
- }
833
- )
834
- }
835
-
836
- if (containerGithubLocations.length) {
837
- addResult(
838
- results,
839
- 'info',
840
- 'Containerized GitHub jobs may need Git safe.directory',
841
- 'Git can reject metadata commands in containerized jobs when checkout ownership differs from the container user.',
842
- {
843
- locations: containerGithubLocations,
844
- recommendation: 'Run git config --global --add safe.directory "$GITHUB_WORKSPACE" when needed.',
845
- }
846
- )
847
- }
848
-
849
- if (evidence.hasAgentlessEnabled && !evidence.hasApiKey && !env.DD_API_KEY && !env.DATADOG_API_KEY) {
850
- addResult(
851
- results,
852
- 'warning',
853
- 'Agentless mode is enabled but no API key reference was found',
854
- 'DD_CIVISIBILITY_AGENTLESS_ENABLED requires DD_API_KEY or DATADOG_API_KEY at runtime.',
855
- {
856
- recommendation: 'Provide DD_API_KEY or DATADOG_API_KEY as a CI secret in the test job.',
857
- }
858
- )
859
- }
860
-
861
- if (evidence.gitStrategyNoneLocations.length) {
862
- addResult(
863
- results,
864
- 'warning',
865
- 'CI configuration disables git checkout',
866
- 'Git metadata extraction cannot work when the CI job does not check out the repository.',
867
- {
868
- locations: evidence.gitStrategyNoneLocations,
869
- recommendation: 'Enable repository checkout for Test Optimization jobs.',
870
- }
871
- )
872
- }
873
- }
874
-
875
- /**
876
- * Checks local git availability and repository metadata.
877
- *
878
- * @param {Array<object>} results mutable result list
879
- * @param {string} root repository root
880
- * @param {typeof process.env} env environment
881
- * @param {Function} execFile command runner
882
- * @param {string|undefined} gitExecutable trusted git executable
883
- */
884
- function checkGit (results, root, env, execFile, gitExecutable) {
885
- const gitEnv = getGitEnvironment(gitExecutable, env)
886
- if (!canRunGit(execFile, root, gitExecutable, gitEnv)) {
887
- addResult(
888
- results,
889
- 'error',
890
- 'git executable is not available',
891
- 'Test Optimization uses git to extract repository metadata and impacted files.',
892
- { recommendation: 'Install git in the CI image or runner that executes tests.' }
893
- )
894
- return
895
- }
896
-
897
- addResult(results, 'ok', 'git executable found', 'The current environment can execute git.')
898
-
899
- const insideWorktree = runGit(execFile, root, gitExecutable, gitEnv, ['rev-parse', '--is-inside-work-tree'])
900
- if (insideWorktree !== 'true') {
901
- addResult(
902
- results,
903
- 'warning',
904
- 'Current path is not inside a git worktree',
905
- 'Git metadata extraction needs the checked-out repository.',
906
- { recommendation: 'Run the test command from inside the checked-out repository.' }
907
- )
908
- return
909
- }
910
-
911
- const head = runGit(execFile, root, gitExecutable, gitEnv, ['rev-parse', 'HEAD'])
912
- const remote = runGit(execFile, root, gitExecutable, gitEnv, ['config', '--get', 'remote.origin.url'])
913
- const branch = runGit(execFile, root, gitExecutable, gitEnv, ['branch', '--show-current'])
914
- const shallow = runGit(execFile, root, gitExecutable, gitEnv, ['rev-parse', '--is-shallow-repository'])
915
-
916
- if (head) {
917
- addResult(results, 'ok', 'git commit SHA detected', `Current HEAD is ${head.slice(0, 12)}.`)
918
- } else {
919
- addResult(
920
- results,
921
- 'warning',
922
- 'git commit SHA could not be detected',
923
- 'The diagnosis could not read git rev-parse HEAD.',
924
- { recommendation: 'Ensure the CI checkout includes a valid git repository.' }
925
- )
926
- }
927
-
928
- if (!remote) {
929
- addResult(
930
- results,
931
- 'warning',
932
- 'git remote origin is not configured',
933
- 'Repository URL metadata may be missing.',
934
- { recommendation: 'Configure remote.origin.url or provide DD_GIT_REPOSITORY_URL.' }
935
- )
936
- }
937
-
938
- if (!branch && !hasBranchMetadata(env)) {
939
- addResult(
940
- results,
941
- 'warning',
942
- 'git branch metadata could not be detected',
943
- 'The checkout appears detached and no CI branch metadata was found in the current environment.',
944
- { recommendation: 'Provide branch metadata through CI provider variables or DD_GIT_BRANCH.' }
945
- )
946
- }
947
-
948
- if (shallow === 'true') {
949
- addResult(
950
- results,
951
- 'warning',
952
- 'Repository is shallow',
953
- 'A shallow repository can limit metadata upload and impacted-test detection.',
954
- { recommendation: 'Use a full checkout, or keep DD_CIVISIBILITY_GIT_UNSHALLOW_ENABLED enabled.' }
955
- )
956
- }
957
- }
958
-
959
- /**
960
- * Checks current environment variables relevant to Test Optimization.
961
- *
962
- * @param {Array<object>} results mutable result list
963
- * @param {typeof process.env} env environment
964
- * @param {object} evidence repository evidence
965
- */
966
- function checkCurrentEnvironment (results, env, evidence) {
967
- if (isFalseLike(env.DD_CIVISIBILITY_ENABLED) || evidence.hasCiVisibilityDisabled) {
968
- addResult(
969
- results,
970
- 'error',
971
- 'Test Optimization is explicitly disabled',
972
- 'DD_CIVISIBILITY_ENABLED is set to false or 0.',
973
- { recommendation: 'Remove DD_CIVISIBILITY_ENABLED=false from the test job.' }
974
- )
975
- }
976
-
977
- if (isFalseLike(env.DD_CIVISIBILITY_ITR_ENABLED) || evidence.hasItrDisabled) {
978
- addResult(
979
- results,
980
- 'warning',
981
- 'Test Impact Analysis is disabled',
982
- 'DD_CIVISIBILITY_ITR_ENABLED is set to false or 0.',
983
- { recommendation: 'Remove DD_CIVISIBILITY_ITR_ENABLED=false if suite skipping should be enabled.' }
984
- )
985
- }
986
-
987
- if (isFalseLike(env.DD_CIVISIBILITY_GIT_UPLOAD_ENABLED) || evidence.hasGitUploadDisabled) {
988
- addResult(
989
- results,
990
- 'warning',
991
- 'Git metadata upload is disabled',
992
- 'DD_CIVISIBILITY_GIT_UPLOAD_ENABLED is set to false or 0.',
993
- { recommendation: 'Remove DD_CIVISIBILITY_GIT_UPLOAD_ENABLED=false unless this is intentional.' }
994
- )
995
- }
996
-
997
- if (isTrueLike(env.DD_CIVISIBILITY_AGENTLESS_ENABLED) && !env.DD_API_KEY && !env.DATADOG_API_KEY) {
998
- addResult(
999
- results,
1000
- 'error',
1001
- 'Agentless mode is missing an API key',
1002
- 'The current environment has DD_CIVISIBILITY_AGENTLESS_ENABLED set, but no DD_API_KEY or DATADOG_API_KEY.',
1003
- { recommendation: 'Set DD_API_KEY or DATADOG_API_KEY in the CI job.' }
1004
- )
1005
- }
1006
-
1007
- if (!env.DD_SERVICE && !evidence.hasService) {
1008
- addResult(
1009
- results,
1010
- 'warning',
1011
- 'DD_SERVICE was not found',
1012
- 'A missing service name makes Test Optimization data harder to find and group.',
1013
- { recommendation: 'Set DD_SERVICE in the test job.' }
1014
- )
1015
- }
1016
-
1017
- if ((env.OTEL_TRACES_EXPORTER || '').toLowerCase() === 'otlp' || evidence.hasOtelOtlpExporter) {
1018
- addResult(
1019
- results,
1020
- 'warning',
1021
- 'OTEL_TRACES_EXPORTER=otlp was found',
1022
- 'An OTLP traces exporter can interfere with dd-trace test payloads in instrumented shells.',
1023
- { recommendation: 'Unset OTEL_TRACES_EXPORTER for dd-trace Test Optimization jobs.' }
1024
- )
1025
- }
1026
-
1027
- if (env.CI) {
1028
- checkCurrentCiMetadata(results, env)
1029
- } else {
1030
- addResult(
1031
- results,
1032
- 'info',
1033
- 'Current process is not running in CI',
1034
- 'Runtime CI metadata checks were skipped because CI is not set in the current environment.'
1035
- )
1036
- }
1037
- }
1038
-
1039
- /**
1040
- * Checks current CI provider metadata.
1041
- *
1042
- * @param {Array<object>} results mutable result list
1043
- * @param {typeof process.env} env environment
1044
- */
1045
- function checkCurrentCiMetadata (results, env) {
1046
- const providerDetected = CURRENT_ENV_PROVIDER_KEYS.some(key => env[key])
1047
- if (!providerDetected) {
1048
- addResult(
1049
- results,
1050
- 'warning',
1051
- 'Current CI provider is not recognized',
1052
- 'The current environment has CI set, but no known CI provider variables were found.',
1053
- { recommendation: 'Provide CI and git metadata with DD_GIT_* variables if the provider is custom.' }
1054
- )
1055
- }
1056
-
1057
- if (!hasShaMetadata(env)) {
1058
- addResult(
1059
- results,
1060
- 'warning',
1061
- 'Current CI commit SHA metadata is missing',
1062
- 'The current CI environment does not expose a recognized commit SHA variable.',
1063
- { recommendation: 'Provide DD_GIT_COMMIT_SHA when the CI provider does not expose one.' }
1064
- )
1065
- }
1066
-
1067
- if (!hasBranchMetadata(env)) {
1068
- addResult(
1069
- results,
1070
- 'warning',
1071
- 'Current CI branch metadata is missing',
1072
- 'The current CI environment does not expose a recognized branch or tag variable.',
1073
- { recommendation: 'Provide DD_GIT_BRANCH or DD_GIT_TAG when the CI provider does not expose one.' }
1074
- )
1075
- }
1076
- }
1077
-
1078
- /**
1079
- * Collects package scripts from all manifests.
1080
- *
1081
- * @param {Array<object>} manifests package manifests
1082
- * @returns {Array<object>} scripts
1083
- */
1084
- function collectScripts (manifests) {
1085
- const scripts = []
1086
-
1087
- for (const manifest of manifests) {
1088
- const manifestScripts = manifest.json.scripts || {}
1089
- for (const [name, command] of Object.entries(manifestScripts)) {
1090
- if (typeof command !== 'string') continue
1091
-
1092
- scripts.push({
1093
- name,
1094
- command,
1095
- relativePath: manifest.relativePath,
1096
- })
1097
- }
1098
- }
1099
-
1100
- return scripts
1101
- }
1102
-
1103
- /**
1104
- * Detects supported test frameworks.
1105
- *
1106
- * @param {string} root repository root
1107
- * @param {Array<object>} definitions framework definitions
1108
- * @param {Array<object>} manifests package manifests
1109
- * @param {Array<object>} scripts package scripts
1110
- * @param {Array<object>} textFiles scanned text files
1111
- * @returns {Array<object>} detected supported frameworks
1112
- */
1113
- function detectSupportedFrameworks (root, definitions, manifests, scripts, textFiles) {
1114
- const frameworks = []
1115
- const projectPreferenceScores = getProjectPreferenceScores(root, manifests)
1116
-
1117
- for (const definition of definitions) {
1118
- const dependencyEntries = [
1119
- ...findDependencyEntries(manifests, definition.packages),
1120
- ...findPackageIdentityEntries(manifests, definition.packages),
1121
- ]
1122
- const scriptMatches = findScriptMatches(scripts, definition.commandPatterns)
1123
- const configMatches = findConfigMatches(textFiles, definition.configPatterns)
1124
-
1125
- if (!dependencyEntries.length && !scriptMatches.length && !configMatches.length) continue
1126
-
1127
- frameworks.push({
1128
- ...definition,
1129
- dependencyEntries,
1130
- scriptMatches,
1131
- configMatches,
1132
- projectPreferenceScores,
1133
- locations: unique([
1134
- ...dependencyEntries.map(entry => entry.relativePath),
1135
- ...scriptMatches.map(script => script.relativePath),
1136
- ...configMatches,
1137
- ]),
1138
- versionDetections: getVersionDetections(root, definition.packages, dependencyEntries),
1139
- })
1140
- }
1141
-
1142
- return frameworks
1143
- }
1144
-
1145
- /**
1146
- * Gets frameworks that are eligible live-validation candidates.
1147
- *
1148
- * @param {Array<object>} frameworks detected supported frameworks
1149
- * @returns {Array<object>} eligible frameworks with eligibility details
1150
- */
1151
- function getEligibleFrameworks (frameworks) {
1152
- const eligible = []
1153
-
1154
- for (const framework of frameworks) {
1155
- const command = getEligibleCommandMatch(framework)
1156
- const version = getSupportedVersionDetection(framework, command?.relativePath)
1157
- const reasons = []
1158
-
1159
- if (!version) reasons.push(`No statically supported ${framework.name} version was found.`)
1160
- if (!command) reasons.push(`No eligible ${framework.name} test command was found.`)
1161
-
1162
- if (!version || !command) continue
1163
-
1164
- eligible.push({
1165
- ...framework,
1166
- eligibleCommand: command,
1167
- eligibleVersion: version,
1168
- eligibility: {
1169
- command: command.command,
1170
- commandLocation: command.relativePath,
1171
- version: version.version,
1172
- versionLocation: version.relativePath,
1173
- },
1174
- ineligibleReasons: reasons,
1175
- })
1176
- }
1177
-
1178
- return eligible
1179
- }
1180
-
1181
- /**
1182
- * Gets the first supported version detection for a framework.
1183
- *
1184
- * @param {object} framework detected framework
1185
- * @param {string} [relativePath] package manifest that owns the selected command
1186
- * @returns {object|undefined} supported version detection
1187
- */
1188
- function getSupportedVersionDetection (framework, relativePath) {
1189
- const detections = framework.versionDetections || []
1190
- const localDetections = relativePath
1191
- ? detections.filter(detection => detection.relativePath === relativePath)
1192
- : []
1193
- const candidates = localDetections.length > 0 ? localDetections : detections
1194
-
1195
- for (const detection of candidates) {
1196
- if (detection.version && satisfies(detection.version, framework.supportedRange)) return detection
1197
- }
1198
- }
1199
-
1200
- /**
1201
- * Gets an eligible script command for a framework.
1202
- *
1203
- * @param {object} framework detected framework
1204
- * @returns {object|undefined} eligible command match
1205
- */
1206
- function getEligibleCommandMatch (framework) {
1207
- const scriptMatches = [...(framework.scriptMatches || [])].sort((left, right) => {
1208
- return compareProjectScope(left, right, framework.projectPreferenceScores) ||
1209
- getFrameworkCommandPreference(framework.id, left) - getFrameworkCommandPreference(framework.id, right) ||
1210
- left.relativePath.localeCompare(right.relativePath)
1211
- })
1212
-
1213
- for (const script of scriptMatches) {
1214
- if (isIneligibleFrameworkCommand(framework.id, script.command)) continue
1215
- return script
1216
- }
1217
-
1218
- if (framework.id === 'cucumber' || framework.id === 'cypress' || framework.id === 'jest' ||
1219
- framework.id === 'mocha' || framework.id === 'playwright' || framework.id === 'vitest') {
1220
- const dependencyEntries = [...(framework.dependencyEntries || [])].sort((left, right) => {
1221
- return compareProjectPreference(left, right, framework.projectPreferenceScores)
1222
- })
1223
- return dependencyEntries[0] && {
1224
- command: `direct ${framework.id} binary`,
1225
- relativePath: dependencyEntries[0].relativePath,
1226
- }
1227
- }
1228
- }
1229
-
1230
- /**
1231
- * Prefers direct, single-stage framework scripts over aggregate coverage or setup chains.
1232
- *
1233
- * @param {string} frameworkId framework id
1234
- * @param {object} script package script
1235
- */
1236
- function getFrameworkCommandPreference (frameworkId, script) {
1237
- let score = 0
1238
- if (/coverage|all|full/i.test(script.name)) score += 4
1239
- if (/[\r\n;&|`]|\$\(/.test(script.command)) score += 4
1240
- const invokesFramework = frameworkId === 'cucumber'
1241
- ? isCucumberRunnerCommand(script.command)
1242
- : script.command.toLowerCase().includes(frameworkId.toLowerCase())
1243
- if (invokesFramework) score--
1244
- return score
1245
- }
1246
-
1247
- /**
1248
- * Scores package manifests by how closely their names match the repository directory name.
1249
- *
1250
- * @param {string} root repository root
1251
- * @param {Array<object>} manifests package manifests
1252
- * @returns {Map<string, number>} preference score by package.json path
1253
- */
1254
- function getProjectPreferenceScores (root, manifests) {
1255
- const repositoryTokens = getIdentityTokens(path.basename(root))
1256
- const scores = new Map()
1257
-
1258
- for (const manifest of manifests) {
1259
- const projectName = manifest.json.name || (manifest.relativePath === 'package.json'
1260
- ? path.basename(root)
1261
- : path.basename(path.dirname(manifest.relativePath)))
1262
- const projectTokens = getIdentityTokens(projectName)
1263
- let score = 0
1264
- for (const token of projectTokens) {
1265
- if (repositoryTokens.has(token)) score++
1266
- }
1267
- scores.set(manifest.relativePath, score)
1268
- }
1269
-
1270
- return scores
1271
- }
1272
-
1273
- /**
1274
- * Normalizes repository and package names for conservative identity comparison.
1275
- *
1276
- * @param {unknown} value repository or package name from manifest metadata
1277
- * @returns {Set<string>} normalized identity tokens
1278
- */
1279
- function getIdentityTokens (value) {
1280
- const tokens = String(value || '').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)
1281
- const normalized = new Set()
1282
- for (const token of tokens) {
1283
- if (['monorepo', 'package', 'packages', 'project', 'repo', 'root', 'workspace'].includes(token)) continue
1284
- normalized.add(token.endsWith('js') && token.length > 2 ? token.slice(0, -2) : token)
1285
- }
1286
- return normalized
1287
- }
1288
-
1289
- /**
1290
- * Orders command owners by repository identity, then by scope and stable path.
1291
- *
1292
- * @param {object} left first command or dependency entry
1293
- * @param {object} right second command or dependency entry
1294
- * @param {Map<string, number>|undefined} scores package preference scores
1295
- */
1296
- function compareProjectPreference (left, right, scores) {
1297
- return compareProjectScope(left, right, scores) ||
1298
- left.relativePath.localeCompare(right.relativePath)
1299
- }
1300
-
1301
- /**
1302
- * Orders command owners by repository identity and package depth.
1303
- *
1304
- * @param {object} left first command or dependency entry
1305
- * @param {object} right second command or dependency entry
1306
- * @param {Map<string, number>|undefined} scores package preference scores
1307
- */
1308
- function compareProjectScope (left, right, scores) {
1309
- const scoreDifference = (scores?.get(right.relativePath) || 0) - (scores?.get(left.relativePath) || 0)
1310
- if (scoreDifference !== 0) return scoreDifference
1311
-
1312
- return left.relativePath.split('/').length - right.relativePath.split('/').length
1313
- }
1314
-
1315
- /**
1316
- * Checks whether a framework command is ineligible for live validation.
1317
- *
1318
- * @param {string} frameworkId framework id
1319
- * @param {string} command package script command
1320
- */
1321
- function isIneligibleFrameworkCommand (frameworkId, command) {
1322
- if (frameworkId === 'cucumber' && !isCucumberRunnerCommand(command)) return true
1323
- if (frameworkId === 'vitest' && /\bvitest\s+bench\b/.test(command)) return true
1324
- if (WATCH_MODE_RE.test(command)) return true
1325
-
1326
- return false
1327
- }
1328
-
1329
- /**
1330
- * Checks whether a package command invokes the Cucumber runner instead of merely naming a Cucumber config file.
1331
- *
1332
- * @param {string} command package script command
1333
- */
1334
- function isCucumberRunnerCommand (command) {
1335
- return CUCUMBER_RUNNER_COMMAND_RE.test(command)
1336
- }
1337
-
1338
- /**
1339
- * Detects unsupported test frameworks.
1340
- *
1341
- * @param {Array<object>} definitions unsupported framework definitions
1342
- * @param {Array<object>} manifests package manifests
1343
- * @param {Array<object>} scripts package scripts
1344
- * @returns {Array<object>} detected unsupported frameworks
1345
- */
1346
- function detectUnsupportedFrameworks (definitions, manifests, scripts) {
1347
- const frameworks = []
1348
-
1349
- for (const definition of definitions) {
1350
- const dependencyEntries = findDependencyEntries(manifests, definition.packages)
1351
- const scriptMatches = findScriptMatches(scripts, definition.commandPatterns)
1352
-
1353
- if (!dependencyEntries.length && !scriptMatches.length) continue
1354
-
1355
- frameworks.push({
1356
- ...definition,
1357
- locations: unique([
1358
- ...dependencyEntries.map(entry => entry.relativePath),
1359
- ...scriptMatches.map(script => script.relativePath),
1360
- ]),
1361
- })
1362
- }
1363
-
1364
- return frameworks
1365
- }
1366
-
1367
- /**
1368
- * Collects useful boolean evidence from scanned files and environment.
1369
- *
1370
- * @param {Array<object>} textFiles scanned text files
1371
- * @param {typeof process.env} env environment
1372
- * @returns {object} evidence object
1373
- */
1374
- function collectEvidence (textFiles, env) {
1375
- const ciInitLocations = findNodeOptionsPreloadLocations(textFiles, INIT_PRELOAD_RE)
1376
- const registerLocations = findNodeOptionsPreloadLocations(textFiles, REGISTER_PRELOAD_RE)
1377
-
1378
- return {
1379
- ciInitLocations,
1380
- directCiInitLocations: findLocations(textFiles, DIRECT_CI_INIT_RE),
1381
- wrongInitLocations: findLocations(textFiles.filter(isTestSetupOrCiFile), WRONG_INIT_RE),
1382
- cypressManualPluginLocations: findLocations(textFiles, CYPRESS_MANUAL_PLUGIN_RE),
1383
- cypressSupportLocations: findLocations(textFiles, CYPRESS_SUPPORT_RE),
1384
- cypressSupportDisabledLocations: findLocations(textFiles, CYPRESS_SUPPORT_DISABLED_RE),
1385
- gitStrategyNoneLocations: findLocations(textFiles, /GIT_STRATEGY\s*:\s*none\b/i),
1386
- hasCiInit: ciInitLocations.length > 0,
1387
- hasRegister: registerLocations.length > 0,
1388
- hasCiVisibilityDisabled: findLocations(textFiles, CI_DISABLED_RE).length > 0,
1389
- hasItrDisabled: findLocations(textFiles, ITR_DISABLED_RE).length > 0,
1390
- hasGitUploadDisabled: findLocations(textFiles, GIT_UPLOAD_DISABLED_RE).length > 0,
1391
- hasAgentlessEnabled: findLocations(textFiles, AGENTLESS_ENABLED_RE).length > 0 ||
1392
- isTrueLike(env.DD_CIVISIBILITY_AGENTLESS_ENABLED),
1393
- hasApiKey: findLocations(textFiles, API_KEY_RE).length > 0,
1394
- hasService: findLocations(textFiles, SERVICE_RE).length > 0,
1395
- hasOtelOtlpExporter: findLocations(textFiles, OTEL_OTLP_RE).length > 0,
1396
- }
1397
- }
1398
-
1399
- /**
1400
- * Finds dependency entries in package manifests.
1401
- *
1402
- * @param {Array<object>} manifests package manifests
1403
- * @param {string[]} packageNames package names
1404
- * @returns {Array<object>} matching dependency entries
1405
- */
1406
- function findDependencyEntries (manifests, packageNames) {
1407
- const entries = []
1408
- const packageSet = new Set(packageNames)
1409
-
1410
- for (const manifest of manifests) {
1411
- for (const section of PACKAGE_SECTIONS) {
1412
- const dependencies = manifest.json[section]
1413
- if (!dependencies) continue
1414
-
1415
- for (const [name, range] of Object.entries(dependencies)) {
1416
- if (!packageSet.has(name)) continue
1417
-
1418
- entries.push({
1419
- packageName: name,
1420
- rawVersion: String(range),
1421
- section,
1422
- relativePath: manifest.relativePath,
1423
- })
1424
- }
1425
- }
1426
- }
1427
-
1428
- return entries
1429
- }
1430
-
1431
- /**
1432
- * Treats a repository containing a framework's own package as a local version source.
1433
- *
1434
- * @param {Array<object>} manifests package manifests
1435
- * @param {string[]} packageNames framework package names
1436
- * @returns {Array<object>} local package identities
1437
- */
1438
- function findPackageIdentityEntries (manifests, packageNames) {
1439
- const packageSet = new Set(packageNames)
1440
- const entries = []
1441
- for (const manifest of manifests) {
1442
- if (!packageSet.has(manifest.json.name) || typeof manifest.json.version !== 'string') continue
1443
- entries.push({
1444
- packageName: manifest.json.name,
1445
- rawVersion: manifest.json.version,
1446
- section: 'package',
1447
- relativePath: manifest.relativePath,
1448
- })
1449
- }
1450
- return entries
1451
- }
1452
-
1453
- /**
1454
- * Resolves framework package versions from installed modules and manifest ranges.
1455
- *
1456
- * @param {string} root repository root
1457
- * @param {string[]} packageNames package names
1458
- * @param {Array<object>} dependencyEntries dependency entries
1459
- * @returns {Array<object>} version detections
1460
- */
1461
- function getVersionDetections (root, packageNames, dependencyEntries) {
1462
- const detections = []
1463
-
1464
- for (const entry of dependencyEntries) {
1465
- const packageRoot = path.dirname(path.resolve(root, entry.relativePath))
1466
- const installedVersion = getInstalledPackageVersion(root, entry.packageName, packageRoot)
1467
- detections.push({
1468
- packageName: entry.packageName,
1469
- rawVersion: installedVersion || entry.rawVersion,
1470
- version: installedVersion || coerceVersion(entry.rawVersion),
1471
- relativePath: entry.relativePath,
1472
- source: installedVersion ? 'installed' : 'manifest',
1473
- })
1474
- }
1475
-
1476
- if (detections.length > 0) return uniqueVersionDetections(detections)
1477
-
1478
- for (const packageName of packageNames) {
1479
- const version = getInstalledPackageVersion(root, packageName, root)
1480
- if (!version) continue
1481
-
1482
- detections.push({
1483
- packageName,
1484
- rawVersion: version,
1485
- version,
1486
- source: 'installed',
1487
- })
1488
- }
1489
-
1490
- return uniqueVersionDetections(detections)
1491
- }
1492
-
1493
- /**
1494
- * Reads an installed package version from node_modules.
1495
- *
1496
- * @param {string} root repository root
1497
- * @param {string} packageName package name
1498
- * @param {string} packageRoot package directory where resolution begins
1499
- * @returns {string|undefined} installed version
1500
- */
1501
- function getInstalledPackageVersion (root, packageName, packageRoot) {
1502
- const repositoryRoot = path.resolve(root)
1503
- let directory = path.resolve(packageRoot)
1504
- if (!isPathInside(repositoryRoot, directory)) return
1505
-
1506
- while (isPathInside(repositoryRoot, directory)) {
1507
- const packageJsonPath = path.join(directory, 'node_modules', ...packageName.split('/'), 'package.json')
1508
- const json = readJsonFile(packageJsonPath)
1509
- if (typeof json?.version === 'string') return json.version
1510
- if (directory === repositoryRoot) return
1511
-
1512
- const parent = path.dirname(directory)
1513
- if (parent === directory) return
1514
- directory = parent
1515
- }
1516
- }
1517
-
1518
- /**
1519
- * Finds scripts matching any pattern.
1520
- *
1521
- * @param {Array<object>} scripts package scripts
1522
- * @param {RegExp[]} patterns command patterns
1523
- * @returns {Array<object>} matching scripts
1524
- */
1525
- function findScriptMatches (scripts, patterns) {
1526
- const matches = []
1527
-
1528
- for (const script of scripts) {
1529
- if (!/test|spec|e2e|integration|unit/i.test(script.name) &&
1530
- !patterns.some(pattern => pattern.test(script.command))) {
1531
- continue
1532
- }
1533
-
1534
- if (patterns.some(pattern => pattern.test(script.command))) {
1535
- matches.push(script)
1536
- }
1537
- }
1538
-
1539
- return matches
1540
- }
1541
-
1542
- /**
1543
- * Finds scanned config files that match definition patterns.
1544
- *
1545
- * @param {Array<object>} textFiles scanned text files
1546
- * @param {RegExp[]} patterns filename patterns
1547
- * @returns {string[]} matching relative paths
1548
- */
1549
- function findConfigMatches (textFiles, patterns) {
1550
- const matches = []
1551
-
1552
- for (const file of textFiles) {
1553
- const basename = path.basename(file.relativePath)
1554
- if (patterns.some(pattern => pattern.test(basename))) {
1555
- matches.push(file.relativePath)
1556
- }
1557
- }
1558
-
1559
- return matches
1560
- }
1561
-
1562
- /**
1563
- * Finds Jest TypeScript config files.
1564
- *
1565
- * @param {Array<object>} textFiles scanned text files
1566
- * @returns {string[]} matching relative paths
1567
- */
1568
- function findJestTypescriptConfigLocations (textFiles) {
1569
- return textFiles
1570
- .map(file => file.relativePath)
1571
- .filter(relativePath => /(?:^|\/)jest\.config\.(?:ts|mts|cts)$/.test(relativePath))
1572
- }
1573
-
1574
- /**
1575
- * Finds files where NODE_OPTIONS appears close to a supported Node preload option.
1576
- *
1577
- * @param {Array<object>} textFiles scanned text files
1578
- * @param {RegExp} preloadPattern Node preload option pattern
1579
- * @returns {string[]} matching relative paths
1580
- */
1581
- function findNodeOptionsPreloadLocations (textFiles, preloadPattern) {
1582
- const locations = []
1583
-
1584
- for (const file of textFiles) {
1585
- const lines = file.content.split(/\r?\n/)
1586
- for (let i = 0; i < lines.length; i++) {
1587
- if (!NODE_OPTIONS_RE.test(lines[i])) continue
1588
-
1589
- const window = lines.slice(i, i + 4).join('\n')
1590
- preloadPattern.lastIndex = 0
1591
- if (preloadPattern.test(window)) {
1592
- locations.push(file.relativePath)
1593
- break
1594
- }
1595
- }
1596
- }
1597
-
1598
- return unique(locations)
1599
- }
1600
-
1601
- /**
1602
- * Finds files whose content matches a pattern.
1603
- *
1604
- * @param {Array<object>} textFiles scanned text files
1605
- * @param {RegExp} pattern content pattern
1606
- * @returns {string[]} matching relative paths
1607
- */
1608
- function findLocations (textFiles, pattern) {
1609
- const locations = []
1610
-
1611
- for (const file of textFiles) {
1612
- pattern.lastIndex = 0
1613
- if (pattern.test(file.content)) {
1614
- locations.push(file.relativePath)
1615
- }
1616
- }
1617
-
1618
- return unique(locations)
1619
- }
1620
-
1621
- /**
1622
- * Collects text-like repository files.
1623
- *
1624
- * @param {string} root repository root
1625
- * @param {string|undefined} physicalRoot physical repository root
1626
- * @param {number} maxFiles maximum number of files
1627
- * @param {string[]} [excludePaths] repository paths excluded from the scan
1628
- * @returns {Array<string> & {truncated?: boolean}} relative paths
1629
- */
1630
- function collectTextFiles (root, physicalRoot, maxFiles, excludePaths = []) {
1631
- const files = []
1632
- const seen = new Set()
1633
- const exclusions = getScanExclusions(root, excludePaths)
1634
- files.truncated = false
1635
-
1636
- addTextFileIfPresent('package.json')
1637
-
1638
- function walk (dir, relativeDir) {
1639
- if (files.length >= maxFiles) {
1640
- files.truncated = true
1641
- return
1642
- }
1643
-
1644
- let entries
1645
- try {
1646
- entries = fs.readdirSync(dir, { withFileTypes: true })
1647
- } catch {
1648
- return
1649
- }
1650
-
1651
- entries.sort((a, b) => a.name.localeCompare(b.name))
1652
-
1653
- for (const entry of entries) {
1654
- if (files.length >= maxFiles) {
1655
- files.truncated = true
1656
- return
1657
- }
1658
-
1659
- const relativePath = relativeDir ? path.join(relativeDir, entry.name) : entry.name
1660
- const absolutePath = path.join(root, relativePath)
1661
- if (isScanPathExcluded(relativePath, exclusions)) continue
1662
-
1663
- if (entry.isDirectory()) {
1664
- if (!SKIPPED_DIRECTORIES.has(entry.name)) {
1665
- walk(absolutePath, relativePath)
1666
- }
1667
- continue
1668
- }
1669
-
1670
- if (entry.isFile() && isTextFileName(entry.name)) {
1671
- addTextFile(relativePath)
1672
- }
1673
- }
1674
- }
1675
-
1676
- function addTextFileIfPresent (relativePath) {
1677
- if (!getSafeScannedFile(root, physicalRoot, relativePath)) return
1678
- addTextFile(relativePath)
1679
- }
1680
-
1681
- function addTextFile (relativePath) {
1682
- const normalizedPath = normalizeRelativePath(relativePath)
1683
- if (seen.has(normalizedPath) || SKIPPED_FILES.has(normalizedPath)) return
1684
-
1685
- if (files.length >= maxFiles) {
1686
- files.truncated = true
1687
- return
1688
- }
1689
-
1690
- seen.add(normalizedPath)
1691
- files.push(relativePath)
1692
- }
1693
-
1694
- walk(root, '')
1695
- return files
1696
- }
1697
-
1698
- /**
1699
- * Normalizes caller-provided scan exclusions to repository-relative paths.
1700
- *
1701
- * @param {string} root repository root
1702
- * @param {string[]} excludePaths paths to exclude
1703
- * @returns {Set<string>} normalized repository-relative exclusions
1704
- */
1705
- function getScanExclusions (root, excludePaths) {
1706
- const exclusions = new Set()
1707
- for (const candidate of excludePaths) {
1708
- if (typeof candidate !== 'string') continue
1709
- const relative = path.relative(root, path.resolve(root, candidate))
1710
- if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) continue
1711
- exclusions.add(normalizeRelativePath(relative))
1712
- }
1713
- return exclusions
1714
- }
1715
-
1716
- /**
1717
- * Checks whether a scanned path is inside a caller-provided exclusion.
1718
- *
1719
- * @param {string} relativePath repository-relative path
1720
- * @param {Set<string>} exclusions normalized exclusions
1721
- */
1722
- function isScanPathExcluded (relativePath, exclusions) {
1723
- const normalizedPath = normalizeRelativePath(relativePath)
1724
- for (const exclusion of exclusions) {
1725
- if (normalizedPath === exclusion || normalizedPath.startsWith(`${exclusion}/`)) return true
1726
- }
1727
- return false
1728
- }
1729
-
1730
- /**
1731
- * Reads scanned text files within the size limit.
1732
- *
1733
- * @param {string} root repository root
1734
- * @param {string|undefined} physicalRoot physical repository root
1735
- * @param {string[]} files relative file paths
1736
- * @param {number} maxTotalBytes maximum aggregate bytes to retain
1737
- * @returns {Array<object>} text file records
1738
- */
1739
- function readTextFiles (root, physicalRoot, files, maxTotalBytes) {
1740
- const textFiles = []
1741
- let totalBytes = 0
1742
- textFiles.truncated = false
1743
-
1744
- for (const relativePath of files) {
1745
- const file = getSafeScannedFile(root, physicalRoot, relativePath)
1746
- if (!file || file.stat.size > MAX_TEXT_FILE_SIZE) continue
1747
- if (totalBytes + file.stat.size > maxTotalBytes) {
1748
- textFiles.truncated = true
1749
- break
1750
- }
1751
-
1752
- try {
1753
- const content = fs.readFileSync(file.filename, 'utf8')
1754
- const contentBytes = Buffer.byteLength(content)
1755
- if (contentBytes > MAX_TEXT_FILE_SIZE) continue
1756
- if (totalBytes + contentBytes > maxTotalBytes) {
1757
- textFiles.truncated = true
1758
- break
1759
- }
1760
- textFiles.push({
1761
- relativePath: normalizeRelativePath(relativePath),
1762
- content,
1763
- })
1764
- totalBytes += contentBytes
1765
- } catch {
1766
- // Ignore files that cannot be read as UTF-8.
1767
- }
1768
- }
1769
-
1770
- return textFiles
1771
- }
1772
-
1773
- /**
1774
- * Resolves the physical repository root used to constrain scanned file reads.
1775
- *
1776
- * @param {string} root repository root
1777
- * @returns {string|undefined} physical directory path
1778
- */
1779
- function getPhysicalRoot (root) {
1780
- try {
1781
- const physicalRoot = fs.realpathSync(root)
1782
- return fs.statSync(physicalRoot).isDirectory() ? physicalRoot : undefined
1783
- } catch {}
1784
- }
1785
-
1786
- /**
1787
- * Resolves one regular non-symlink file without escaping the physical repository root.
1788
- *
1789
- * @param {string} root lexical repository root
1790
- * @param {string|undefined} physicalRoot physical repository root
1791
- * @param {string} relativePath repository-relative candidate
1792
- * @returns {{filename: string, stat: fs.Stats}|undefined} safe file information
1793
- */
1794
- function getSafeScannedFile (root, physicalRoot, relativePath) {
1795
- if (!physicalRoot) return
1796
-
1797
- const lexicalRoot = path.resolve(root)
1798
- const absolutePath = path.resolve(lexicalRoot, relativePath)
1799
- if (!isPathInside(lexicalRoot, absolutePath)) return
1800
-
1801
- try {
1802
- const entry = fs.lstatSync(absolutePath)
1803
- if (!entry.isFile() || entry.isSymbolicLink()) return
1804
-
1805
- const filename = fs.realpathSync(absolutePath)
1806
- if (!isPathInside(physicalRoot, filename)) return
1807
-
1808
- const stat = fs.statSync(filename)
1809
- return stat.isFile() ? { filename, stat } : undefined
1810
- } catch {}
1811
- }
1812
-
1813
- /**
1814
- * Checks lexical or physical path containment.
1815
- *
1816
- * @param {string} root allowed root
1817
- * @param {string} filename candidate path
1818
- */
1819
- function isPathInside (root, filename) {
1820
- const relative = path.relative(root, filename)
1821
- return relative === '' || (relative && !relative.startsWith('..') && !path.isAbsolute(relative))
1822
- }
1823
-
1824
- /**
1825
- * Checks whether a filename should be scanned as text.
1826
- *
1827
- * @param {string} name filename
1828
- */
1829
- function isTextFileName (name) {
1830
- return TEXT_FILE_NAMES.has(name) || TEXT_EXTENSIONS.has(path.extname(name))
1831
- }
1832
-
1833
- /**
1834
- * Checks whether a file is a common CI workflow file.
1835
- *
1836
- * @param {string} relativePath relative path
1837
- */
1838
- function isWorkflowFile (relativePath) {
1839
- return relativePath.startsWith('.github/workflows/') ||
1840
- relativePath === '.gitlab-ci.yml' ||
1841
- relativePath === '.gitlab-ci.yaml' ||
1842
- relativePath === 'bitbucket-pipelines.yml' ||
1843
- relativePath === 'bitbucket-pipelines.yaml' ||
1844
- relativePath === 'azure-pipelines.yml' ||
1845
- relativePath === 'azure-pipelines.yaml' ||
1846
- /^\.azure-pipelines\/.+\.ya?ml$/.test(relativePath) ||
1847
- relativePath === 'Jenkinsfile' ||
1848
- relativePath === '.circleci/config.yml' ||
1849
- relativePath === '.circleci/config.yaml' ||
1850
- relativePath === '.buildkite/pipeline.yml' ||
1851
- relativePath === '.buildkite/pipeline.yaml'
1852
- }
1853
-
1854
- /**
1855
- * Checks whether a scanned file is likely to configure test process initialization.
1856
- *
1857
- * @param {object} file scanned text file
1858
- */
1859
- function isTestSetupOrCiFile (file) {
1860
- const relativePath = file.relativePath
1861
- const basename = path.basename(relativePath)
1862
-
1863
- return isWorkflowFile(relativePath) ||
1864
- basename === 'package.json' ||
1865
- /^(?:jest|config-jest|vitest|vite|playwright|cypress|cucumber)\.config\./.test(basename) ||
1866
- /^\.mocharc\./.test(basename) ||
1867
- basename === 'cypress.json' ||
1868
- /setup|bootstrap/i.test(basename) ||
1869
- relativePath.startsWith('cypress/support/')
1870
- }
1871
-
1872
- /**
1873
- * Runs git --version to check availability.
1874
- *
1875
- * @param {Function} execFile command runner
1876
- * @param {string} root repository root
1877
- * @param {string|undefined} gitExecutable trusted git executable
1878
- * @param {typeof process.env} env credential-free git environment
1879
- */
1880
- function canRunGit (execFile, root, gitExecutable, env) {
1881
- if (!gitExecutable) return false
1882
-
1883
- try {
1884
- execFile(gitExecutable, ['--version'], { cwd: root, env, stdio: 'pipe', timeout: 2000 })
1885
- return true
1886
- } catch {
1887
- return false
1888
- }
1889
- }
1890
-
1891
- /**
1892
- * Runs a git command and trims output.
1893
- *
1894
- * @param {Function} execFile command runner
1895
- * @param {string} root repository root
1896
- * @param {string} gitExecutable trusted git executable
1897
- * @param {typeof process.env} env credential-free git environment
1898
- * @param {string[]} args git arguments
1899
- */
1900
- function runGit (execFile, root, gitExecutable, env, args) {
1901
- try {
1902
- return String(execFile(gitExecutable, args, { cwd: root, env, stdio: 'pipe', timeout: 2000 })).trim()
1903
- } catch {
1904
- return ''
1905
- }
1906
- }
1907
-
1908
- /**
1909
- * Resolves git without trusting repository-controlled PATH entries.
1910
- *
1911
- * @returns {string|undefined} trusted absolute git path
1912
- */
1913
- function findTrustedGitExecutable () {
1914
- const candidates = process.platform === 'win32'
1915
- ? [
1916
- String.raw`C:\Program Files\Git\cmd\git.exe`,
1917
- String.raw`C:\Program Files\Git\bin\git.exe`,
1918
- String.raw`C:\Program Files (x86)\Git\cmd\git.exe`,
1919
- String.raw`C:\Program Files (x86)\Git\bin\git.exe`,
1920
- ]
1921
- : ['/usr/bin/git', '/usr/local/bin/git', '/opt/homebrew/bin/git']
1922
-
1923
- for (const candidate of candidates) {
1924
- let resolved
1925
- try {
1926
- resolved = fs.realpathSync(candidate)
1927
- fs.accessSync(resolved, fs.constants.X_OK)
1928
- } catch {
1929
- continue
1930
- }
1931
-
1932
- return resolved
1933
- }
1934
- }
1935
-
1936
- /**
1937
- * Creates the minimal environment needed by read-only local git metadata commands.
1938
- *
1939
- * @param {string|undefined} gitExecutable trusted git executable
1940
- * @param {typeof process.env} sourceEnv source environment
1941
- * @returns {typeof process.env} credential-free git environment
1942
- */
1943
- function getGitEnvironment (gitExecutable, sourceEnv) {
1944
- const env = {
1945
- GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null',
1946
- GIT_CONFIG_NOSYSTEM: '1',
1947
- GIT_OPTIONAL_LOCKS: '0',
1948
- GIT_TERMINAL_PROMPT: '0',
1949
- }
1950
-
1951
- for (const name of ['COMSPEC', 'ComSpec', 'PATHEXT', 'SystemRoot', 'WINDIR', 'windir']) {
1952
- if (sourceEnv[name] !== undefined) env[name] = sourceEnv[name]
1953
- }
1954
- if (gitExecutable && path.isAbsolute(gitExecutable)) env.PATH = path.dirname(gitExecutable)
1955
- return env
1956
- }
1957
-
1958
- /**
1959
- * Reads a JSON file.
1960
- *
1961
- * @param {string} filePath absolute file path
1962
- * @returns {object|undefined} parsed JSON
1963
- */
1964
- function readJsonFile (filePath) {
1965
- try {
1966
- return parseJson(fs.readFileSync(filePath, 'utf8'))
1967
- } catch {
1968
- // File is absent or unreadable.
1969
- }
1970
- }
1971
-
1972
- /**
1973
- * Parses JSON safely.
1974
- *
1975
- * @param {string} content JSON content
1976
- * @returns {object|undefined} parsed JSON
1977
- */
1978
- function parseJson (content) {
1979
- try {
1980
- return JSON.parse(content)
1981
- } catch {
1982
- // Invalid JSON is reported by the checks that depend on it.
1983
- }
1984
- }
1985
-
1986
- /**
1987
- * Extracts a comparable semantic version from a package range.
1988
- *
1989
- * @param {string} rawVersion raw package version or range
1990
- * @returns {string|undefined} comparable version
1991
- */
1992
- function coerceVersion (rawVersion) {
1993
- const aliasedVersion = rawVersion.match(/^npm:[^@]+@(.+)$/)?.[1] || rawVersion
1994
- if (isAmbiguousRange(aliasedVersion)) return
1995
-
1996
- const match = aliasedVersion.match(/\d+(?:\.\d+){0,2}/)
1997
- if (!match) return
1998
-
1999
- const parts = match[0].split('.')
2000
- while (parts.length < 3) {
2001
- parts.push('0')
2002
- }
2003
- return parts.slice(0, 3).join('.')
2004
- }
2005
-
2006
- /**
2007
- * Checks whether a manifest dependency range cannot be represented by one comparable version.
2008
- *
2009
- * @param {string} rawVersion package manifest version/range
2010
- */
2011
- function isAmbiguousRange (rawVersion) {
2012
- const version = rawVersion.trim()
2013
- if (!version || version.includes('||')) return true
2014
- return /<=?\s*\d/.test(version)
2015
- }
2016
-
2017
- /**
2018
- * Checks whether a framework id is present.
2019
- *
2020
- * @param {Array<object>} frameworks detected frameworks
2021
- * @param {string} id framework id
2022
- */
2023
- function hasFramework (frameworks, id) {
2024
- return frameworks.some(framework => framework.id === id)
2025
- }
2026
-
2027
- /**
2028
- * Checks whether NODE_OPTIONS preloads dd-trace/ci/init.
2029
- *
2030
- * @param {string|undefined} nodeOptions NODE_OPTIONS value
2031
- */
2032
- function hasCiInitInNodeOptions (nodeOptions) {
2033
- return !!nodeOptions && INIT_PRELOAD_RE.test(nodeOptions)
2034
- }
2035
-
2036
- /**
2037
- * Checks whether NODE_OPTIONS preloads dd-trace/register.js.
2038
- *
2039
- * @param {string|undefined} nodeOptions NODE_OPTIONS value
2040
- */
2041
- function hasRegisterInNodeOptions (nodeOptions) {
2042
- return !!nodeOptions && REGISTER_PRELOAD_RE.test(nodeOptions)
2043
- }
2044
-
2045
- /**
2046
- * Checks whether environment contains branch or tag metadata.
2047
- *
2048
- * @param {typeof process.env} env environment
2049
- */
2050
- function hasBranchMetadata (env) {
2051
- return !!(
2052
- env.DD_GIT_BRANCH ||
2053
- env.DD_GIT_TAG ||
2054
- env.GITHUB_HEAD_REF ||
2055
- env.GITHUB_REF_NAME ||
2056
- env.CI_COMMIT_REF_NAME ||
2057
- env.CIRCLE_BRANCH ||
2058
- env.GIT_BRANCH ||
2059
- env.BUILDKITE_BRANCH ||
2060
- env.TRAVIS_BRANCH ||
2061
- env.BITBUCKET_BRANCH ||
2062
- env.DRONE_BRANCH ||
2063
- env.BUDDY_EXECUTION_BRANCH ||
2064
- env.BITRISE_GIT_BRANCH
2065
- )
2066
- }
2067
-
2068
- /**
2069
- * Checks whether environment contains commit SHA metadata.
2070
- *
2071
- * @param {typeof process.env} env environment
2072
- */
2073
- function hasShaMetadata (env) {
2074
- return !!(
2075
- env.DD_GIT_COMMIT_SHA ||
2076
- env.GITHUB_SHA ||
2077
- env.CI_COMMIT_SHA ||
2078
- env.CIRCLE_SHA1 ||
2079
- env.GIT_COMMIT ||
2080
- env.BUILDKITE_COMMIT ||
2081
- env.TRAVIS_COMMIT ||
2082
- env.BITBUCKET_COMMIT ||
2083
- env.DRONE_COMMIT ||
2084
- env.BUDDY_EXECUTION_REVISION
2085
- )
2086
- }
2087
-
2088
- /**
2089
- * Checks truthy string env values.
2090
- *
2091
- * @param {string|undefined} value value to inspect
2092
- */
2093
- function isTrueLike (value) {
2094
- return /^(?:1|true)$/i.test(String(value))
2095
- }
2096
-
2097
- /**
2098
- * Checks false-like string env values.
2099
- *
2100
- * @param {string|undefined} value value to inspect
2101
- */
2102
- function isFalseLike (value) {
2103
- return /^(?:0|false)$/i.test(String(value || ''))
2104
- }
2105
-
2106
- /**
2107
- * Formats a list of locations for text output.
2108
- *
2109
- * @param {string[]} locations relative paths
2110
- */
2111
- function formatLocations (locations) {
2112
- const uniqueLocations = unique(locations).slice(0, 5)
2113
- const suffix = locations.length > uniqueLocations.length
2114
- ? `, and ${locations.length - uniqueLocations.length} more`
2115
- : ''
2116
- return uniqueLocations.join(', ') + suffix
2117
- }
2118
-
2119
- /**
2120
- * Serializes a supported framework for JSON output.
2121
- *
2122
- * @param {object} framework detected framework
2123
- * @returns {object} serializable framework summary
2124
- */
2125
- function serializeSupportedFramework (framework) {
2126
- const eligibleCommand = getEligibleCommandMatch(framework)
2127
- const supportedVersion = getSupportedVersionDetection(framework, eligibleCommand?.relativePath)
2128
- return {
2129
- id: framework.id,
2130
- name: framework.name,
2131
- packages: framework.packages,
2132
- supportedRange: framework.supportedRange,
2133
- locations: framework.locations,
2134
- versionDetections: framework.versionDetections,
2135
- eligibleCommand,
2136
- supportedVersion,
2137
- }
2138
- }
2139
-
2140
- /**
2141
- * Serializes an eligible framework for JSON output.
2142
- *
2143
- * @param {object} framework eligible framework
2144
- * @returns {object} serializable eligible framework summary
2145
- */
2146
- function serializeEligibleFramework (framework) {
2147
- return {
2148
- id: framework.id,
2149
- name: framework.name,
2150
- command: framework.eligibility.command,
2151
- commandLocation: framework.eligibility.commandLocation,
2152
- supportedRange: framework.supportedRange,
2153
- version: framework.eligibility.version,
2154
- versionLocation: framework.eligibility.versionLocation,
2155
- }
2156
- }
2157
-
2158
- /**
2159
- * Serializes an unsupported framework for JSON output.
2160
- *
2161
- * @param {object} framework detected unsupported framework
2162
- * @returns {object} serializable framework summary
2163
- */
2164
- function serializeUnsupportedFramework (framework) {
2165
- return {
2166
- id: framework.id,
2167
- name: framework.name,
2168
- locations: framework.locations,
2169
- }
2170
- }
2171
-
2172
- /**
2173
- * Deduplicates values.
2174
- *
2175
- * @param {Array<string>} values values
2176
- * @returns {string[]} unique values
2177
- */
2178
- function unique (values) {
2179
- return [...new Set(values.filter(Boolean))]
2180
- }
2181
-
2182
- /**
2183
- * Deduplicates version detections.
2184
- *
2185
- * @param {Array<object>} detections version detections
2186
- * @returns {Array<object>} unique detections
2187
- */
2188
- function uniqueVersionDetections (detections) {
2189
- const seen = new Set()
2190
- const uniqueDetections = []
2191
-
2192
- for (const detection of detections) {
2193
- const key = `${detection.packageName}:${detection.rawVersion}:${detection.relativePath || ''}`
2194
- if (seen.has(key)) continue
2195
-
2196
- seen.add(key)
2197
- uniqueDetections.push(detection)
2198
- }
2199
-
2200
- return uniqueDetections
2201
- }
2202
-
2203
- /**
2204
- * Normalizes relative paths to POSIX separators for stable output.
2205
- *
2206
- * @param {string} relativePath relative path
2207
- */
2208
- function normalizeRelativePath (relativePath) {
2209
- return relativePath.split(path.sep).join('/')
2210
- }
2211
-
2212
- module.exports = {
2213
- getFrameworkDefinitions,
2214
- runDiagnosis,
2215
- }