-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathcodegen.ts
More file actions
358 lines (318 loc) · 10 KB
/
codegen.ts
File metadata and controls
358 lines (318 loc) · 10 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
import {
DefinitionNode,
DocumentNode,
Kind,
NameNode,
print,
specifiedRules,
visit,
} from 'graphql';
import {
AddToSchemaResult,
createNoopProfiler,
federationSpec,
getCachedDocumentNodeFromSchema,
isComplexPluginOutput,
Types,
} from '@graphql-codegen/plugin-helpers';
import { mergeSchemas } from '@graphql-tools/schema';
import { asArray, Source, validateGraphQlDocuments } from '@graphql-tools/utils';
import { executePlugin } from './execute-plugin.js';
import { transformDocuments } from './transform-document.js';
import {
extractHashFromSchema,
getSkipDocumentsValidationOption,
hasFederationSpec,
pickFlag,
prioritize,
shouldValidateDocumentsAgainstSchema,
shouldValidateDuplicateDocuments,
} from './utils.js';
export async function codegen(options: Types.GenerateOptions): Promise<string> {
const documents = options.documents || [];
const profiler = options.profiler ?? createNoopProfiler();
const skipDocumentsValidation = getSkipDocumentsValidationOption(options);
if (documents.length > 0 && shouldValidateDuplicateDocuments(skipDocumentsValidation)) {
await profiler.run(
async () => validateDuplicateDocuments(documents),
'validateDuplicateDocuments',
);
}
const pluginPackages = Object.keys(options.pluginMap).map(key => options.pluginMap[key]);
// merged schema with parts added by plugins
const additionalTypeDefs: AddToSchemaResult[] = [];
for (const plugin of pluginPackages) {
const addToSchema =
typeof plugin.addToSchema === 'function'
? plugin.addToSchema(options.config)
: plugin.addToSchema;
if (addToSchema) {
additionalTypeDefs.push(addToSchema);
}
}
const federationInConfig: boolean = pickFlag('federation', options.config);
const isFederation = prioritize(federationInConfig, false);
if (isFederation && !hasFederationSpec(options.schemaAst || options.schema)) {
additionalTypeDefs.push(federationSpec);
}
// Use mergeSchemas, only if there is no GraphQLSchema provided or the schema should be extended
const mergeNeeded = !options.schemaAst || additionalTypeDefs.length > 0;
const schemaInstance = await profiler.run(async () => {
return mergeNeeded
? mergeSchemas({
// If GraphQLSchema provided, use it
schemas: options.schemaAst ? [options.schemaAst] : [],
// If GraphQLSchema isn't provided but DocumentNode is, use it to get the final GraphQLSchema
typeDefs: options.schemaAst
? additionalTypeDefs
: [options.schema, ...additionalTypeDefs],
convertExtensions: true,
assumeValid: true,
assumeValidSDL: true,
...options.config,
} as any)
: options.schemaAst;
}, 'Create schema instance');
const schemaDocumentNode =
mergeNeeded || !options.schema
? getCachedDocumentNodeFromSchema(schemaInstance!)
: options.schema;
const documentTransforms = Array.isArray(options.documentTransforms)
? options.documentTransforms
: [];
const transformedDocuments = await transformDocuments({
...options,
documentTransforms,
schema: schemaDocumentNode,
schemaAst: schemaInstance,
profiler,
});
if (
schemaInstance &&
transformedDocuments.length > 0 &&
shouldValidateDocumentsAgainstSchema(skipDocumentsValidation)
) {
const ignored = ['NoUnusedFragments', 'NoUnusedVariables', 'KnownDirectives'];
if (typeof skipDocumentsValidation === 'object' && skipDocumentsValidation.ignoreRules) {
ignored.push(...asArray(skipDocumentsValidation.ignoreRules));
}
const extraFragments: { importFrom: string; node: DefinitionNode }[] =
pickFlag('externalFragments', options.config) || [];
const errors = await profiler.run(() => {
const fragments = extraFragments.map(f => ({
location: f.importFrom,
document: {
kind: Kind.DOCUMENT,
definitions: [f.node],
} as DocumentNode,
}));
const rules = specifiedRules.filter(
rule => !ignored.some(ignoredRule => rule.name.startsWith(ignoredRule)),
);
const schemaHash = extractHashFromSchema(schemaInstance);
if (
!schemaHash ||
!options.cache ||
transformedDocuments.some(d => typeof d.hash !== 'string')
) {
return Promise.resolve(
validateGraphQlDocuments(
schemaInstance,
[
...transformedDocuments.flatMap(d => d.document),
...fragments.flatMap(f => f.document),
],
rules,
),
);
}
const cacheKey = [schemaHash]
.concat(transformedDocuments.map(doc => doc.hash))
.concat(JSON.stringify(fragments))
.join(',');
return options.cache('documents-validation', cacheKey, () =>
Promise.resolve(
validateGraphQlDocuments(
schemaInstance,
[
...transformedDocuments.flatMap(d => d.document),
...fragments.flatMap(f => f.document),
],
rules,
),
),
);
}, 'Validate documents against schema');
if (errors.length > 0) {
throw new Error(
`GraphQL Document Validation failed with ${errors.length} errors;
${errors.map((error, index) => `Error ${index}: ${error.stack}`).join('\n\n')}`,
);
}
}
const prepend: Set<string> = new Set<string>();
const append: Set<string> = new Set<string>();
const output = await Promise.all(
options.plugins.map(async plugin => {
const name = Object.keys(plugin)[0];
const pluginPackage = options.pluginMap[name];
const pluginConfig = plugin[name] || {};
const execConfig =
typeof pluginConfig === 'object' ? { ...options.config, ...pluginConfig } : pluginConfig;
const result = await profiler.run(
() =>
executePlugin(
{
name,
config: execConfig,
parentConfig: options.config,
schema: schemaDocumentNode,
schemaAst: schemaInstance,
documents: transformedDocuments,
outputFilename: options.filename,
allPlugins: options.plugins,
skipDocumentsValidation: options.skipDocumentsValidation,
pluginContext: options.pluginContext,
profiler,
},
pluginPackage,
),
`Plugin ${name}`,
);
if (typeof result === 'string') {
return result || '';
}
if (isComplexPluginOutput(result)) {
if (result.append && result.append.length > 0) {
for (const item of result.append) {
if (item) {
append.add(item);
}
}
}
if (result.prepend && result.prepend.length > 0) {
for (const item of result.prepend) {
if (item) {
prepend.add(item);
}
}
}
return result.content || '';
}
return '';
}),
);
return [
...sortPrependValues(Array.from(prepend.values())),
...output,
...Array.from(append.values()),
]
.filter(Boolean)
.join('\n');
}
function resolveCompareValue(a: string) {
if (
a.startsWith('/*') ||
a.startsWith('//') ||
a.startsWith(' *') ||
a.startsWith(' */') ||
a.startsWith('*/')
) {
return 0;
}
if (a.startsWith('package')) {
return 1;
}
if (a.startsWith('import')) {
return 2;
}
return 3;
}
export function sortPrependValues(values: string[]): string[] {
return values.sort((a: string, b: string) => {
const aV = resolveCompareValue(a);
const bV = resolveCompareValue(b);
if (aV < bV) {
return -1;
}
if (aV > bV) {
return 1;
}
return 0;
});
}
function validateDuplicateDocuments(files: Types.DocumentFile[]) {
// duplicated names
const definitionMap: {
[kind: string]: {
[name: string]: {
paths: Set<string>;
contents: Set<string>;
};
};
} = {};
function addDefinition(
file: Source,
node: DefinitionNode & { name?: NameNode },
deduplicatedDefinitions: Set<DefinitionNode>,
) {
if (typeof node.name !== 'undefined') {
definitionMap[node.kind] ||= {};
definitionMap[node.kind][node.name.value] ||= {
paths: new Set(),
contents: new Set(),
};
const definitionKindMap = definitionMap[node.kind];
const length = definitionKindMap[node.name.value].contents.size;
definitionKindMap[node.name.value].paths.add(file.location!);
definitionKindMap[node.name.value].contents.add(print(node));
if (length === definitionKindMap[node.name.value].contents.size) {
return null;
}
}
return deduplicatedDefinitions.add(node);
}
for (const file of files) {
const deduplicatedDefinitions = new Set<DefinitionNode>();
visit(file.document!, {
OperationDefinition(node) {
addDefinition(file, node, deduplicatedDefinitions);
},
FragmentDefinition(node) {
addDefinition(file, node, deduplicatedDefinitions);
},
});
(file.document as any).definitions = Array.from(deduplicatedDefinitions);
}
const kinds = Object.keys(definitionMap);
for (const kind of kinds) {
const definitionKindMap = definitionMap[kind];
const names = Object.keys(definitionKindMap);
if (names.length) {
const duplicated = names.filter(name => definitionKindMap[name].contents.size > 1);
if (!duplicated.length) {
continue;
}
const list = duplicated
.map(name =>
`
* ${name} found in:
${[...definitionKindMap[name].paths]
.map(filepath => {
return `
- ${filepath}
`.trimEnd();
})
.join('')}
`.trimEnd(),
)
.join('');
const definitionKindName = kind.replace('Definition', '').toLowerCase();
throw new Error(
`Not all ${definitionKindName}s have an unique name: ${duplicated.join(', ')}: \n
${list}
`,
);
}
}
}