-
Notifications
You must be signed in to change notification settings - Fork 342
/
eslintServer.ts
2396 lines (2143 loc) · 78.8 KB
/
eslintServer.ts
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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
import * as path from 'path';
import * as fs from 'fs';
import * as crypto from 'crypto';
import { execSync } from 'child_process';
import { EOL } from 'os';
import {
createConnection, Connection, ResponseError, RequestType, NotificationType, RequestHandler, NotificationHandler,
Diagnostic, DiagnosticSeverity, Range, Files, CancellationToken, TextDocuments, TextDocumentSyncKind, TextEdit,
TextDocumentIdentifier, Command, WorkspaceChange, CodeActionRequest, VersionedTextDocumentIdentifier,
ExecuteCommandRequest, DidChangeWatchedFilesNotification, DidChangeConfigurationNotification, WorkspaceFolder,
DidChangeWorkspaceFoldersNotification, CodeAction, CodeActionKind, Position, DocumentFormattingRequest,
DocumentFormattingRegistrationOptions, Disposable, DocumentFilter, TextDocumentEdit, LSPErrorCodes, DiagnosticTag, NotificationType0,
Message as LMessage, RequestMessage as LRequestMessage, ResponseMessage as LResponseMessage, uinteger
} from 'vscode-languageserver/node';
import {
TextDocument
} from 'vscode-languageserver-textdocument';
import { URI } from 'vscode-uri';
import { stringDiff } from './diff';
import { LRUCache } from './linkedMap';
namespace Is {
const toString = Object.prototype.toString;
export function boolean(value: any): value is boolean {
return value === true || value === false;
}
export function nullOrUndefined(value: any): value is null | undefined {
return value === null || value === undefined;
}
export function string(value: any): value is string {
return toString.call(value) === '[object String]';
}
}
namespace CommandIds {
export const applySingleFix: string = 'eslint.applySingleFix';
export const applySuggestion: string = 'eslint.applySuggestion';
export const applySameFixes: string = 'eslint.applySameFixes';
export const applyAllFixes: string = 'eslint.applyAllFixes';
export const applyDisableLine: string = 'eslint.applyDisableLine';
export const applyDisableFile: string = 'eslint.applyDisableFile';
export const openRuleDoc: string = 'eslint.openRuleDoc';
}
interface ESLintError extends Error {
messageTemplate?: string;
messageData?: {
pluginName?: string;
};
}
enum Status {
ok = 1,
warn = 2,
error = 3
}
interface StatusParams {
uri: string;
state: Status;
}
namespace StatusNotification {
export const type = new NotificationType<StatusParams>('eslint/status');
}
interface NoConfigParams {
message: string;
document: TextDocumentIdentifier;
}
interface NoConfigResult {
}
namespace NoConfigRequest {
export const type = new RequestType<NoConfigParams, NoConfigResult, void>('eslint/noConfig');
}
interface NoESLintLibraryParams {
source: TextDocumentIdentifier;
}
interface NoESLintLibraryResult {
}
namespace NoESLintLibraryRequest {
export const type = new RequestType<NoESLintLibraryParams, NoESLintLibraryResult, void>('eslint/noLibrary');
}
interface OpenESLintDocParams {
url: string;
}
interface OpenESLintDocResult {
}
namespace OpenESLintDocRequest {
export const type = new RequestType<OpenESLintDocParams, OpenESLintDocResult, void>('eslint/openDoc');
}
interface ProbeFailedParams {
textDocument: TextDocumentIdentifier;
}
namespace ProbeFailedRequest {
export const type = new RequestType<ProbeFailedParams, void, void>('eslint/probeFailed');
}
namespace ShowOutputChannel {
export const type = new NotificationType0('eslint/showOutputChannel');
}
type RunValues = 'onType' | 'onSave';
enum ModeEnum {
auto = 'auto',
location = 'location'
}
namespace ModeEnum {
export function is(value: string): value is ModeEnum {
return value === ModeEnum.auto || value === ModeEnum.location;
}
}
interface ModeItem {
mode: ModeEnum
}
namespace ModeItem {
export function is(item: any): item is ModeItem {
const candidate = item as ModeItem;
return candidate && ModeEnum.is(candidate.mode);
}
}
interface DirectoryItem {
directory: string;
'!cwd'?: boolean;
}
namespace DirectoryItem {
export function is(item: any): item is DirectoryItem {
const candidate = item as DirectoryItem;
return candidate && Is.string(candidate.directory) && (Is.boolean(candidate['!cwd']) || candidate['!cwd'] === undefined);
}
}
interface CodeActionSettings {
disableRuleComment: {
enable: boolean;
location: 'separateLine' | 'sameLine';
};
showDocumentation: {
enable: boolean;
};
}
type PackageManagers = 'npm' | 'yarn' | 'pnpm';
type ESLintOptions = object & { fixTypes?: string[] };
enum Validate {
on = 'on',
off = 'off',
probe = 'probe'
}
enum ESLintSeverity {
off = 'off',
warn = 'warn',
error = 'error'
}
enum CodeActionsOnSaveMode {
all = 'all',
problems = 'problems'
}
interface CodeActionsOnSaveSettings {
enable: boolean;
mode: CodeActionsOnSaveMode;
rules?: string[];
}
enum RuleSeverity {
// Original ESLint values
info = 'info',
warn = 'warn',
error = 'error',
// Added severity override changes
off = 'off',
default = 'default',
downgrade = 'downgrade',
upgrade = 'upgrade'
}
interface RuleCustomization {
rule: string;
severity: RuleSeverity;
}
interface CommonSettings {
validate: Validate;
packageManager: 'npm' | 'yarn' | 'pnpm';
useESLintClass: boolean;
codeAction: CodeActionSettings;
codeActionOnSave: CodeActionsOnSaveSettings;
format: boolean;
quiet: boolean;
onIgnoredFiles: ESLintSeverity;
options: ESLintOptions | undefined;
rulesCustomizations: RuleCustomization[];
run: RunValues;
nodePath: string | null;
workspaceFolder: WorkspaceFolder | undefined;
}
interface ConfigurationSettings extends CommonSettings {
workingDirectory: ModeItem | DirectoryItem | undefined;
}
interface TextDocumentSettings extends CommonSettings {
silent: boolean;
workingDirectory: DirectoryItem | undefined;
library: ESLintModule | undefined;
resolvedGlobalPackageManagerPath: string | undefined;
}
namespace TextDocumentSettings {
export function hasLibrary(settings: TextDocumentSettings): settings is (TextDocumentSettings & { library: ESLintModule }) {
return settings.library !== undefined;
}
}
interface ESLintAutoFixEdit {
range: [number, number];
text: string;
}
interface ESLintSuggestionResult {
desc: string;
fix: ESLintAutoFixEdit;
}
interface ESLintProblem {
line: number;
column: number;
endLine?: number;
endColumn?: number;
severity: number;
ruleId: string;
message: string;
fix?: ESLintAutoFixEdit;
suggestions?: ESLintSuggestionResult[]
}
interface ESLintDocumentReport {
filePath: string;
errorCount: number;
warningCount: number;
messages: ESLintProblem[];
output?: string;
}
interface ESLintReport {
errorCount: number;
warningCount: number;
results: ESLintDocumentReport[];
}
interface CLIOptions {
cwd?: string;
fixTypes?: string[];
fix?: boolean;
}
type SeverityConf = 0 | 1 | 2 | 'off' | 'warn' | 'error';
type RuleConf = SeverityConf | [SeverityConf, ...any[]];
type ConfigData = {
rules?: Record<string, RuleConf>;
};
interface ESLintClassOptions {
cwd?: string;
fixTypes?: string[];
fix?: boolean;
overrideConfig?: ConfigData;
}
type RuleMetaData = {
docs?: {
url?: string;
};
type?: string;
};
// { meta: { docs: [Object], schema: [Array] }, create: [Function: create] }
type RuleData = {
meta?: RuleMetaData;
};
namespace RuleData {
export function hasMetaType(value: RuleMetaData | undefined): value is RuleMetaData & { type: string; } {
return value !== undefined && value.type !== undefined;
}
}
interface ParserOptions {
parser?: string;
}
interface ESLintConfig {
env: Record<string, boolean>;
extends: string | string[];
// globals: Record<string, GlobalConf>;
ignorePatterns: string | string[];
noInlineConfig: boolean;
// overrides: OverrideConfigData[];
parser: string | null;
parserOptions?: ParserOptions;
plugins: string[];
processor: string;
reportUnusedDisableDirectives: boolean | undefined;
root: boolean;
rules: Record<string, RuleConf>;
settings: object;
}
interface ESLintClass {
// https://eslint.org/docs/developer-guide/nodejs-api#-eslintlinttextcode-options
lintText(content: string, options: {filePath?: string, warnIgnored?: boolean}): Promise<ESLintDocumentReport[]>;
// https://eslint.org/docs/developer-guide/nodejs-api#-eslintispathignoredfilepath
isPathIgnored(path: string): Promise<boolean>;
// https://eslint.org/docs/developer-guide/nodejs-api#-eslintgetrulesmetaforresultsresults
getRulesMetaForResults?(results: ESLintDocumentReport[]): Record<string, RuleMetaData> | undefined /* for ESLintClassEmulator */;
// https://eslint.org/docs/developer-guide/nodejs-api#-eslintcalculateconfigforfilefilepath
calculateConfigForFile(path: string): Promise<ESLintConfig | undefined /* for ESLintClassEmulator */>;
// Whether it is the old CLI Engine
isCLIEngine?: boolean;
}
interface ESLintClassConstructor {
new(options: ESLintClassOptions): ESLintClass;
}
interface CLIEngineConstructor {
new(options: CLIOptions): CLIEngine;
}
type ESLintModule =
{
// version < 7.0
ESLint: undefined;
CLIEngine: CLIEngineConstructor;
} | {
// 7.0 <= version < 8.0
ESLint: ESLintClassConstructor;
CLIEngine: CLIEngineConstructor;
} | {
// 8.0 <= version.
ESLint: ESLintClassConstructor;
CLIEngine: undefined;
};
namespace ESLintModule {
export function hasESLintClass(value: ESLintModule): value is { ESLint: ESLintClassConstructor; CLIEngine: CLIEngineConstructor | undefined;} {
return value.ESLint !== undefined;
}
export function hasCLIEngine(value: ESLintModule): value is { CLIEngine: CLIEngineConstructor; ESLint: ESLintClassConstructor | undefined; } {
return value.CLIEngine !== undefined;
}
}
namespace ESLintClass {
export function newESLintClass(library: ESLintModule, newOptions: ESLintClassOptions | CLIOptions, useESLintClass: boolean): ESLintClass {
if (ESLintModule.hasESLintClass(library) && useESLintClass) {
return new library.ESLint(newOptions);
}
if (ESLintModule.hasCLIEngine(library)) {
return new ESLintClassEmulator(new library.CLIEngine(newOptions));
}
return new library.ESLint(newOptions);
}
}
interface CLIEngine {
executeOnText(content: string, file?: string, warn?: boolean): ESLintReport;
isPathIgnored(path: string): boolean;
// This is only available from v4.15.0 forward
getRules?(): Map<string, RuleData>;
getConfigForFile?(path: string): ESLintConfig;
}
namespace CLIEngine {
export function hasRule(value: CLIEngine): value is CLIEngine & { getRules(): Map<string, RuleData> } {
return value.getRules !== undefined;
}
}
/**
* ESLint class emulator using CLI Engine.
*/
class ESLintClassEmulator implements ESLintClass {
private cli: CLIEngine;
constructor(cli: CLIEngine) {
this.cli = cli;
}
get isCLIEngine(): boolean {
return true;
}
async lintText(content: string, options: { filePath?: string | undefined; warnIgnored?: boolean | undefined; }): Promise<ESLintDocumentReport[]> {
return this.cli.executeOnText(content, options.filePath, options.warnIgnored).results;
}
async isPathIgnored(path: string): Promise<boolean> {
return this.cli.isPathIgnored(path);
}
getRulesMetaForResults(_results: ESLintDocumentReport[]): Record<string, RuleMetaData> | undefined {
if (!CLIEngine.hasRule(this.cli)) {
return undefined;
}
const rules: Record<string, RuleMetaData> = {};
for (const [name, rule] of this.cli.getRules()) {
if (rule.meta !== undefined) {
rules[name] = rule.meta;
}
}
return rules;
}
async calculateConfigForFile(path: string): Promise<ESLintConfig | undefined> {
return typeof this.cli.getConfigForFile === 'function' ? this.cli.getConfigForFile(path) : undefined;
}
}
namespace RuleMetaData {
const handled: Set<string> = new Set();
const ruleId2Meta: Map<string, RuleMetaData> = new Map();
export function capture(eslint: ESLintClass, reports: ESLintDocumentReport[]): void {
let rulesMetaData: Record<string, RuleMetaData> | undefined;
if (eslint.isCLIEngine) {
const toHandle = reports.filter(report => !handled.has(report.filePath));
if (toHandle.length === 0) {
return;
}
rulesMetaData = typeof eslint.getRulesMetaForResults === 'function' ? eslint.getRulesMetaForResults(toHandle) : undefined;
toHandle.forEach(report => handled.add(report.filePath));
} else {
rulesMetaData = typeof eslint.getRulesMetaForResults === 'function' ? eslint.getRulesMetaForResults(reports) : undefined;
}
if (rulesMetaData === undefined) {
return undefined;
}
Object.entries(rulesMetaData).forEach(([key, meta]) => {
if (ruleId2Meta.has(key)) {
return;
}
if (meta && meta.docs && Is.string(meta.docs.url)) {
ruleId2Meta.set(key, meta);
}
});
}
export function clear(): void {
handled.clear();
ruleId2Meta.clear();
}
export function getUrl(ruleId: string): string | undefined {
return ruleId2Meta.get(ruleId)?.docs?.url;
}
export function getType(ruleId: string): string | undefined {
return ruleId2Meta.get(ruleId)?.type;
}
export function hasRuleId(ruleId: string): boolean {
return ruleId2Meta.has(ruleId);
}
}
declare const __webpack_require__: typeof require;
declare const __non_webpack_require__: typeof require;
function loadNodeModule<T>(moduleName: string): T | undefined {
const r = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require;
try {
return r(moduleName);
} catch (err: any) {
if (err.stack) {
connection.console.error(err.stack.toString());
}
}
return undefined;
}
const ruleSeverityCache = new LRUCache<string, RuleSeverity | null>(1024);
function asteriskMatches(matcher: string, ruleId: string): boolean {
return matcher.startsWith('!')
? !(new RegExp(`^${matcher.slice(1).replace(/\*/g, '.*')}$`, 'g').test(ruleId))
: new RegExp(`^${matcher.replace(/\*/g, '.*')}$`, 'g').test(ruleId);
}
function getSeverityOverride(ruleId: string, customizations: RuleCustomization[]): RuleSeverity | undefined {
let result: RuleSeverity | undefined | null = ruleSeverityCache.get(ruleId);
if (result === null) {
return undefined;
}
if (result !== undefined) {
return result;
}
for (const customization of customizations) {
if (asteriskMatches(customization.rule, ruleId)) {
result = customization.severity;
}
}
if (result === undefined) {
ruleSeverityCache.set(ruleId, null);
return undefined;
}
ruleSeverityCache.set(ruleId, result);
return result;
}
type SaveRuleConfigItem = { offRules: Set<string>, onRules: Set<string>};
const saveRuleConfigCache = new LRUCache<string, SaveRuleConfigItem | null>(128);
function isOff(ruleId: string, matchers: string[]): boolean {
for (const matcher of matchers) {
if (matcher.startsWith('!') && new RegExp(`^${matcher.slice(1).replace(/\*/g, '.*')}$`, 'g').test(ruleId)) {
return true;
} else if (new RegExp(`^${matcher.replace(/\*/g, '.*')}$`, 'g').test(ruleId)) {
return false;
}
}
return true;
}
async function getSaveRuleConfig(uri: string, settings: TextDocumentSettings & { library: ESLintModule }): Promise<SaveRuleConfigItem | undefined> {
const filePath = getFilePath(uri);
let result = saveRuleConfigCache.get(uri);
if (filePath === undefined || result === null) {
return undefined;
}
if (result !== undefined) {
return result;
}
const rules = settings.codeActionOnSave.rules;
result = await withESLintClass(async (eslint) => {
if (rules === undefined || eslint.isCLIEngine) {
return undefined;
}
const config = await eslint.calculateConfigForFile(filePath);
if (config === undefined || config.rules === undefined || config.rules.length === 0) {
return undefined;
}
const offRules: Set<string> = new Set();
const onRules: Set<string> = new Set();
if (rules.length === 0) {
Object.keys(config.rules).forEach(ruleId => offRules.add(ruleId));
} else {
for (const ruleId of Object.keys(config.rules)) {
if (isOff(ruleId, rules)) {
offRules.add(ruleId);
} else {
onRules.add(ruleId);
}
}
}
return offRules.size > 0 ? { offRules, onRules } : undefined;
}, settings);
if (result === undefined || result === null) {
saveRuleConfigCache.set(uri, null);
return undefined;
} else {
saveRuleConfigCache.set(uri, result);
return result;
}
}
function makeDiagnostic(settings: TextDocumentSettings, problem: ESLintProblem): [Diagnostic, RuleSeverity | undefined] {
const message = problem.message;
const startLine = Is.nullOrUndefined(problem.line) ? 0 : Math.max(0, problem.line - 1);
const startChar = Is.nullOrUndefined(problem.column) ? 0 : Math.max(0, problem.column - 1);
const endLine = Is.nullOrUndefined(problem.endLine) ? startLine : Math.max(0, problem.endLine - 1);
const endChar = Is.nullOrUndefined(problem.endColumn) ? startChar : Math.max(0, problem.endColumn - 1);
const override = getSeverityOverride(problem.ruleId, settings.rulesCustomizations);
const result: Diagnostic = {
message: message,
severity: convertSeverityToDiagnosticWithOverride(problem.severity, override),
source: 'eslint',
range: {
start: { line: startLine, character: startChar },
end: { line: endLine, character: endChar }
}
};
if (problem.ruleId) {
const url = RuleMetaData.getUrl(problem.ruleId);
result.code = problem.ruleId;
if (url !== undefined) {
result.codeDescription = {
href: url
};
}
if (problem.ruleId === 'no-unused-vars') {
result.tags = [DiagnosticTag.Unnecessary];
}
}
return [result, override];
}
interface Problem {
label: string;
documentVersion: number;
ruleId: string;
line: number;
diagnostic: Diagnostic;
edit?: ESLintAutoFixEdit;
suggestions?: ESLintSuggestionResult[];
}
namespace Problem {
export function isFixable(problem: Problem): problem is FixableProblem {
return problem.edit !== undefined;
}
export function hasSuggestions(problem: Problem): problem is SuggestionsProblem {
return problem.suggestions !== undefined;
}
}
interface FixableProblem extends Problem {
edit: ESLintAutoFixEdit;
}
namespace FixableProblem {
export function createTextEdit(document: TextDocument, editInfo: FixableProblem): TextEdit {
return TextEdit.replace(Range.create(document.positionAt(editInfo.edit.range[0]), document.positionAt(editInfo.edit.range[1])), editInfo.edit.text || '');
}
}
interface SuggestionsProblem extends Problem {
suggestions: ESLintSuggestionResult[];
}
namespace SuggestionsProblem {
export function createTextEdit(document: TextDocument, suggestion: ESLintSuggestionResult): TextEdit {
return TextEdit.replace(Range.create(document.positionAt(suggestion.fix.range[0]), document.positionAt(suggestion.fix.range[1])), suggestion.fix.text || '');
}
}
function computeKey(diagnostic: Diagnostic): string {
const range = diagnostic.range;
let message: string | undefined;
if (diagnostic.message) {
const hash = crypto.createHash('md5');
hash.update(diagnostic.message);
message = hash.digest('base64');
}
return `[${range.start.line},${range.start.character},${range.end.line},${range.end.character}]-${diagnostic.code}-${message ?? ''}`;
}
const codeActions: Map<string, Map<string, Problem>> = new Map<string, Map<string, Problem>>();
function recordCodeAction(document: TextDocument, diagnostic: Diagnostic, problem: ESLintProblem): void {
if (!problem.ruleId) {
return;
}
const uri = document.uri;
let edits: Map<string, Problem> | undefined = codeActions.get(uri);
if (edits === undefined) {
edits = new Map<string, Problem>();
codeActions.set(uri, edits);
}
edits.set(computeKey(diagnostic), {
label: `Fix this ${problem.ruleId} problem`,
documentVersion: document.version,
ruleId: problem.ruleId,
line: problem.line,
diagnostic: diagnostic,
edit: problem.fix,
suggestions: problem.suggestions
});
}
function adjustSeverityForOverride(severity: number | RuleSeverity, severityOverride?: RuleSeverity) {
switch (severityOverride) {
case RuleSeverity.off:
case RuleSeverity.info:
case RuleSeverity.warn:
case RuleSeverity.error:
return severityOverride;
case RuleSeverity.downgrade:
switch (convertSeverityToDiagnostic(severity)) {
case DiagnosticSeverity.Error:
return RuleSeverity.warn;
case DiagnosticSeverity.Warning:
case DiagnosticSeverity.Information:
return RuleSeverity.info;
}
case RuleSeverity.upgrade:
switch (convertSeverityToDiagnostic(severity)) {
case DiagnosticSeverity.Information:
return RuleSeverity.warn;
case DiagnosticSeverity.Warning:
case DiagnosticSeverity.Error:
return RuleSeverity.error;
}
default:
return severity;
}
}
function convertSeverityToDiagnostic(severity: number | RuleSeverity) {
// RuleSeverity concerns an overridden rule. A number is direct from ESLint.
switch (severity) {
// Eslint 1 is warning
case 1:
case RuleSeverity.warn:
return DiagnosticSeverity.Warning;
case 2:
case RuleSeverity.error:
return DiagnosticSeverity.Error;
case RuleSeverity.info:
return DiagnosticSeverity.Information;
default:
return DiagnosticSeverity.Error;
}
}
function convertSeverityToDiagnosticWithOverride(severity: number | RuleSeverity, severityOverride: RuleSeverity | undefined): DiagnosticSeverity {
return convertSeverityToDiagnostic(adjustSeverityForOverride(severity, severityOverride));
}
const enum CharCode {
/**
* The `\` character.
*/
Backslash = 92,
}
/**
* Check if the path follows this pattern: `\\hostname\sharename`.
*
* @see https://msdn.microsoft.com/en-us/library/gg465305.aspx
* @return A boolean indication if the path is a UNC path, on none-windows
* always false.
*/
function isUNC(path: string): boolean {
if (process.platform !== 'win32') {
// UNC is a windows concept
return false;
}
if (!path || path.length < 5) {
// at least \\a\b
return false;
}
let code = path.charCodeAt(0);
if (code !== CharCode.Backslash) {
return false;
}
code = path.charCodeAt(1);
if (code !== CharCode.Backslash) {
return false;
}
let pos = 2;
const start = pos;
for (; pos < path.length; pos++) {
code = path.charCodeAt(pos);
if (code === CharCode.Backslash) {
break;
}
}
if (start === pos) {
return false;
}
code = path.charCodeAt(pos + 1);
if (isNaN(code) || code === CharCode.Backslash) {
return false;
}
return true;
}
function normalizeDriveLetter(path: string): string {
if (process.platform !== 'win32' || path.length < 2 || path[1] !== ':') {
return path;
}
return path[0].toUpperCase() + path.substr(1);
}
function getFileSystemPath(uri: URI): string {
let result = uri.fsPath;
if (process.platform === 'win32' && result.length >= 2 && result[1] === ':') {
// Node by default uses an upper case drive letter and ESLint uses
// === to compare paths which results in the equal check failing
// if the drive letter is lower case in th URI. Ensure upper case.
result = result[0].toUpperCase() + result.substr(1);
}
if (process.platform === 'win32' || process.platform === 'darwin') {
const realpath = fs.realpathSync.native(result);
// Only use the real path if only the casing has changed.
if (realpath.toLowerCase() === result.toLowerCase()) {
result = realpath;
}
}
return result;
}
function normalizePath(path: string): string;
function normalizePath(path: undefined): undefined;
function normalizePath(path: string | undefined): string | undefined {
if (path === undefined) {
return undefined;
}
if (process.platform === 'win32') {
return path.replace(/\\/g, '/');
}
return path;
}
function getUri(documentOrUri: string | TextDocument | URI): URI {
return Is.string(documentOrUri)
? URI.parse(documentOrUri)
: documentOrUri instanceof URI
? documentOrUri
: URI.parse(documentOrUri.uri);
}
function getFilePath(documentOrUri: string | TextDocument | URI | undefined): string | undefined {
if (!documentOrUri) {
return undefined;
}
const uri = getUri(documentOrUri);
if (uri.scheme !== 'file') {
return undefined;
}
return getFileSystemPath(uri);
}
const exitCalled = new NotificationType<[number, string]>('eslint/exitCalled');
const nodeExit = process.exit;
process.exit = ((code?: number): void => {
const stack = new Error('stack');
connection.sendNotification(exitCalled, [code ? code : 0, stack.stack]);
setTimeout(() => {
nodeExit(code);
}, 1000);
}) as any;
process.on('uncaughtException', (error: any) => {
let message: string | undefined;
if (error) {
if (typeof error.stack === 'string') {
message = error.stack;
} else if (typeof error.message === 'string') {
message = error.message;
} else if (typeof error === 'string') {
message = error;
}
if (message === undefined || message.length === 0) {
try {
message = JSON.stringify(error, undefined, 4);
} catch (e) {
// Should not happen.
}
}
}
// eslint-disable-next-line no-console
console.error('Uncaught exception received.');
if (message) {
// eslint-disable-next-line no-console
console.error(message);
}
});
function isRequestMessage(message: LMessage | undefined): message is LRequestMessage {
const candidate = <LRequestMessage>message;
return candidate && typeof candidate.method === 'string' && (typeof candidate.id === 'string' || typeof candidate.id === 'number');
}
const connection = createConnection({
cancelUndispatched: (message: LMessage) => {
// Code actions can savely be cancel on request.
if (isRequestMessage(message) && message.method === 'textDocument/codeAction') {
const response: LResponseMessage = {
jsonrpc: message.jsonrpc,
id: message.id,
result: null
};
return response;
}
return undefined;
}
});
connection.console.info(`ESLint server running in node ${process.version}`);
// Is instantiated in the initialize handle;
let documents!: TextDocuments<TextDocument>;
const _globalPaths: Record<string, { cache: string | undefined; get(): string | undefined; }> = {
yarn: {
cache: undefined,
get(): string | undefined {
return Files.resolveGlobalYarnPath(trace);
}
},
npm: {
cache: undefined,
get(): string | undefined {
return Files.resolveGlobalNodePath(trace);
}
},
pnpm: {
cache: undefined,
get(): string {
const pnpmPath = execSync('pnpm root -g').toString().trim();
return pnpmPath;
}
}
};
function globalPathGet(packageManager: PackageManagers): string | undefined {
const pm = _globalPaths[packageManager];
if (pm) {
if (pm.cache === undefined) {
pm.cache = pm.get();
}
return pm.cache;
}
return undefined;
}
type LanguageConfig = {
ext: string;
lineComment: string;
blockComment: [string, string];
};
const languageId2Config: Map<string, LanguageConfig> = new Map([
['javascript', { ext: 'js', lineComment: '//', blockComment: ['/*', '*/'] }],
['javascriptreact', { ext: 'jsx', lineComment: '//', blockComment: ['/*', '*/'] }],
['typescript', { ext: 'ts', lineComment: '//', blockComment: ['/*', '*/'] } ],
['typescriptreact', { ext: 'tsx', lineComment: '//', blockComment: ['/*', '*/'] } ],
['html', { ext: 'html', lineComment: '//', blockComment: ['/*', '*/'] }],
['vue', { ext: 'vue', lineComment: '//', blockComment: ['/*', '*/'] }],
['coffeescript', { ext: 'coffee', lineComment: '#', blockComment: ['###', '###'] }],
['yaml', { ext: 'yaml', lineComment: '#', blockComment: ['#', ''] }],
['graphql', { ext: 'graphql', lineComment: '#', blockComment: ['#', ''] }]
]);
function getLineComment(languageId: string): string {
return languageId2Config.get(languageId)?.lineComment ?? '//';
}
function getBlockComment(languageId: string): [string, string] {
return languageId2Config.get(languageId)?.blockComment ?? ['/**', '*/'];
}
const languageId2ParserRegExp: Map<string, RegExp[]> = function createLanguageId2ParserRegExp() {
const result = new Map<string, RegExp[]>();
const typescript = /\/@typescript-eslint\/parser\//;
const babelESLint = /\/babel-eslint\/lib\/index.js$/;
result.set('typescript', [typescript, babelESLint]);
result.set('typescriptreact', [typescript, babelESLint]);
const angular = /\/@angular-eslint\/template-parser\//;
result.set('html', [angular]);
return result;
}();
const languageId2ParserOptions: Map<string, { regExps: RegExp[]; parsers: Set<string>; parserRegExps?: RegExp[] }> = function createLanguageId2ParserOptionsRegExp() {
const result = new Map<string, { regExps: RegExp[]; parsers: Set<string>; parserRegExps?: RegExp[] }>();
const vue = /vue-eslint-parser\/.*\.js$/;
const typescriptEslintParser = /@typescript-eslint\/parser\/.*\.js$/;
result.set('typescript', { regExps: [vue], parsers: new Set<string>(['@typescript-eslint/parser']), parserRegExps: [typescriptEslintParser] });
return result;