-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathdiagnose.js
More file actions
2241 lines (2025 loc) · 71.5 KB
/
Copy pathdiagnose.js
File metadata and controls
2241 lines (2025 loc) · 71.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
/* eslint-disable eslint-rules/eslint-process-env */
const fs = require('node:fs')
const path = require('node:path')
const { execFileSync } = require('node:child_process')
const satisfies = require('../vendor/dist/semifies')
const { DD_MAJOR, VERSION } = require('../version')
const MAX_TEXT_FILE_SIZE = 512 * 1024
const MAX_SCANNED_FILES = 1500
const MAX_SCANNED_TEXT_BYTES = 32 * 1024 * 1024
const PACKAGE_SECTIONS = [
'dependencies',
'devDependencies',
'optionalDependencies',
'peerDependencies',
]
const SKIPPED_DIRECTORIES = new Set([
'.cache',
'.git',
'.hg',
'.next',
'.nuxt',
'.output',
'.parcel-cache',
'.serverless',
'.svn',
'.turbo',
'.yarn',
'build',
'coverage',
'dd-test-optimization-validation-results',
'dist',
'node_modules',
'out',
'target',
'tmp',
'vendor',
])
const SKIPPED_FILES = new Set([
'ci/diagnose.js',
])
const TEXT_EXTENSIONS = new Set([
'.cjs',
'.cts',
'.js',
'.json',
'.mjs',
'.mts',
'.sh',
'.ts',
'.tsx',
'.yaml',
'.yml',
])
const TEXT_FILE_NAMES = new Set([
'Dockerfile',
'Jenkinsfile',
'Makefile',
'docker-compose.yml',
'docker-compose.yaml',
'package.json',
])
const NODE_OPTIONS_RE = /\bNODE_OPTIONS\b/
const INIT_PRELOAD_TARGET =
String.raw`(?:dd-trace/ci/init|(?:[^\s'"]*[/\\])?node_modules[/\\]dd-trace[/\\]ci[/\\]init|\./ci/init)`
const INIT_PRELOAD_RE =
new RegExp(String.raw`(?:^|[\s='"])(?:-r|--require)(?:=|\s+)['"]?${INIT_PRELOAD_TARGET}(?:\.js)?['"]?(?=$|[\s"'])`)
const REGISTER_PRELOAD_RE =
/(?:^|[\s='"])(?:--import|-r|--require)(?:=|\s+)['"]?dd-trace\/register(?:\.js)?['"]?(?=$|[\s"'])/
const WRONG_INIT_RE = /dd-trace\/(?:init|initialize\.mjs)\b|require\(['"]dd-trace['"]\)\.init\s*\(/
const DIRECT_CI_INIT_RE = /(?:require\(|import\s+)['"]dd-trace\/ci\/init(?:\.js)?['"]/
const CI_DISABLED_RE = /DD_CIVISIBILITY_ENABLED["'\s:=]+(?:false|0)\b/i
const ITR_DISABLED_RE = /DD_CIVISIBILITY_ITR_ENABLED["'\s:=]+(?:false|0)\b/i
const GIT_UPLOAD_DISABLED_RE = /DD_CIVISIBILITY_GIT_UPLOAD_ENABLED["'\s:=]+(?:false|0)\b/i
const AGENTLESS_ENABLED_RE = /DD_CIVISIBILITY_AGENTLESS_ENABLED["'\s:=]+(?:true|1)\b/i
const API_KEY_RE = /\b(?:DD_API_KEY|DATADOG_API_KEY)\b/
const SERVICE_RE = /\bDD_SERVICE\b/
const OTEL_OTLP_RE = /OTEL_TRACES_EXPORTER["'\s:=]+otlp\b/i
const WATCH_MODE_RE = /(?:^|\s)(?:watch|--watch|--watchAll)(?!=false(?:\s|$))(?:\s|=|$)/
const CYPRESS_MANUAL_PLUGIN_RE = /dd-trace\/ci\/cypress\/(?:plugin|after-run|after-spec)\b/
const CYPRESS_SUPPORT_RE = /dd-trace\/ci\/cypress\/support\b/
const CYPRESS_SUPPORT_DISABLED_RE = /supportFile\s*:\s*false|"supportFile"\s*:\s*false/
const CUCUMBER_RUNNER_COMMAND_RE = new RegExp(
String.raw`(?:^|(?:&&|\|\||[;|])\s*)` +
String.raw`(?:(?:[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|[^\s"';&|][^\s;&|]*)|` +
String.raw`cross-env|env|npx|nyc|c8|npm\s+exec|pnpm\s+exec|yarn\s+exec|-[^\s;&|]+)\s+)*` +
String.raw`(?:(?:[^\s"';&|]+[/\\])?(?:cucumber-js(?:\.cmd)?|cucumber(?:\.cmd)?)|` +
String.raw`node(?:\.exe)?\s+(?:[^\s"';&|]+[/\\])?bin[/\\]cucumber\.js)` +
String.raw`(?=$|[\s"';&|])`
)
const CUCUMBER_PARALLEL_RE =
/\bcucumber(?:-js)?\b[\s\S]{0,200}\s--parallel\b|--parallel\b[\s\S]{1,200}\bcucumber(?:-js)?\b/
const JEST_FORCE_EXIT_RE = /\bforceExit\s*:\s*true\b|--forceExit\b|"forceExit"\s*:\s*true/
const JEST_JASMINE_RE = /jest-jasmine2/
const CURRENT_ENV_PROVIDER_KEYS = [
'GITHUB_ACTIONS',
'GITLAB_CI',
'CIRCLECI',
'JENKINS_URL',
'BUILDKITE',
'TRAVIS',
'TF_BUILD',
'BITBUCKET_BUILD_NUMBER',
'DRONE',
'TEAMCITY_VERSION',
]
/**
* Builds the framework support table for the tracer major version that is running this script.
*
* @param {number} ddMajor dd-trace major version
* @returns {Array<object>} supported framework definitions
*/
function getFrameworkDefinitions (ddMajor) {
return [
{
id: 'jest',
name: 'Jest',
packages: ['jest', '@jest/core'],
commandPatterns: [/\bjest\b/],
configPatterns: [/^jest\.config\./, /^config-jest\./],
supportedRange: ddMajor >= 6 ? '>=28.0.0' : '>=24.8.0',
recommendation: 'Use a Jest and dd-trace combination whose documented support ranges overlap; this ' +
`dd-trace version requires Jest ${ddMajor >= 6 ? '>=28.0.0' : '>=24.8.0'}.`,
},
{
id: 'mocha',
name: 'Mocha',
packages: ['mocha'],
commandPatterns: [/\bmocha\b/],
configPatterns: [/^\.mocharc\./],
supportedRange: ddMajor >= 6 ? '>=8.0.0' : '>=5.2.0',
recommendation: 'Use a Mocha and dd-trace combination whose documented support ranges overlap; this ' +
`dd-trace version requires Mocha ${ddMajor >= 6 ? '>=8.0.0' : '>=5.2.0'}.`,
notes: [
'Impacted tests are detected at suite level for Mocha.',
],
},
{
id: 'cucumber',
name: 'Cucumber',
packages: ['@cucumber/cucumber'],
commandPatterns: [CUCUMBER_RUNNER_COMMAND_RE],
configPatterns: [/^cucumber\./],
supportedRange: '>=7.0.0',
recommendation: 'Upgrade @cucumber/cucumber to >=7.0.0.',
},
{
id: 'cypress',
name: 'Cypress',
packages: ['cypress'],
commandPatterns: [/\bcypress\s+(?:run|open)\b/],
configPatterns: [/^cypress\.config\./, /^cypress\.json$/],
supportedRange: ddMajor >= 6 ? '>=12.0.0' : '>=6.7.0',
autoInstrumentationRange: ddMajor >= 6 ? '>=12.0.0' : '>=10.2.0',
recommendation: 'Use a Cypress and dd-trace combination whose documented support ranges overlap; this ' +
`dd-trace version requires Cypress ${ddMajor >= 6 ? '>=12.0.0' : '>=6.7.0'}.`,
},
{
id: 'playwright',
name: 'Playwright',
packages: ['@playwright/test'],
commandPatterns: [/\bplaywright\s+test\b/],
configPatterns: [/^playwright\.config\./],
supportedRange: ddMajor >= 6 ? '>=1.38.0' : '>=1.18.0',
recommendation: 'Use a Playwright and dd-trace combination whose documented support ranges overlap; this ' +
`dd-trace version requires Playwright ${ddMajor >= 6 ? '>=1.38.0' : '>=1.18.0'}.`,
notes: [
'Test Impact Analysis suite skipping is not supported for Playwright.',
'Impacted tests are detected at suite level for Playwright.',
],
},
{
id: 'vitest',
name: 'Vitest',
packages: ['vitest'],
commandPatterns: [/\bvitest\b/],
configPatterns: [/^vitest\.config\./, /^vite\.config\./],
supportedRange: '>=1.6.0',
recommendation: 'Upgrade Vitest to >=1.6.0.',
notes: [
'Test Impact Analysis suite skipping is not supported for Vitest.',
'Impacted tests are detected at suite level for Vitest.',
],
esmInitialization: true,
},
]
}
const UNSUPPORTED_FRAMEWORKS = [
{
id: 'node-test',
name: 'Node.js test runner',
packages: [],
commandPatterns: [/\bnode\s+--test\b/, /\bnode\s+--experimental-test-coverage\b/, /\bbnt\b/],
},
{ id: 'ava', name: 'AVA', packages: ['ava'], commandPatterns: [/\bava\b/] },
{ id: 'tap', name: 'tap', packages: ['tap'], commandPatterns: [/\btap\b/] },
{ id: 'jasmine', name: 'Jasmine', packages: ['jasmine'], commandPatterns: [/\bjasmine\b/] },
{ id: 'karma', name: 'Karma', packages: ['karma'], commandPatterns: [/\bkarma\b/] },
{ id: 'uvu', name: 'uvu', packages: ['uvu'], commandPatterns: [/\buvu\b/] },
{
id: 'testcafe',
name: 'TestCafe',
packages: ['testcafe'],
commandPatterns: [/\btestcafe\b/],
},
]
/**
* Runs all static checks for a repository.
*
* @param {object} [options] diagnosis options
* @param {string} [options.root] repository path to inspect
* @param {typeof process.env} [options.env] environment to inspect
* @param {Function} [options.execFile] command runner used for git checks
* @param {string} [options.gitExecutable] trusted git executable used for git checks
* @param {number} [options.maxFiles] maximum number of text files to scan
* @param {number} [options.maxTotalBytes] maximum aggregate bytes of text files to scan
* @param {string[]} [options.excludePaths] repository paths to exclude from the text scan
* @returns {object} diagnosis report
*/
function runDiagnosis (options = {}) {
const root = path.resolve(options.root || process.cwd())
const physicalRoot = getPhysicalRoot(root)
const env = options.env || process.env
const execFile = options.execFile || execFileSync
const maxFiles = options.maxFiles || MAX_SCANNED_FILES
const maxTotalBytes = options.maxTotalBytes || MAX_SCANNED_TEXT_BYTES
const results = []
const files = collectTextFiles(root, physicalRoot, maxFiles, options.excludePaths)
const textFiles = readTextFiles(root, physicalRoot, files, maxTotalBytes)
const truncatedFileScan = files.truncated || textFiles.truncated
const manifests = readPackageManifests(root, textFiles)
const rootManifest = manifests.find(manifest => manifest.relativePath === 'package.json')
const rootPackageJsonState = getRootPackageJsonState(root, physicalRoot)
const scripts = collectScripts(manifests)
const workflowFiles = textFiles.filter(file => isWorkflowFile(file.relativePath))
const definitions = getFrameworkDefinitions(DD_MAJOR)
const supportedFrameworks = detectSupportedFrameworks(root, definitions, manifests, scripts, textFiles)
const eligibleFrameworks = getEligibleFrameworks(supportedFrameworks)
const unsupportedFrameworks = detectUnsupportedFrameworks(UNSUPPORTED_FRAMEWORKS, manifests, scripts)
const evidence = collectEvidence(textFiles, env)
checkPackageManifest(results, rootManifest, rootPackageJsonState)
checkDdTraceDependency(results, manifests, { root, truncatedFileScan, rootPackageJsonState })
checkSupportedFrameworks(results, supportedFrameworks)
checkUnsupportedFrameworks(results, unsupportedFrameworks, supportedFrameworks)
checkInitialization(results, supportedFrameworks, evidence, env)
checkFrameworkConfiguration(results, supportedFrameworks, evidence, textFiles, manifests)
checkCiConfiguration(results, workflowFiles, evidence, env)
const gitExecutable = options.gitExecutable || (options.execFile ? 'git' : findTrustedGitExecutable())
checkGit(results, root, env, execFile, gitExecutable)
checkCurrentEnvironment(results, env, evidence)
return {
root,
ddTraceVersion: VERSION,
ddTraceMajor: DD_MAJOR,
scannedFileCount: textFiles.length,
truncatedFileScan,
supportedFrameworks: supportedFrameworks.map(serializeSupportedFramework),
eligibleFrameworks: eligibleFrameworks.map(serializeEligibleFramework),
unsupportedFrameworks: unsupportedFrameworks.map(serializeUnsupportedFramework),
results,
}
}
/**
* Adds a normalized result to the list.
*
* @param {Array<object>} results mutable result list
* @param {string} status result status
* @param {string} title short title
* @param {string} message result details
* @param {object} [extra] optional fields
*/
function addResult (results, status, title, message, extra = {}) {
results.push({
status,
title,
message,
...extra,
})
}
/**
* Reads package.json files collected by the repository scan.
*
* @param {string} root repository root
* @param {Array<object>} textFiles scanned text files
* @returns {Array<object>} parsed package manifests
*/
function readPackageManifests (root, textFiles) {
const manifests = []
for (const file of textFiles) {
if (path.basename(file.relativePath) !== 'package.json') continue
const json = parseJson(file.content)
if (!json) continue
manifests.push({
path: path.join(root, file.relativePath),
relativePath: file.relativePath,
json,
})
}
return manifests
}
/**
* Checks whether the repository root has a package.json independently from the text-file scan.
*
* @param {string} root repository root
* @param {string|undefined} physicalRoot physical repository root
* @returns {{ exists: boolean }} root package.json state
*/
function getRootPackageJsonState (root, physicalRoot) {
return {
exists: Boolean(getSafeScannedFile(root, physicalRoot, 'package.json')),
}
}
/**
* Checks that a root package.json exists.
*
* @param {Array<object>} results mutable result list
* @param {object|undefined} rootManifest parsed root package manifest
* @param {object} rootPackageJsonState root package.json filesystem state
*/
function checkPackageManifest (results, rootManifest, rootPackageJsonState) {
if (rootManifest) {
addResult(results, 'ok', 'Root package.json found', 'Dependency and script checks can inspect package metadata.')
return
}
if (rootPackageJsonState.exists) {
addResult(
results,
'warning',
'Root package.json not determined',
'A root package.json file exists, but static diagnosis could not parse it as scanned text.',
{
recommendation:
'Check whether package.json is readable UTF-8 JSON and smaller than the static diagnosis file limit.',
}
)
return
}
addResult(
results,
'warning',
'No root package.json found',
'The diagnosis could not inspect root dependencies or package scripts.',
{ recommendation: 'Run this script from the JavaScript repository root, or pass --path <repository>.' }
)
}
/**
* Checks whether dd-trace is declared in repository manifests.
*
* @param {Array<object>} results mutable result list
* @param {Array<object>} manifests package manifests
* @param {object} options dependency check options
* @param {string} [options.root] repository root
* @param {boolean} [options.truncatedFileScan] whether static file discovery was truncated
* @param {object} [options.rootPackageJsonState] root package manifest state
*/
function checkDdTraceDependency (results, manifests, options = {}) {
const entries = findDependencyEntries(manifests, ['dd-trace'])
if (entries.length) {
addResult(
results,
'ok',
'dd-trace dependency found',
`Detected dd-trace in ${formatLocations(entries.map(entry => entry.relativePath))}.`
)
return
}
const installedPackageJson = options.root && path.join(options.root, 'node_modules', 'dd-trace', 'package.json')
let installed = false
try {
installed = installedPackageJson && fs.statSync(installedPackageJson).isFile()
} catch {}
if (installed) {
addResult(
results,
'ok',
'dd-trace package installed',
'Detected an installed dd-trace package even though it was not declared in the scanned package manifests.'
)
return
}
if (options.truncatedFileScan || (options.rootPackageJsonState?.exists && !hasParsedRootManifest(manifests))) {
addResult(
results,
'warning',
'dd-trace dependency not determined',
'Static diagnosis did not confirm a dd-trace dependency, but the file scan was incomplete or root package ' +
'metadata could not be parsed.',
{ recommendation: 'Inspect the package that runs tests and install dd-trace there if it is absent.' }
)
return
}
addResult(
results,
'warning',
'dd-trace dependency not found in package.json',
'The script did not find dd-trace in dependencies or devDependencies.',
{ recommendation: 'Install dd-trace in the project that runs the tests.' }
)
}
/**
* Checks whether static diagnosis parsed the repository root package manifest.
*
* @param {Array<object>} manifests parsed package manifests
* @returns {boolean} true when the root package.json was parsed
*/
function hasParsedRootManifest (manifests) {
return manifests.some(manifest => manifest.relativePath === 'package.json')
}
/**
* Checks supported framework detections and versions.
*
* @param {Array<object>} results mutable result list
* @param {Array<object>} frameworks detected supported frameworks
*/
function checkSupportedFrameworks (results, frameworks) {
if (!frameworks.length) {
addResult(
results,
'warning',
'No supported test framework detected',
'No supported Test Optimization framework was found in dependencies, scripts, or config files.',
{
recommendation:
'Use Jest, Mocha, Cucumber, Cypress, Playwright, or Vitest with a supported version.',
}
)
return
}
for (const framework of frameworks) {
if (!framework.versionDetections.length) {
addResult(
results,
'warning',
`${framework.name} detected but version is unknown`,
`${framework.name} appears in scripts or config, but no package version could be determined.`,
{
locations: framework.locations,
recommendation:
`Ensure ${framework.packages.join(' or ')} is installed and matches ${framework.supportedRange}.`,
}
)
}
for (const detection of framework.versionDetections) {
if (!detection.version) {
addResult(
results,
'warning',
`${framework.name} version could not be determined`,
`Detected ${detection.packageName}@${detection.rawVersion}, but the version is not statically comparable.`,
{
locations: [detection.relativePath],
recommendation: `Verify ${framework.name} satisfies ${framework.supportedRange}.`,
}
)
continue
}
const status = satisfies(detection.version, framework.supportedRange) ? 'ok' : 'error'
const source = detection.source === 'installed' ? 'installed package' : 'package manifest'
addResult(
results,
status,
`${framework.name} ${detection.version} ${status === 'ok' ? 'is supported' : 'is not supported'}`,
`Detected ${detection.packageName}@${detection.rawVersion} from ${source}; supported range is ` +
`${framework.supportedRange}.`,
{
locations: detection.relativePath ? [detection.relativePath] : undefined,
recommendation: status === 'error' ? framework.recommendation : undefined,
}
)
}
for (const note of framework.notes || []) {
addResult(results, 'info', `${framework.name} capability note`, note)
}
}
}
/**
* Checks unsupported framework detections.
*
* @param {Array<object>} results mutable result list
* @param {Array<object>} unsupported detected unsupported frameworks
* @param {Array<object>} supported detected supported frameworks
*/
function checkUnsupportedFrameworks (results, unsupported, supported) {
for (const framework of unsupported) {
const status = supported.length ? 'warning' : 'error'
addResult(
results,
status,
`${framework.name} is not supported by Test Optimization`,
`${framework.name} was detected in dependencies or test scripts.`,
{
locations: framework.locations,
recommendation:
'Use a supported JavaScript test framework for automatic Test Optimization instrumentation.',
}
)
}
}
/**
* Checks Test Optimization initialization.
*
* @param {Array<object>} results mutable result list
* @param {Array<object>} frameworks detected supported frameworks
* @param {object} evidence repository evidence
* @param {typeof process.env} env environment
*/
function checkInitialization (results, frameworks, evidence, env) {
if (!frameworks.length) return
const hasCiInit = evidence.hasCiInit || hasCiInitInNodeOptions(env.NODE_OPTIONS)
const hasCypressOnly = frameworks.length === 1 && frameworks[0].id === 'cypress'
const hasCypressManualPlugin = evidence.cypressManualPluginLocations.length > 0
if (hasCiInit) {
addResult(
results,
'ok',
'Test Optimization initialization found',
'Found dd-trace/ci/init preloaded through NODE_OPTIONS in repository files or the current environment.',
{ locations: evidence.ciInitLocations }
)
} else if (hasCypressOnly && hasCypressManualPlugin) {
addResult(
results,
'ok',
'Cypress manual plugin initialization found',
'Found the Cypress-specific dd-trace Test Optimization plugin setup.',
{ locations: evidence.cypressManualPluginLocations }
)
} else {
addResult(
results,
'error',
'Missing Test Optimization initialization',
'No NODE_OPTIONS preload for dd-trace/ci/init was found in repository files or the current environment.',
{
recommendation:
'Run tests with NODE_OPTIONS="-r dd-trace/ci/init". For ESM test runners, also include ' +
'--import dd-trace/register.js.',
}
)
}
if (evidence.directCiInitLocations.length) {
addResult(
results,
'error',
'Test Optimization initialization is imported directly',
'The diagnosis found require("dd-trace/ci/init") or import "dd-trace/ci/init". ' +
'That does not preload the tracer early enough for Test Optimization setup.',
{
locations: evidence.directCiInitLocations,
recommendation: 'Set NODE_OPTIONS="-r dd-trace/ci/init" on the test process instead.',
}
)
}
if (evidence.wrongInitLocations.length) {
addResult(
results,
'error',
'Plain dd-trace initialization found in test setup',
'The diagnosis found dd-trace/init, dd-trace/initialize.mjs, or require("dd-trace").init(). ' +
'That does not initialize the tracer in Test Optimization mode.',
{
locations: evidence.wrongInitLocations,
recommendation: 'Use dd-trace/ci/init for test commands instead of the plain tracing initializer.',
}
)
}
if (frameworks.some(framework => framework.esmInitialization) && hasCiInit && !evidence.hasRegister &&
!hasRegisterInNodeOptions(env.NODE_OPTIONS)) {
addResult(
results,
'warning',
'ESM loader registration not found',
'Vitest and other ESM-heavy test runners often need dd-trace/register.js before dd-trace/ci/init.',
{
recommendation:
'Use NODE_OPTIONS="--import dd-trace/register.js -r dd-trace/ci/init" for ESM test runs.',
}
)
}
}
/**
* Checks framework-specific configuration pitfalls.
*
* @param {Array<object>} results mutable result list
* @param {Array<object>} frameworks detected supported frameworks
* @param {object} evidence repository evidence
* @param {Array<object>} textFiles scanned text files
* @param {Array<object>} manifests package manifests
*/
function checkFrameworkConfiguration (results, frameworks, evidence, textFiles, manifests) {
if (hasFramework(frameworks, 'vitest') && !hasFramework(frameworks, 'playwright') &&
findDependencyEntries(manifests, ['playwright']).length > 0) {
addResult(
results,
'info',
'Playwright package is not a Playwright Test runner',
'The repository uses Vitest and has the playwright package, but no @playwright/test runner was detected. ' +
'Treat Playwright as Vitest browser-provider infrastructure, not as another test framework.',
{}
)
}
if (hasFramework(frameworks, 'cypress')) {
checkCypressConfiguration(results, evidence)
}
if (hasFramework(frameworks, 'jest')) {
const jestLocations = findLocations(textFiles, JEST_FORCE_EXIT_RE)
if (jestLocations.length) {
addResult(
results,
'warning',
'Jest forceExit can drop Test Optimization data',
'Jest\'s forceExit option can terminate before dd-trace flushes all test data.',
{
locations: jestLocations,
recommendation: 'Remove --forceExit or forceExit: true from Jest configuration when possible.',
}
)
}
const jasmineLocations = findLocations(textFiles, JEST_JASMINE_RE)
if (jasmineLocations.length) {
addResult(
results,
'info',
'Jest is configured with jest-jasmine2',
'dd-trace can avoid crashing with jest-jasmine2, but jest-circus is the better-supported runner.',
{
locations: jasmineLocations,
recommendation: 'Prefer the default jest-circus runner on supported Jest versions.',
}
)
}
const tsConfigLocations = findJestTypescriptConfigLocations(textFiles)
const hasTsNode = findDependencyEntries(manifests, ['ts-node']).length > 0
if (tsConfigLocations.length && !hasTsNode) {
addResult(
results,
'warning',
'Jest TypeScript config may need ts-node',
'Jest loads TypeScript configuration files before test transforms. Without ts-node or an equivalent ' +
'precompiled config, the selected command can fail before collecting tests.',
{
locations: tsConfigLocations,
recommendation:
'Install ts-node for the diagnostic run, or use a temporary JSON/CommonJS Jest config generated ' +
'from the repository config.',
}
)
}
}
if (hasFramework(frameworks, 'cucumber')) {
const cucumber = frameworks.find(framework => framework.id === 'cucumber')
const parallelLocations = findLocations(textFiles, CUCUMBER_PARALLEL_RE)
const hasOldParallel = cucumber.versionDetections.some(detection =>
detection.version && !satisfies(detection.version, '>=11.0.0')
)
if (parallelLocations.length && hasOldParallel) {
addResult(
results,
'warning',
'Cucumber parallel mode has feature limits before version 11',
'Some Test Optimization features for Cucumber parallel mode require @cucumber/cucumber >=11.0.0.',
{
locations: parallelLocations,
recommendation: 'Upgrade @cucumber/cucumber to >=11.0.0 when using --parallel.',
}
)
}
}
}
/**
* Checks Cypress-specific setup.
*
* @param {Array<object>} results mutable result list
* @param {object} evidence repository evidence
*/
function checkCypressConfiguration (results, evidence) {
if (evidence.cypressSupportDisabledLocations.length) {
addResult(
results,
'warning',
'Cypress support file is disabled',
'Cypress browser-side hooks cannot be injected when supportFile is false.',
{
locations: evidence.cypressSupportDisabledLocations,
recommendation: 'Use a Cypress support file, or manually require dd-trace/ci/cypress/support.',
}
)
return
}
if (evidence.cypressSupportLocations.length) {
addResult(
results,
'ok',
'Cypress support hook found',
'Found dd-trace/ci/cypress/support in the repository.',
{ locations: evidence.cypressSupportLocations }
)
} else {
addResult(
results,
'info',
'Cypress support hook not explicitly configured',
'For supported Cypress versions, dd-trace can inject a temporary support wrapper when dd-trace/ci/init is used.',
{
recommendation:
'If browser-side test events are missing, add require("dd-trace/ci/cypress/support") to the ' +
'Cypress support file.',
}
)
}
}
/**
* Checks static CI workflow files.
*
* @param {Array<object>} results mutable result list
* @param {Array<object>} workflowFiles scanned CI workflow files
* @param {object} evidence repository evidence
* @param {typeof process.env} env environment
*/
function checkCiConfiguration (results, workflowFiles, evidence, env) {
if (!workflowFiles.length) {
addResult(
results,
'info',
'No CI workflow files found',
'The diagnosis did not find common CI configuration files to inspect.'
)
return
}
addResult(
results,
'ok',
'CI workflow files found',
`Inspected ${workflowFiles.length} CI workflow file(s).`,
{ locations: workflowFiles.map(file => file.relativePath) }
)
if (!evidence.hasCiInit && !hasCiInitInNodeOptions(env.NODE_OPTIONS)) {
addResult(
results,
'warning',
'CI workflows do not show Test Optimization initialization',
'No CI workflow file shows NODE_OPTIONS preloading dd-trace/ci/init.',
{
recommendation:
'Set NODE_OPTIONS="-r dd-trace/ci/init" in the CI job that runs the supported JavaScript test framework.',
}
)
}
const shallowGithubLocations = []
const containerGithubLocations = []
for (const file of workflowFiles) {
if (!file.relativePath.startsWith('.github/workflows/')) continue
if (/actions\/checkout/.test(file.content) && !/fetch-depth\s*:\s*0\b/.test(file.content)) {
shallowGithubLocations.push(file.relativePath)
}
if (/\bcontainer\s*:/.test(file.content) && !/safe\.directory/.test(file.content)) {
containerGithubLocations.push(file.relativePath)
}
}
if (shallowGithubLocations.length) {
addResult(
results,
'warning',
'GitHub Actions checkout may be shallow',
'actions/checkout defaults to a shallow checkout, which can limit git metadata and impacted-test detection.',
{
locations: shallowGithubLocations,
recommendation: 'Set fetch-depth: 0 for the checkout step, or keep git unshallowing enabled.',
}
)
}
if (containerGithubLocations.length) {
addResult(
results,
'info',
'Containerized GitHub jobs may need Git safe.directory',
'Git can reject metadata commands in containerized jobs when checkout ownership differs from the container user.',
{
locations: containerGithubLocations,
recommendation: 'Run git config --global --add safe.directory "$GITHUB_WORKSPACE" when needed.',
}
)
}
if (evidence.hasAgentlessEnabled && !evidence.hasApiKey && !env.DD_API_KEY && !env.DATADOG_API_KEY) {
addResult(
results,
'warning',
'Agentless mode is enabled but no API key reference was found',
'DD_CIVISIBILITY_AGENTLESS_ENABLED requires DD_API_KEY or DATADOG_API_KEY at runtime.',
{
recommendation: 'Provide DD_API_KEY or DATADOG_API_KEY as a CI secret in the test job.',
}
)
}
if (evidence.gitStrategyNoneLocations.length) {
addResult(
results,
'warning',
'CI configuration disables git checkout',
'Git metadata extraction cannot work when the CI job does not check out the repository.',
{
locations: evidence.gitStrategyNoneLocations,
recommendation: 'Enable repository checkout for Test Optimization jobs.',
}
)
}
}
/**
* Checks local git availability and repository metadata.
*
* @param {Array<object>} results mutable result list
* @param {string} root repository root
* @param {typeof process.env} env environment
* @param {Function} execFile command runner
* @param {string|undefined} gitExecutable trusted git executable
*/
function checkGit (results, root, env, execFile, gitExecutable) {
const gitEnv = getGitEnvironment(gitExecutable, env)
if (!canRunGit(execFile, root, gitExecutable, gitEnv)) {
addResult(
results,
'error',
'git executable is not available',
'Test Optimization uses git to extract repository metadata and impacted files.',
{ recommendation: 'Install git in the CI image or runner that executes tests.' }
)
return
}
addResult(results, 'ok', 'git executable found', 'The current environment can execute git.')
const insideWorktree = runGit(execFile, root, gitExecutable, gitEnv, ['rev-parse', '--is-inside-work-tree'])
if (insideWorktree !== 'true') {
addResult(
results,
'warning',
'Current path is not inside a git worktree',
'Git metadata extraction needs the checked-out repository.',
{ recommendation: 'Run the test command from inside the checked-out repository.' }
)
return
}
const head = runGit(execFile, root, gitExecutable, gitEnv, ['rev-parse', 'HEAD'])
const remote = runGit(execFile, root, gitExecutable, gitEnv, ['config', '--get', 'remote.origin.url'])
const branch = runGit(execFile, root, gitExecutable, gitEnv, ['branch', '--show-current'])
const shallow = runGit(execFile, root, gitExecutable, gitEnv, ['rev-parse', '--is-shallow-repository'])
if (head) {
addResult(results, 'ok', 'git commit SHA detected', `Current HEAD is ${head.slice(0, 12)}.`)
} else {
addResult(
results,
'warning',
'git commit SHA could not be detected',
'The diagnosis could not read git rev-parse HEAD.',
{ recommendation: 'Ensure the CI checkout includes a valid git repository.' }
)
}
if (!remote) {
addResult(
results,
'warning',
'git remote origin is not configured',
'Repository URL metadata may be missing.',
{ recommendation: 'Configure remote.origin.url or provide DD_GIT_REPOSITORY_URL.' }
)
}
if (!branch && !hasBranchMetadata(env)) {
addResult(
results,
'warning',
'git branch metadata could not be detected',
'The checkout appears detached and no CI branch metadata was found in the current environment.',
{ recommendation: 'Provide branch metadata through CI provider variables or DD_GIT_BRANCH.' }
)
}
if (shallow === 'true') {
addResult(
results,
'warning',
'Repository is shallow',
'A shallow repository can limit metadata upload and impacted-test detection.',
{ recommendation: 'Use a full checkout, or keep DD_CIVISIBILITY_GIT_UNSHALLOW_ENABLED enabled.' }
)
}
}
/**
* Checks current environment variables relevant to Test Optimization.
*
* @param {Array<object>} results mutable result list
* @param {typeof process.env} env environment
* @param {object} evidence repository evidence
*/
function checkCurrentEnvironment (results, env, evidence) {
if (isFalseLike(env.DD_CIVISIBILITY_ENABLED) || evidence.hasCiVisibilityDisabled) {
addResult(
results,
'error',
'Test Optimization is explicitly disabled',
'DD_CIVISIBILITY_ENABLED is set to false or 0.',
{ recommendation: 'Remove DD_CIVISIBILITY_ENABLED=false from the test job.' }
)
}
if (isFalseLike(env.DD_CIVISIBILITY_ITR_ENABLED) || evidence.hasItrDisabled) {
addResult(
results,
'warning',
'Test Impact Analysis is disabled',
'DD_CIVISIBILITY_ITR_ENABLED is set to false or 0.',
{ recommendation: 'Remove DD_CIVISIBILITY_ITR_ENABLED=false if suite skipping should be enabled.' }
)
}
if (isFalseLike(env.DD_CIVISIBILITY_GIT_UPLOAD_ENABLED) || evidence.hasGitUploadDisabled) {
addResult(
results,
'warning',
'Git metadata upload is disabled',
'DD_CIVISIBILITY_GIT_UPLOAD_ENABLED is set to false or 0.',
{ recommendation: 'Remove DD_CIVISIBILITY_GIT_UPLOAD_ENABLED=false unless this is intentional.' }
)
}
if (isTrueLike(env.DD_CIVISIBILITY_AGENTLESS_ENABLED) && !env.DD_API_KEY && !env.DATADOG_API_KEY) {
addResult(
results,
'error',
'Agentless mode is missing an API key',