/
flat-eslint.js
5915 lines (5022 loc) · 250 KB
/
flat-eslint.js
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
/**
* @fileoverview Tests for the ESLint class.
* @author Kai Cataldo
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const assert = require("assert");
const util = require("util");
const fs = require("fs");
const fsp = fs.promises;
const os = require("os");
const path = require("path");
const escapeStringRegExp = require("escape-string-regexp");
const fCache = require("file-entry-cache");
const sinon = require("sinon");
const proxyquire = require("proxyquire").noCallThru().noPreserveCache();
const shell = require("shelljs");
const hash = require("../../../lib/cli-engine/hash");
const { unIndent, createCustomTeardown } = require("../../_utils");
const { shouldUseFlatConfig } = require("../../../lib/eslint/flat-eslint");
const coreRules = require("../../../lib/rules");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Creates a directory if it doesn't already exist.
* @param {string} dirPath The path to the directory that should exist.
* @returns {void}
*/
function ensureDirectoryExists(dirPath) {
try {
fs.statSync(dirPath);
} catch {
fs.mkdirSync(dirPath);
}
}
/**
* Does nothing for a given time.
* @param {number} time Time in ms.
* @returns {void}
*/
async function sleep(time) {
await util.promisify(setTimeout)(time);
}
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
describe("FlatESLint", () => {
const examplePluginName = "eslint-plugin-example";
const examplePluginNameWithNamespace = "@eslint/eslint-plugin-example";
const examplePlugin = {
rules: {
"example-rule": require("../../fixtures/rules/custom-rule"),
"make-syntax-error": require("../../fixtures/rules/make-syntax-error-rule")
}
};
const examplePreprocessorName = "eslint-plugin-processor";
const originalDir = process.cwd();
const fixtureDir = path.resolve(fs.realpathSync(os.tmpdir()), "eslint/fixtures");
/** @type {import("../../../lib/eslint/flat-eslint").FlatESLint} */
let FlatESLint;
/**
* Returns the path inside of the fixture directory.
* @param {...string} args file path segments.
* @returns {string} The path inside the fixture directory.
* @private
*/
function getFixturePath(...args) {
const filepath = path.join(fixtureDir, ...args);
try {
return fs.realpathSync(filepath);
} catch {
return filepath;
}
}
/**
* Create the ESLint object by mocking some of the plugins
* @param {Object} options options for ESLint
* @returns {ESLint} engine object
* @private
*/
function eslintWithPlugins(options) {
return new FlatESLint({
...options,
plugins: {
[examplePluginName]: examplePlugin,
[examplePluginNameWithNamespace]: examplePlugin,
[examplePreprocessorName]: require("../../fixtures/processors/custom-processor")
}
});
}
// copy into clean area so as not to get "infected" by this project's .eslintrc files
before(function() {
/*
* GitHub Actions Windows and macOS runners occasionally exhibit
* extremely slow filesystem operations, during which copying fixtures
* exceeds the default test timeout, so raise it just for this hook.
* Mocha uses `this` to set timeouts on an individual hook level.
*/
this.timeout(60 * 1000); // eslint-disable-line no-invalid-this -- Mocha API
shell.mkdir("-p", fixtureDir);
shell.cp("-r", "./tests/fixtures/.", fixtureDir);
});
beforeEach(() => {
({ FlatESLint } = require("../../../lib/eslint/flat-eslint"));
});
after(() => {
shell.rm("-r", fixtureDir);
});
describe("ESLint constructor function", () => {
it("the default value of 'options.cwd' should be the current working directory.", async () => {
process.chdir(__dirname);
try {
const engine = new FlatESLint();
const results = await engine.lintFiles("eslint.js");
assert.strictEqual(path.dirname(results[0].filePath), __dirname);
} finally {
process.chdir(originalDir);
}
});
it("should normalize 'options.cwd'.", async () => {
const cwd = getFixturePath("example-app3");
const engine = new FlatESLint({
cwd: `${cwd}${path.sep}foo${path.sep}..`, // `<cwd>/foo/..` should be normalized to `<cwd>`
overrideConfigFile: true,
overrideConfig: {
plugins: {
test: require(path.join(cwd, "node_modules", "eslint-plugin-test"))
},
rules: {
"test/report-cwd": "error"
}
}
});
const results = await engine.lintText("");
assert.strictEqual(results[0].messages[0].ruleId, "test/report-cwd");
assert.strictEqual(results[0].messages[0].message, cwd);
const formatter = await engine.loadFormatter("cwd");
assert.strictEqual(formatter.format(results), cwd);
});
// https://github.com/eslint/eslint/issues/2380
it("should not modify baseConfig when format is specified", () => {
const customBaseConfig = { root: true };
new FlatESLint({ baseConfig: customBaseConfig }); // eslint-disable-line no-new -- Check for argument side effects
assert.deepStrictEqual(customBaseConfig, { root: true });
});
it("should throw readable messages if removed options are present", () => {
assert.throws(
() => new FlatESLint({
cacheFile: "",
configFile: "",
envs: [],
globals: [],
ignorePath: ".gitignore",
ignorePattern: [],
parser: "",
parserOptions: {},
rules: {},
plugins: []
}),
new RegExp(escapeStringRegExp([
"Invalid Options:",
"- Unknown options: cacheFile, configFile, envs, globals, ignorePath, ignorePattern, parser, parserOptions, rules"
].join("\n")), "u")
);
});
it("should throw readable messages if wrong type values are given to options", () => {
assert.throws(
() => new FlatESLint({
allowInlineConfig: "",
baseConfig: "",
cache: "",
cacheLocation: "",
cwd: "foo",
errorOnUnmatchedPattern: "",
fix: "",
fixTypes: ["xyz"],
globInputPaths: "",
ignore: "",
ignorePatterns: "",
overrideConfig: "",
overrideConfigFile: "",
plugins: "",
reportUnusedDisableDirectives: ""
}),
new RegExp(escapeStringRegExp([
"Invalid Options:",
"- 'allowInlineConfig' must be a boolean.",
"- 'baseConfig' must be an object or null.",
"- 'cache' must be a boolean.",
"- 'cacheLocation' must be a non-empty string.",
"- 'cwd' must be an absolute path.",
"- 'errorOnUnmatchedPattern' must be a boolean.",
"- 'fix' must be a boolean or a function.",
"- 'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\".",
"- 'globInputPaths' must be a boolean.",
"- 'ignore' must be a boolean.",
"- 'ignorePatterns' must be an array of non-empty strings or null.",
"- 'overrideConfig' must be an object or null.",
"- 'overrideConfigFile' must be a non-empty string, null, or true.",
"- 'plugins' must be an object or null.",
"- 'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null."
].join("\n")), "u")
);
});
it("should throw readable messages if 'ignorePatterns' is not an array of non-empty strings.", () => {
const invalidIgnorePatterns = [
() => {},
false,
{},
"",
"foo",
[[]],
[() => {}],
[false],
[{}],
[""],
["foo", ""],
["foo", "", "bar"],
["foo", false, "bar"]
];
invalidIgnorePatterns.forEach(ignorePatterns => {
assert.throws(
() => new FlatESLint({ ignorePatterns }),
new RegExp(escapeStringRegExp([
"Invalid Options:",
"- 'ignorePatterns' must be an array of non-empty strings or null."
].join("\n")), "u")
);
});
});
it("should throw readable messages if 'plugins' option contains empty key", () => {
assert.throws(
() => new FlatESLint({
plugins: {
"eslint-plugin-foo": {},
"eslint-plugin-bar": {},
"": {}
}
}),
new RegExp(escapeStringRegExp([
"Invalid Options:",
"- 'plugins' must not include an empty string."
].join("\n")), "u")
);
});
});
describe("lintText()", () => {
let eslint;
it("should report the total and per file errors when using local cwd eslint.config.js", async () => {
eslint = new FlatESLint({
cwd: __dirname
});
const results = await eslint.lintText("var foo = 'bar';");
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 4);
assert.strictEqual(results[0].messages[0].ruleId, "no-var");
assert.strictEqual(results[0].messages[1].ruleId, "no-unused-vars");
assert.strictEqual(results[0].messages[2].ruleId, "quotes");
assert.strictEqual(results[0].messages[3].ruleId, "eol-last");
assert.strictEqual(results[0].fixableErrorCount, 3);
assert.strictEqual(results[0].fixableWarningCount, 0);
assert.strictEqual(results[0].usedDeprecatedRules.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should report the total and per file warnings when using local cwd .eslintrc", async () => {
eslint = new FlatESLint({
overrideConfig: {
rules: {
quotes: 1,
"no-var": 1,
"eol-last": 1,
"no-unused-vars": 1
}
},
overrideConfigFile: true
});
const results = await eslint.lintText("var foo = 'bar';");
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 4);
assert.strictEqual(results[0].messages[0].ruleId, "no-var");
assert.strictEqual(results[0].messages[1].ruleId, "no-unused-vars");
assert.strictEqual(results[0].messages[2].ruleId, "quotes");
assert.strictEqual(results[0].messages[3].ruleId, "eol-last");
assert.strictEqual(results[0].fixableErrorCount, 0);
assert.strictEqual(results[0].fixableWarningCount, 3);
assert.strictEqual(results[0].usedDeprecatedRules.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should report one message when using specific config file", async () => {
eslint = new FlatESLint({
overrideConfigFile: "fixtures/configurations/quotes-error.js",
cwd: getFixturePath("..")
});
const results = await eslint.lintText("var foo = 'bar';");
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 1);
assert.strictEqual(results[0].messages[0].ruleId, "quotes");
assert.strictEqual(results[0].messages[0].output, void 0);
assert.strictEqual(results[0].errorCount, 1);
assert.strictEqual(results[0].fixableErrorCount, 1);
assert.strictEqual(results[0].warningCount, 0);
assert.strictEqual(results[0].fatalErrorCount, 0);
assert.strictEqual(results[0].usedDeprecatedRules.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should report the filename when passed in", async () => {
eslint = new FlatESLint({
ignore: false,
cwd: getFixturePath()
});
const options = { filePath: "test.js" };
const results = await eslint.lintText("var foo = 'bar';", options);
assert.strictEqual(results[0].filePath, getFixturePath("test.js"));
});
it("should return a warning when given a filename by --stdin-filename in excluded files list if warnIgnored is true", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(".."),
overrideConfigFile: "fixtures/eslint.config_with_ignores.js"
});
const options = { filePath: "fixtures/passing.js", warnIgnored: true };
const results = await eslint.lintText("var bar = foo;", options);
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].filePath, getFixturePath("passing.js"));
assert.strictEqual(results[0].messages[0].severity, 1);
assert.strictEqual(results[0].messages[0].message, "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override.");
assert.strictEqual(results[0].messages[0].output, void 0);
assert.strictEqual(results[0].errorCount, 0);
assert.strictEqual(results[0].warningCount, 1);
assert.strictEqual(results[0].fatalErrorCount, 0);
assert.strictEqual(results[0].fixableErrorCount, 0);
assert.strictEqual(results[0].fixableWarningCount, 0);
assert.strictEqual(results[0].usedDeprecatedRules.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should not return a warning when given a filename by --stdin-filename in excluded files list if warnIgnored is false", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(".."),
overrideConfigFile: "fixtures/eslint.config_with_ignores.js"
});
const options = {
filePath: "fixtures/passing.js",
warnIgnored: false
};
// intentional parsing error
const results = await eslint.lintText("va r bar = foo;", options);
// should not report anything because the file is ignored
assert.strictEqual(results.length, 0);
});
it("should suppress excluded file warnings by default", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(".."),
overrideConfigFile: "fixtures/eslint.config_with_ignores.js"
});
const options = { filePath: "fixtures/passing.js" };
const results = await eslint.lintText("var bar = foo;", options);
// should not report anything because there are no errors
assert.strictEqual(results.length, 0);
});
it("should return a message when given a filename by --stdin-filename in excluded files list and ignore is off", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(".."),
ignore: false,
overrideConfigFile: "fixtures/eslint.config_with_ignores.js",
overrideConfig: {
rules: {
"no-undef": 2
}
}
});
const options = { filePath: "fixtures/passing.js" };
const results = await eslint.lintText("var bar = foo;", options);
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].filePath, getFixturePath("passing.js"));
assert.strictEqual(results[0].messages[0].ruleId, "no-undef");
assert.strictEqual(results[0].messages[0].severity, 2);
assert.strictEqual(results[0].messages[0].output, void 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should return a message and fixed text when in fix mode", async () => {
eslint = new FlatESLint({
overrideConfigFile: true,
fix: true,
overrideConfig: {
rules: {
semi: 2
}
},
ignore: false,
cwd: getFixturePath()
});
const options = { filePath: "passing.js" };
const results = await eslint.lintText("var bar = foo", options);
assert.deepStrictEqual(results, [
{
filePath: getFixturePath("passing.js"),
messages: [],
suppressedMessages: [],
errorCount: 0,
warningCount: 0,
fatalErrorCount: 0,
fixableErrorCount: 0,
fixableWarningCount: 0,
output: "var bar = foo;",
usedDeprecatedRules: []
}
]);
});
it("should return a message and omit fixed text when in fix mode and fixes aren't done", async () => {
eslint = new FlatESLint({
overrideConfigFile: true,
fix: true,
overrideConfig: {
rules: {
"no-undef": 2
}
},
ignore: false,
cwd: getFixturePath()
});
const options = { filePath: "passing.js" };
const results = await eslint.lintText("var bar = foo", options);
assert.deepStrictEqual(results, [
{
filePath: getFixturePath("passing.js"),
messages: [
{
ruleId: "no-undef",
severity: 2,
messageId: "undef",
message: "'foo' is not defined.",
line: 1,
column: 11,
endLine: 1,
endColumn: 14,
nodeType: "Identifier"
}
],
suppressedMessages: [],
errorCount: 1,
warningCount: 0,
fatalErrorCount: 0,
fixableErrorCount: 0,
fixableWarningCount: 0,
source: "var bar = foo",
usedDeprecatedRules: []
}
]);
});
it("should not delete code if there is a syntax error after trying to autofix.", async () => {
eslint = eslintWithPlugins({
overrideConfigFile: true,
fix: true,
overrideConfig: {
rules: {
"example/make-syntax-error": "error"
}
},
ignore: false,
cwd: getFixturePath(".")
});
const options = { filePath: "test.js" };
const results = await eslint.lintText("var bar = foo", options);
assert.deepStrictEqual(results, [
{
filePath: getFixturePath("test.js"),
messages: [
{
ruleId: null,
fatal: true,
severity: 2,
message: "Parsing error: Unexpected token is",
line: 1,
column: 19,
nodeType: null
}
],
suppressedMessages: [],
errorCount: 1,
warningCount: 0,
fatalErrorCount: 1,
fixableErrorCount: 0,
fixableWarningCount: 0,
output: "var bar = foothis is a syntax error.",
usedDeprecatedRules: []
}
]);
});
it("should not crash even if there are any syntax error since the first time.", async () => {
eslint = eslintWithPlugins({
overrideConfigFile: true,
fix: true,
overrideConfig: {
rules: {
"example/make-syntax-error": "error"
}
},
ignore: false,
cwd: getFixturePath()
});
const options = { filePath: "test.js" };
const results = await eslint.lintText("var bar =", options);
assert.deepStrictEqual(results, [
{
filePath: getFixturePath("test.js"),
messages: [
{
ruleId: null,
fatal: true,
severity: 2,
message: "Parsing error: Unexpected token",
line: 1,
column: 10,
nodeType: null
}
],
suppressedMessages: [],
errorCount: 1,
warningCount: 0,
fatalErrorCount: 1,
fixableErrorCount: 0,
fixableWarningCount: 0,
source: "var bar =",
usedDeprecatedRules: []
}
]);
});
it("should return source code of file in `source` property when errors are present", async () => {
eslint = new FlatESLint({
overrideConfigFile: true,
overrideConfig: {
rules: { semi: 2 }
}
});
const results = await eslint.lintText("var foo = 'bar'");
assert.strictEqual(results[0].source, "var foo = 'bar'");
});
it("should return source code of file in `source` property when warnings are present", async () => {
eslint = new FlatESLint({
overrideConfigFile: true,
overrideConfig: {
rules: { semi: 1 }
}
});
const results = await eslint.lintText("var foo = 'bar'");
assert.strictEqual(results[0].source, "var foo = 'bar'");
});
it("should not return a `source` property when no errors or warnings are present", async () => {
eslint = new FlatESLint({
overrideConfigFile: true,
overrideConfig: {
rules: { semi: 2 }
}
});
const results = await eslint.lintText("var foo = 'bar';");
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[0].source, void 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should not return a `source` property when fixes are applied", async () => {
eslint = new FlatESLint({
overrideConfigFile: true,
fix: true,
overrideConfig: {
rules: {
semi: 2,
"no-unused-vars": 2
}
}
});
const results = await eslint.lintText("var msg = 'hi' + foo\n");
assert.strictEqual(results[0].source, void 0);
assert.strictEqual(results[0].output, "var msg = 'hi' + foo;\n");
});
it("should return a `source` property when a parsing error has occurred", async () => {
eslint = new FlatESLint({
overrideConfigFile: true,
overrideConfig: {
rules: { semi: 2 }
}
});
const results = await eslint.lintText("var bar = foothis is a syntax error.\n return bar;");
assert.deepStrictEqual(results, [
{
filePath: "<text>",
messages: [
{
ruleId: null,
fatal: true,
severity: 2,
message: "Parsing error: Unexpected token is",
line: 1,
column: 19,
nodeType: null
}
],
suppressedMessages: [],
errorCount: 1,
warningCount: 0,
fatalErrorCount: 1,
fixableErrorCount: 0,
fixableWarningCount: 0,
source: "var bar = foothis is a syntax error.\n return bar;",
usedDeprecatedRules: []
}
]);
});
// https://github.com/eslint/eslint/issues/5547
it("should respect default ignore rules (ignoring node_modules), even with --no-ignore", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(),
ignore: false
});
const results = await eslint.lintText("var bar = foo;", { filePath: "node_modules/passing.js", warnIgnored: true });
const expectedMsg = "File ignored by default because it is located under the node_modules directory. Use ignore pattern \"!**/node_modules/\" to override.";
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].filePath, getFixturePath("node_modules/passing.js"));
assert.strictEqual(results[0].messages[0].message, expectedMsg);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should warn when deprecated rules are found in a config", async () => {
eslint = new FlatESLint({
cwd: originalDir,
overrideConfigFile: "tests/fixtures/cli-engine/deprecated-rule-config/eslint.config.js"
});
const [result] = await eslint.lintText("foo");
assert.deepStrictEqual(
result.usedDeprecatedRules,
[{ ruleId: "indent-legacy", replacedBy: ["indent"] }]
);
});
it("should throw if eslint.config.js file is not present", async () => {
eslint = new FlatESLint({
cwd: getFixturePath("..")
});
await assert.rejects(() => eslint.lintText("var foo = 'bar';"), /Could not find config file/u);
});
it("should not throw if eslint.config.js file is not present and overrideConfigFile is `true`", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(".."),
overrideConfigFile: true
});
await eslint.lintText("var foo = 'bar';");
});
it("should not throw if eslint.config.js file is not present and overrideConfigFile is path to a config file", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(".."),
overrideConfigFile: "fixtures/configurations/quotes-error.js"
});
await eslint.lintText("var foo = 'bar';");
});
it("should throw if overrideConfigFile is path to a file that doesn't exist", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(""),
overrideConfigFile: "does-not-exist.js"
});
await assert.rejects(() => eslint.lintText("var foo = 'bar';"), { code: "ENOENT" });
});
it("should throw if non-string value is given to 'code' parameter", async () => {
eslint = new FlatESLint();
await assert.rejects(() => eslint.lintText(100), /'code' must be a string/u);
});
it("should throw if non-object value is given to 'options' parameter", async () => {
eslint = new FlatESLint();
await assert.rejects(() => eslint.lintText("var a = 0", "foo.js"), /'options' must be an object, null, or undefined/u);
});
it("should throw if 'options' argument contains unknown key", async () => {
eslint = new FlatESLint();
await assert.rejects(() => eslint.lintText("var a = 0", { filename: "foo.js" }), /'options' must not include the unknown option\(s\): filename/u);
});
it("should throw if non-string value is given to 'options.filePath' option", async () => {
eslint = new FlatESLint();
await assert.rejects(() => eslint.lintText("var a = 0", { filePath: "" }), /'options.filePath' must be a non-empty string or undefined/u);
});
it("should throw if non-boolean value is given to 'options.warnIgnored' option", async () => {
eslint = new FlatESLint();
await assert.rejects(() => eslint.lintText("var a = 0", { warnIgnored: "" }), /'options.warnIgnored' must be a boolean or undefined/u);
});
it("should work with config file that exports a promise", async () => {
eslint = new FlatESLint({
cwd: getFixturePath("promise-config")
});
const results = await eslint.lintText('var foo = "bar";');
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 1);
assert.strictEqual(results[0].messages[0].severity, 2);
assert.strictEqual(results[0].messages[0].ruleId, "quotes");
});
});
describe("lintFiles()", () => {
/** @type {InstanceType<import("../../../lib/eslint").ESLint>} */
let eslint;
it("should use correct parser when custom parser is specified", async () => {
const filePath = path.resolve(__dirname, "../../fixtures/configurations/parser/custom.js");
eslint = new FlatESLint({
cwd: originalDir,
ignore: false,
overrideConfigFile: true,
overrideConfig: {
languageOptions: {
parser: require(filePath)
}
}
});
const results = await eslint.lintFiles([filePath]);
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 1);
assert.strictEqual(results[0].messages[0].message, "Parsing error: Boom!");
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should report zero messages when given a config file and a valid file", async () => {
eslint = new FlatESLint({
cwd: originalDir,
overrideConfigFile: "tests/fixtures/simple-valid-project/eslint.config.js"
});
const results = await eslint.lintFiles(["tests/fixtures/simple-valid-project/**/foo*.js"]);
assert.strictEqual(results.length, 2);
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[1].messages.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should handle multiple patterns with overlapping files", async () => {
eslint = new FlatESLint({
cwd: originalDir,
overrideConfigFile: "tests/fixtures/simple-valid-project/eslint.config.js"
});
const results = await eslint.lintFiles([
"tests/fixtures/simple-valid-project/**/foo*.js",
"tests/fixtures/simple-valid-project/foo.?s",
"tests/fixtures/simple-valid-project/{foo,src/foobar}.js"
]);
assert.strictEqual(results.length, 2);
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[1].messages.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should report zero messages when given a config file and a valid file and espree as parser", async () => {
eslint = new FlatESLint({
overrideConfig: {
languageOptions: {
parser: require("espree"),
parserOptions: {
ecmaVersion: 2021
}
}
},
overrideConfigFile: true
});
const results = await eslint.lintFiles(["lib/cli.js"]);
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should report zero messages when given a config file and a valid file and esprima as parser", async () => {
eslint = new FlatESLint({
overrideConfig: {
languageOptions: {
parser: require("esprima")
}
},
overrideConfigFile: true,
ignore: false
});
const results = await eslint.lintFiles(["tests/fixtures/passing.js"]);
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should throw if eslint.config.js file is not present", async () => {
eslint = new FlatESLint({
cwd: getFixturePath("..")
});
await assert.rejects(() => eslint.lintFiles("fixtures/undef*.js"), /Could not find config file/u);
});
it("should not throw if eslint.config.js file is not present and overrideConfigFile is `true`", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(".."),
overrideConfigFile: true
});
await eslint.lintFiles("fixtures/undef*.js");
});
it("should not throw if eslint.config.js file is not present and overrideConfigFile is path to a config file", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(".."),
overrideConfigFile: "fixtures/configurations/quotes-error.js"
});
await eslint.lintFiles("fixtures/undef*.js");
});
it("should throw if overrideConfigFile is path to a file that doesn't exist", async () => {
eslint = new FlatESLint({
cwd: getFixturePath(),
overrideConfigFile: "does-not-exist.js"
});
await assert.rejects(() => eslint.lintFiles("undef*.js"), { code: "ENOENT" });
});
it("should throw an error when given a config file and a valid file and invalid parser", async () => {
eslint = new FlatESLint({
overrideConfig: {
languageOptions: {
parser: "test11"
}
},
overrideConfigFile: true
});
await assert.rejects(async () => await eslint.lintFiles(["lib/cli.js"]), /Expected object with parse\(\) or parseForESLint\(\) method/u);
});
it("should report zero messages when given a directory with a .js2 file", async () => {
eslint = new FlatESLint({
cwd: path.join(fixtureDir, ".."),
overrideConfigFile: getFixturePath("eslint.config.js"),
overrideConfig: {
files: ["**/*.js2"]
}
});
const results = await eslint.lintFiles([getFixturePath("files/foo.js2")]);
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
it("should report zero messages when given a directory with a .js and a .js2 file", async () => {
eslint = new FlatESLint({
ignore: false,
cwd: getFixturePath(".."),
overrideConfig: { files: ["**/*.js", "**/*.js2"] },
overrideConfigFile: getFixturePath("eslint.config.js")
});
const results = await eslint.lintFiles(["fixtures/files/"]);
assert.strictEqual(results.length, 3);
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[1].messages.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
// https://github.com/eslint/eslint/issues/16413
it("should find files and report zero messages when given a parent directory with a .js", async () => {
eslint = new FlatESLint({
ignore: false,
cwd: getFixturePath("example-app/subdir")
});
const results = await eslint.lintFiles(["../*.js"]);
assert.strictEqual(results.length, 2);
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[0].suppressedMessages.length, 0);
assert.strictEqual(results[1].messages.length, 0);
assert.strictEqual(results[1].suppressedMessages.length, 0);
});
// https://github.com/eslint/eslint/issues/16038
it("should allow files patterns with '..' inside", async () => {
eslint = new FlatESLint({
ignore: false,
cwd: getFixturePath("dots-in-files")
});
const results = await eslint.lintFiles(["."]);
assert.strictEqual(results.length, 2);
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[0].filePath, getFixturePath("dots-in-files/a..b.js"));
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
// https://github.com/eslint/eslint/issues/16299
it("should only find files in the subdir1 directory when given a directory name", async () => {
eslint = new FlatESLint({
ignore: false,
cwd: getFixturePath("example-app2")
});
const results = await eslint.lintFiles(["subdir1"]);
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 0);
assert.strictEqual(results[0].filePath, getFixturePath("example-app2/subdir1/a.js"));
assert.strictEqual(results[0].suppressedMessages.length, 0);
});
// https://github.com/eslint/eslint/issues/14742
it("should run", async () => {
eslint = new FlatESLint({
cwd: getFixturePath("{curly-path}", "server")
});
const results = await eslint.lintFiles(["src/**/*.{js,json}"]);
assert.strictEqual(results.length, 1);
assert.strictEqual(results[0].messages.length, 1);
assert.strictEqual(results[0].messages[0].ruleId, "no-console");
assert.strictEqual(
results[0].filePath,