forked from 0no-co/GraphQLSP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiagnostics.ts
More file actions
574 lines (524 loc) · 17.6 KB
/
diagnostics.ts
File metadata and controls
574 lines (524 loc) · 17.6 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
import { ts } from './ts';
import { Diagnostic, getDiagnostics } from 'graphql-language-service';
import {
FragmentDefinitionNode,
Kind,
OperationDefinitionNode,
parse,
visit,
} from 'graphql';
import { LRUCache } from 'lru-cache';
import fnv1a from '@sindresorhus/fnv1a';
import { print } from '@0no-co/graphql.web';
import {
findAllCallExpressions,
findAllPersistedCallExpressions,
findAllTaggedTemplateNodes,
findAllMaskFragmentsCalls,
getSource,
unrollFragment,
} from './ast';
import { resolveTemplate } from './ast/resolve';
import { UNUSED_FIELD_CODE, checkFieldUsageInFile } from './fieldUsage';
import {
MISSING_FRAGMENT_CODE,
getColocatedFragmentNames,
} from './checkImports';
import {
generateHashForDocument,
getDocumentReferenceFromDocumentNode,
getDocumentReferenceFromTypeQuery,
} from './persisted';
import { SchemaRef } from './graphql/getSchema';
const BASE_CLIENT_DIRECTIVES = new Set([
'populate',
'client',
'unmask',
'_unmask',
'_optional',
'_relayPagination',
'_simplePagination',
'_required',
'optional',
'required',
'arguments',
'argumentDefinitions',
'connection',
'refetchable',
'relay',
'required',
'inline',
]);
export const SEMANTIC_DIAGNOSTIC_CODE = 52001;
export const USING_DEPRECATED_FIELD_CODE = 52004;
export const MISSING_PERSISTED_TYPE_ARG = 520100;
export const MISSING_PERSISTED_CODE_ARG = 520101;
export const MISSING_PERSISTED_DOCUMENT = 520102;
export const MISSMATCH_HASH_TO_DOCUMENT = 520103;
export const ALL_DIAGNOSTICS = [
SEMANTIC_DIAGNOSTIC_CODE,
USING_DEPRECATED_FIELD_CODE,
MISSING_FRAGMENT_CODE,
UNUSED_FIELD_CODE,
MISSING_PERSISTED_TYPE_ARG,
MISSING_PERSISTED_CODE_ARG,
MISSING_PERSISTED_DOCUMENT,
MISSMATCH_HASH_TO_DOCUMENT,
];
const cache = new LRUCache<number, ts.Diagnostic[]>({
// how long to live in ms
ttl: 1000 * 60 * 15,
max: 5000,
});
export function getGraphQLDiagnostics(
filename: string,
schema: SchemaRef,
info: ts.server.PluginCreateInfo
): ts.Diagnostic[] | undefined {
const isCallExpression = info.config.templateIsCallExpression ?? true;
let source = getSource(info, filename);
if (!source) return undefined;
let fragments: Array<FragmentDefinitionNode> = [],
nodes: {
node: ts.StringLiteralLike | ts.TaggedTemplateExpression;
schema: string | null;
}[];
if (isCallExpression) {
const result = findAllCallExpressions(source, info);
fragments = result.fragments;
nodes = result.nodes;
} else {
nodes = findAllTaggedTemplateNodes(source).map(x => ({
node: x,
schema: null,
}));
}
const texts = nodes.map(({ node }) => {
if (
(ts.isNoSubstitutionTemplateLiteral(node) ||
ts.isTemplateExpression(node)) &&
!isCallExpression
) {
if (ts.isTaggedTemplateExpression(node.parent)) {
node = node.parent;
} else {
return undefined;
}
}
return resolveTemplate(node, filename, info).combinedText;
});
const cacheKey = fnv1a(
isCallExpression
? source.getText() +
fragments.map(x => print(x)).join('-') +
schema.version
: texts.join('-') + schema.version
);
let tsDiagnostics: ts.Diagnostic[];
if (cache.has(cacheKey)) {
tsDiagnostics = cache.get(cacheKey)!;
} else {
tsDiagnostics = runDiagnostics(source, { nodes, fragments }, schema, info);
cache.set(cacheKey, tsDiagnostics);
}
const shouldCheckForColocatedFragments =
info.config.shouldCheckForColocatedFragments ?? true;
let fragmentDiagnostics: ts.Diagnostic[] = [];
if (isCallExpression) {
const persistedCalls = findAllPersistedCallExpressions(source, info);
// We need to check whether the user has correctly inserted a hash,
// by means of providing an argument to the function and that they
// are establishing a reference to the document by means of the generic.
const persistedDiagnostics = persistedCalls
.map<ts.Diagnostic | null>(found => {
const { node: callExpression } = found;
if (!callExpression.typeArguments && !callExpression.arguments[1]) {
return {
category: ts.DiagnosticCategory.Warning,
code: MISSING_PERSISTED_TYPE_ARG,
file: source,
messageText: 'Missing generic pointing at the GraphQL document.',
start: callExpression.getStart(),
length: callExpression.getEnd() - callExpression.getStart(),
};
}
let foundNode,
foundFilename = filename,
ref,
start,
length;
const typeQuery =
callExpression.typeArguments && callExpression.typeArguments[0];
if (typeQuery) {
start = typeQuery.getStart();
length = typeQuery.getEnd() - typeQuery.getStart();
if (!ts.isTypeQueryNode(typeQuery)) {
return {
category: ts.DiagnosticCategory.Warning,
code: MISSING_PERSISTED_TYPE_ARG,
file: source,
messageText:
'Provided generic should be a typeQueryNode in the shape of graphql.persisted<typeof document>.',
start,
length,
};
}
const { node: found, filename: fileName } =
getDocumentReferenceFromTypeQuery(typeQuery, filename, info);
foundNode = found;
foundFilename = fileName;
ref = typeQuery.getText();
} else if (callExpression.arguments[1]) {
start = callExpression.arguments[1].getStart();
length =
callExpression.arguments[1].getEnd() -
callExpression.arguments[1].getStart();
if (
!ts.isIdentifier(callExpression.arguments[1]) &&
!ts.isCallExpression(callExpression.arguments[1])
) {
return {
category: ts.DiagnosticCategory.Warning,
code: MISSING_PERSISTED_TYPE_ARG,
file: source,
messageText:
'Provided argument should be an identifier or invocation of "graphql" in the shape of graphql.persisted(hash, document).',
start,
length,
};
}
const { node: found, filename: fileName } =
getDocumentReferenceFromDocumentNode(
callExpression.arguments[1],
filename,
info
);
foundNode = found;
foundFilename = fileName;
ref = callExpression.arguments[1].getText();
}
if (!foundNode) {
return {
category: ts.DiagnosticCategory.Warning,
code: MISSING_PERSISTED_DOCUMENT,
file: source,
messageText: `Can't find reference to "${ref}".`,
start,
length,
};
}
const initializer = foundNode;
if (
!initializer ||
!ts.isCallExpression(initializer) ||
!initializer.arguments[0] ||
!ts.isStringLiteralLike(initializer.arguments[0])
) {
// TODO: we can make this check more stringent where we also parse and resolve
// the accompanying template.
return {
category: ts.DiagnosticCategory.Warning,
code: MISSING_PERSISTED_DOCUMENT,
file: source,
messageText: `Referenced type "${ref}" is not a GraphQL document.`,
start,
length,
};
}
if (!callExpression.arguments[0]) {
// TODO: this might be covered by the API enforcing the first
// argument so can possibly be removed.
return {
category: ts.DiagnosticCategory.Warning,
code: MISSING_PERSISTED_CODE_ARG,
file: source,
messageText: `The call-expression is missing a hash for the persisted argument.`,
start: callExpression.arguments.pos,
length: callExpression.arguments.end - callExpression.arguments.pos,
};
}
const hash = callExpression.arguments[0].getText().slice(1, -1);
if (hash.startsWith('sha256:')) {
const generatedHash = generateHashForDocument(
info,
initializer.arguments[0],
foundFilename,
initializer.arguments[1] &&
ts.isArrayLiteralExpression(initializer.arguments[1])
? initializer.arguments[1]
: undefined
);
if (!generatedHash) return null;
const upToDateHash = `sha256:${generatedHash}`;
if (upToDateHash !== hash) {
return {
category: ts.DiagnosticCategory.Warning,
code: MISSMATCH_HASH_TO_DOCUMENT,
file: source,
messageText: `The persisted document's hash is outdated`,
start: callExpression.arguments.pos,
length:
callExpression.arguments.end - callExpression.arguments.pos,
};
}
}
return null;
})
.filter(Boolean);
tsDiagnostics.push(...(persistedDiagnostics as ts.Diagnostic[]));
}
if (isCallExpression && shouldCheckForColocatedFragments) {
const moduleSpecifierToFragments = getColocatedFragmentNames(source, info);
const typeChecker = info.languageService.getProgram()?.getTypeChecker();
const usedFragments = new Set();
nodes.forEach(({ node }) => {
try {
const parsed = parse(node.getText().slice(1, -1), {
noLocation: true,
});
visit(parsed, {
FragmentSpread: node => {
usedFragments.add(node.name.value);
},
});
} catch (e) {}
});
// check for maskFragments() calls
const maskFragmentsCalls = findAllMaskFragmentsCalls(source);
maskFragmentsCalls.forEach(call => {
const firstArg = call.arguments[0];
if (!firstArg) return;
// Handle array of fragments: maskFragments([Fragment1, Fragment2], data)
if (ts.isArrayLiteralExpression(firstArg)) {
firstArg.elements.forEach(element => {
if (ts.isIdentifier(element)) {
const fragmentDefs = unrollFragment(element, info, typeChecker);
fragmentDefs.forEach(def => usedFragments.add(def.name.value));
}
});
}
});
Object.keys(moduleSpecifierToFragments).forEach(moduleSpecifier => {
const {
fragments: fragmentNames,
start,
length,
} = moduleSpecifierToFragments[moduleSpecifier]!;
const missingFragments = Array.from(
new Set(fragmentNames.filter(x => !usedFragments.has(x)))
);
if (missingFragments.length) {
fragmentDiagnostics.push({
file: source,
length,
start,
category: ts.DiagnosticCategory.Warning,
code: MISSING_FRAGMENT_CODE,
messageText: `Unused co-located fragment definition(s) "${missingFragments.join(
', '
)}" in ${moduleSpecifier}`,
});
}
});
return [...tsDiagnostics, ...fragmentDiagnostics];
} else {
return tsDiagnostics;
}
}
const runDiagnostics = (
source: ts.SourceFile,
{
nodes,
fragments,
}: {
nodes: {
node: ts.TaggedTemplateExpression | ts.StringLiteralLike;
schema: string | null;
tadaFragmentRefs?: readonly ts.Identifier[];
}[];
fragments: FragmentDefinitionNode[];
},
schema: SchemaRef,
info: ts.server.PluginCreateInfo
): ts.Diagnostic[] => {
const filename = source.fileName;
const isCallExpression = info.config.templateIsCallExpression ?? true;
const typeChecker = info.languageService.getProgram()?.getTypeChecker();
const diagnostics = nodes
.map(originalNode => {
let node = originalNode.node;
if (
!isCallExpression &&
(ts.isNoSubstitutionTemplateLiteral(node) ||
ts.isTemplateExpression(node))
) {
if (ts.isTaggedTemplateExpression(node.parent)) {
node = node.parent;
} else {
return undefined;
}
}
const { combinedText: text, resolvedSpans } = resolveTemplate(
node,
filename,
info
);
const lines = text.split('\n');
let isExpression = false;
if (ts.isAsExpression(node.parent)) {
if (ts.isExpressionStatement(node.parent.parent)) {
isExpression = true;
}
} else if (ts.isExpressionStatement(node.parent)) {
isExpression = true;
}
// When we are dealing with a plain gql statement we have to add two these can be recognised
// by the fact that the parent is an expressionStatement
let startingPosition =
node.getStart() +
(isCallExpression
? 0
: (node as ts.TaggedTemplateExpression).tag.getText().length +
(isExpression ? 2 : 0));
const endPosition = startingPosition + node.getText().length;
let docFragments = [...fragments];
if (originalNode.tadaFragmentRefs !== undefined) {
const fragmentNames = new Set<string>();
for (const identifier of originalNode.tadaFragmentRefs) {
const unrolled = unrollFragment(identifier, info, typeChecker);
unrolled.forEach((frag: FragmentDefinitionNode) =>
fragmentNames.add(frag.name.value)
);
}
docFragments = docFragments.filter(frag =>
fragmentNames.has(frag.name.value)
);
}
if (isCallExpression) {
try {
const documentFragments = parse(text, {
noLocation: true,
}).definitions.filter(x => x.kind === Kind.FRAGMENT_DEFINITION);
docFragments = docFragments.filter(
x =>
!documentFragments.some(
y =>
y.kind === Kind.FRAGMENT_DEFINITION &&
y.name.value === x.name.value
)
);
} catch (e) {}
}
const schemaToUse =
originalNode.schema && schema.multi[originalNode.schema]
? schema.multi[originalNode.schema]?.schema
: schema.current?.schema;
if (!schemaToUse) {
return undefined;
}
const clientDirectives = new Set([
...BASE_CLIENT_DIRECTIVES,
...(info.config.clientDirectives || []),
]);
const graphQLDiagnostics = getDiagnostics(
text,
schemaToUse,
undefined,
undefined,
docFragments
)
.filter(diag => {
if (!diag.message.includes('Unknown directive')) return true;
const [message] = diag.message.split('(');
const matches =
message && /Unknown directive "@([^)]+)"/g.exec(message);
if (!matches) return true;
const directiveName = matches[1];
return directiveName && !clientDirectives.has(directiveName);
})
.map(x => {
const { start, end } = x.range;
// We add the start.line to account for newline characters which are
// split out
let startChar = startingPosition + start.line;
for (let i = 0; i <= start.line && i < lines.length; i++) {
if (i === start.line) startChar += start.character;
else if (lines[i]) startChar += lines[i]!.length;
}
let endChar = startingPosition + end.line;
for (let i = 0; i <= end.line && i < lines.length; i++) {
if (i === end.line) endChar += end.character;
else if (lines[i]) endChar += lines[i]!.length;
}
const locatedInFragment = resolvedSpans.find(x => {
const newEnd = x.new.start + x.new.length;
return startChar >= x.new.start && endChar <= newEnd;
});
if (!!locatedInFragment) {
return {
...x,
start: locatedInFragment.original.start,
length: locatedInFragment.original.length,
};
} else {
if (startChar > endPosition) {
// we have to calculate the added length and fix this
const addedCharacters = resolvedSpans
.filter(x => x.new.start + x.new.length < startChar)
.reduce(
(acc, span) => acc + (span.new.length - span.original.length),
0
);
startChar = startChar - addedCharacters;
endChar = endChar - addedCharacters;
return {
...x,
start: startChar + 1,
length: endChar - startChar,
};
} else {
return {
...x,
start: startChar + 1,
length: endChar - startChar,
};
}
}
})
.filter(x => x.start + x.length <= endPosition);
return graphQLDiagnostics;
})
.flat()
.filter(Boolean) as Array<Diagnostic & { length: number; start: number }>;
const tsDiagnostics = diagnostics.map(
diag =>
({
file: source,
length: diag.length,
start: diag.start,
category:
diag.severity === 2
? ts.DiagnosticCategory.Warning
: ts.DiagnosticCategory.Error,
code:
typeof diag.code === 'number'
? diag.code
: diag.severity === 2
? USING_DEPRECATED_FIELD_CODE
: SEMANTIC_DIAGNOSTIC_CODE,
messageText: diag.message.split('\n')[0],
} as ts.Diagnostic)
);
if (isCallExpression) {
const usageDiagnostics =
checkFieldUsageInFile(
source,
nodes.map(x => x.node) as ts.NoSubstitutionTemplateLiteral[],
info
) || [];
if (!usageDiagnostics) return tsDiagnostics;
return [...tsDiagnostics, ...usageDiagnostics];
} else {
return tsDiagnostics;
}
};