-
Notifications
You must be signed in to change notification settings - Fork 26
/
graphql-language-service-adapter.ts
157 lines (141 loc) · 6.39 KB
/
graphql-language-service-adapter.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
import ts from 'typescript';
import { GraphQLSchema, parse, type DocumentNode } from 'graphql';
import {
getTemplateNodeUnder,
isTaggedTemplateNode,
ScriptSourceHelper,
StrictTagCondition,
isTemplateLiteralTypeNode,
} from '../ts-ast-util';
import { SchemaBuildErrorInfo } from '../schema-manager/schema-manager';
import { getFragmentNamesInDocument, detectDuplicatedFragments, type FragmentRegistry } from '../gql-ast-util';
import { AnalysisContext, GetCompletionAtPosition, GetSemanticDiagnostics, GetQuickInfoAtPosition } from './types';
import { getCompletionAtPosition } from './get-completion-at-position';
import { getSemanticDiagnostics } from './get-semantic-diagnostics';
import { getQuickInfoAtPosition } from './get-quick-info-at-position';
import { LRUCache } from '../cache';
export interface GraphQLLanguageServiceAdapterCreateOptions {
schema?: GraphQLSchema | null;
schemaErrors?: SchemaBuildErrorInfo[] | null;
logger?: (msg: string) => void;
tag: StrictTagCondition;
removeDuplicatedFragments: boolean;
fragmentRegistry: FragmentRegistry;
}
type Args<T> = T extends (...args: infer A) => any ? A : never;
export class GraphQLLanguageServiceAdapter {
private _schemaErrors?: SchemaBuildErrorInfo[] | null;
private _schema?: GraphQLSchema | null;
private readonly _tagCondition: StrictTagCondition;
private readonly _removeDuplicatedFragments: boolean;
private readonly _analysisContext: AnalysisContext;
private readonly _fragmentRegisry: FragmentRegistry;
private readonly _parsedDocumentCache = new LRUCache<string, DocumentNode>(500);
constructor(
private readonly _helper: ScriptSourceHelper,
opt: GraphQLLanguageServiceAdapterCreateOptions,
) {
if (opt.logger) this._logger = opt.logger;
if (opt.schemaErrors) this.updateSchema(opt.schemaErrors, null);
if (opt.schema) this.updateSchema(null, opt.schema);
this._tagCondition = opt.tag;
this._removeDuplicatedFragments = opt.removeDuplicatedFragments;
this._analysisContext = this._createAnalysisContext();
this._fragmentRegisry = opt.fragmentRegistry;
}
getCompletionAtPosition(delegate: GetCompletionAtPosition, ...args: Args<GetCompletionAtPosition>) {
return getCompletionAtPosition(this._analysisContext, delegate, ...args);
}
getSemanticDiagnostics(delegate: GetSemanticDiagnostics, ...args: Args<GetSemanticDiagnostics>) {
return getSemanticDiagnostics(this._analysisContext, delegate, ...args);
}
getQuickInfoAtPosition(delegate: GetQuickInfoAtPosition, ...args: Args<GetQuickInfoAtPosition>) {
return getQuickInfoAtPosition(this._analysisContext, delegate, ...args);
}
updateSchema(errors: SchemaBuildErrorInfo[] | null, schema: GraphQLSchema | null) {
if (errors) {
this._schemaErrors = errors;
this._schema = null;
} else {
this._schema = schema;
this._schemaErrors = null;
}
}
private _createAnalysisContext() {
const ctx: AnalysisContext = {
debug: msg => this._logger(msg),
getScriptSourceHelper: () => this._helper,
getSchema: () => this._schema,
getSchemaOrSchemaErrors: () => {
if (!this._schema) {
return [null, this._schemaErrors as SchemaBuildErrorInfo[]];
} else {
return [this._schema, null];
}
},
getGraphQLDocumentNode: text => this._parse(text),
getGlobalFragmentDefinitions: () => this._fragmentRegisry.getFragmentDefinitions(),
getExternalFragmentDefinitions: (documentStr, fileName, sourcePosition) =>
this._fragmentRegisry.getExternalFragments(documentStr, fileName, sourcePosition),
getDuplicaterdFragmentDefinitions: () => this._fragmentRegisry.getDuplicaterdFragmentDefinitions(),
findAscendantTemplateNode: (fileName, position) => this._findAscendantTemplateNode(fileName, position),
findTemplateNodes: fileName => this._findTemplateNodes(fileName),
resolveTemplateInfo: (fileName, node) => this._resolveTemplateInfo(fileName, node),
};
return ctx;
}
private _findAscendantTemplateNode(fileName: string, position: number) {
const nodeUnderCursor = this._helper.getNode(fileName, position);
if (!nodeUnderCursor) return;
let templateNode: ts.NoSubstitutionTemplateLiteral | ts.TemplateExpression;
if (ts.isNoSubstitutionTemplateLiteral(nodeUnderCursor)) {
templateNode = nodeUnderCursor;
} else if (ts.isTemplateHead(nodeUnderCursor) && !isTemplateLiteralTypeNode(nodeUnderCursor.parent)) {
templateNode = nodeUnderCursor.parent;
} else if (
(ts.isTemplateMiddle(nodeUnderCursor) || ts.isTemplateTail(nodeUnderCursor)) &&
!isTemplateLiteralTypeNode(nodeUnderCursor.parent.parent)
) {
templateNode = nodeUnderCursor.parent.parent;
} else {
return;
}
if (!isTaggedTemplateNode(templateNode, this._tagCondition)) {
return;
}
return templateNode;
}
private _findTemplateNodes(fileName: string) {
return this._helper.getAllNodes(fileName, node => getTemplateNodeUnder(node, this._tagCondition));
}
private _parse(text: string) {
const cached = this._parsedDocumentCache.get(text);
if (cached) return cached;
try {
const parsed = parse(text);
this._parsedDocumentCache.set(text, parsed);
return parsed;
} catch {
return undefined;
}
}
private _resolveTemplateInfo(fileName: string, node: ts.TemplateExpression | ts.NoSubstitutionTemplateLiteral) {
const { resolvedInfo, resolveErrors } = this._helper.resolveTemplateLiteral(fileName, node);
if (!resolvedInfo) return { resolveErrors };
const documentNode = this._parse(resolvedInfo.combinedText);
if (!documentNode) {
// Note:
// `parse` throws GraphQL syntax error when combinedText is invalid for GraphQL syntax.
// We don't need handle this error because getDiagnostics method in this class re-checks syntax with graphql-lang-service,
return { resolvedInfo, resolveErrors };
}
const fragmentNames = getFragmentNamesInDocument(documentNode);
if (!this._removeDuplicatedFragments) return { resolveErrors, resolvedInfo, fragmentNames };
const duplicatedFragmentInfoList = detectDuplicatedFragments(documentNode);
const info = duplicatedFragmentInfoList.reduce((acc, fragmentInfo) => {
return this._helper.updateTemplateLiteralInfo(acc, fragmentInfo);
}, resolvedInfo);
return { resolvedInfo: info, resolveErrors };
}
private _logger: (msg: string) => void = () => {};
}