forked from dotansimha/graphql-code-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.ts
More file actions
601 lines (537 loc) · 23.7 KB
/
codegen.ts
File metadata and controls
601 lines (537 loc) · 23.7 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
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
import fs from 'fs';
import { createRequire } from 'module';
import { cpus } from 'os';
import path from 'path';
import { buildASTSchema, DocumentNode, GraphQLError, GraphQLSchema, isSchema } from 'graphql';
import { Listr, ListrTask } from 'listr2';
import { codegen } from '@graphql-codegen/core';
import {
CodegenPlugin,
getCachedDocumentNodeFromSchema,
normalizeConfig,
normalizeImportExtension,
normalizeInstanceOrArray,
normalizeOutputParam,
Types,
} from '@graphql-codegen/plugin-helpers';
import { NoTypeDefinitionsFound, type UnnormalizedTypeDefPointer } from '@graphql-tools/load';
import { mergeTypeDefs } from '@graphql-tools/merge';
import { CodegenContext, ensureContext } from './config.js';
import { getDocumentTransform } from './documentTransforms.js';
import { getPluginByName } from './plugins.js';
import { getPresetByName } from './presets.js';
import { debugLog, printLogs } from './utils/debugging.js';
/**
* Poor mans ESM detection.
* Looking at this and you have a better method?
* Send a PR.
*/
const isESMModule = (typeof __dirname === 'string') === false;
const makeDefaultLoader = (from: string) => {
if (fs.statSync(from).isDirectory()) {
from = path.join(from, '__fake.js');
}
const relativeRequire = createRequire(from);
return async (mod: string) => {
return import(
isESMModule
? /**
* For ESM we currently have no "resolve path" solution
* as import.meta is unavailable in a CommonJS context
* and furthermore unavailable in stable Node.js.
**/
mod
: relativeRequire.resolve(mod)
);
};
};
type Ctx = { errors: Error[] };
function createCache(): <T>(
namespace: string,
key: string,
factory: () => Promise<T>,
) => Promise<T> {
const cache = new Map<string, Promise<unknown>>();
return function ensure<T>(namespace: string, key: string, factory: () => Promise<T>): Promise<T> {
const cacheKey = `${namespace}:${key}`;
const cachedValue = cache.get(cacheKey);
if (cachedValue) {
return cachedValue as Promise<T>;
}
const value = factory();
cache.set(cacheKey, value);
return value;
};
}
export async function executeCodegen(
input: CodegenContext | Types.Config,
): Promise<{ result: Types.FileOutput[]; error: Error | null }> {
const context = ensureContext(input);
const config = context.getConfig();
const pluginContext = context.getPluginContext();
const result: Types.FileOutput[] = [];
let rootConfig: { [key: string]: any } = {};
let rootSchemas: Types.Schema[];
let rootDocuments: Types.OperationDocument[];
let rootExternalDocuments: Types.OperationDocument[];
const generates: { [filename: string]: Types.ConfiguredOutput } = {};
const cache = createCache();
// We need a simple string to uniqually identify the provided GraphQLSchema objects for the above cache.
// Because JavaScript does not provide access to its internal object ids, we need a workaround.
// Below is a common way to get unique ids for objects in JavaScript,
// by using a WeakMap and autoincrementing the id.
const jsObjectIds = new WeakMap<GraphQLSchema, number>();
let jsObjectIdCounter = 0;
function getJsObjectId(schema: GraphQLSchema): number {
if (!jsObjectIds.has(schema)) {
jsObjectIds.set(schema, jsObjectIdCounter++);
}
return jsObjectIds.get(schema)!;
}
function wrapTask(task: () => void | Promise<void>, source: string, taskName: string, ctx: Ctx) {
return () =>
context.profiler.run(async () => {
try {
await Promise.resolve().then(() => task());
} catch (error: any) {
if (source && !(error instanceof GraphQLError)) {
error.source = source;
}
ctx.errors.push(error);
throw error;
}
}, taskName);
}
async function normalize() {
/* Load Require extensions */
const requireExtensions = normalizeInstanceOrArray<string>(config.require);
const loader = makeDefaultLoader(context.cwd);
for (const mod of requireExtensions) {
await loader(mod);
}
/* Root plugin config */
rootConfig = config.config || {};
/* Normalize root "schema" field */
rootSchemas = normalizeInstanceOrArray<Types.Schema>(config.schema);
/* Normalize root "documents" field */
rootDocuments = normalizeInstanceOrArray<Types.OperationDocument>(config.documents);
/* Normalize root "externalDocuments" field */
rootExternalDocuments = normalizeInstanceOrArray<Types.OperationDocument>(
config.externalDocuments,
);
/* Normalize "generators" field */
const generateKeys = Object.keys(config.generates || {});
if (generateKeys.length === 0) {
throw new Error(
`Invalid Codegen Configuration! \n
Please make sure that your codegen config file contains the "generates" field, with a specification for the plugins you need.
It should looks like that:
schema:
- my-schema.graphql
generates:
my-file.ts:
- plugin1
- plugin2
- plugin3`,
);
}
for (const filename of generateKeys) {
const output = (generates[filename] = normalizeOutputParam(config.generates[filename]));
if (!output.preset && (!output.plugins || output.plugins.length === 0)) {
throw new Error(
`Invalid Codegen Configuration! \n
Please make sure that your codegen config file has defined plugins list for output "${filename}".
It should looks like that:
schema:
- my-schema.graphql
generates:
my-file.ts:
- plugin1
- plugin2
- plugin3
`,
);
}
}
if (
rootSchemas.length === 0 &&
Object.keys(generates).some(
filename =>
!generates[filename].schema ||
(Array.isArray(generates[filename].schema === 'object') &&
(generates[filename].schema as unknown as any[]).length === 0),
)
) {
throw new Error(
`Invalid Codegen Configuration! \n
Please make sure that your codegen config file contains either the "schema" field
or every generated file has its own "schema" field.
It should looks like that:
schema:
- my-schema.graphql
or:
generates:
path/to/output:
schema: my-schema.graphql
`,
);
}
}
const isTest = process.env.NODE_ENV === 'test';
const tasks = new Listr<Ctx, 'default' | 'verbose'>(
[
{
title: 'Parse Configuration',
task: () => normalize(),
},
{
title: 'Generate outputs',
task: (ctx, task) => {
const generateTasks: ListrTask<Ctx>[] = Object.keys(generates).map(filename => {
const outputConfig = generates[filename];
const hasPreset = !!outputConfig.preset;
const title = `Generate to ${filename}`;
return {
title,
async task(_, subTask) {
let outputSchemaAst: GraphQLSchema;
let outputSchema: DocumentNode;
const outputFileTemplateConfig = outputConfig.config || {};
const outputDocuments: Types.DocumentFile[] = [];
const outputSpecificSchemas = normalizeInstanceOrArray<Types.Schema>(
outputConfig.schema,
);
let outputSpecificDocuments = normalizeInstanceOrArray<Types.OperationDocument>(
outputConfig.documents,
);
let outputSpecificExternalDocuments =
normalizeInstanceOrArray<Types.OperationDocument>(outputConfig.externalDocuments);
const preset: Types.OutputPreset | null = hasPreset
? typeof outputConfig.preset === 'string'
? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
: outputConfig.preset
: null;
if (preset?.prepareDocuments) {
outputSpecificDocuments = await preset.prepareDocuments(
filename,
outputSpecificDocuments,
);
outputSpecificExternalDocuments = await preset.prepareDocuments(
filename,
outputSpecificExternalDocuments,
);
}
return subTask.newListr(
[
{
title: 'Load GraphQL schemas',
task: wrapTask(
async () => {
debugLog(`[CLI] Loading Schemas`);
const schemaPointerMap: any = {};
const parsedSchemas: GraphQLSchema[] = [];
const allSchemaDenormalizedPointers = [
...rootSchemas,
...outputSpecificSchemas,
];
for (const denormalizedPtr of allSchemaDenormalizedPointers) {
if (isSchema(denormalizedPtr)) {
parsedSchemas.push(denormalizedPtr);
} else if (typeof denormalizedPtr === 'string') {
schemaPointerMap[denormalizedPtr] = {};
} else if (typeof denormalizedPtr === 'object') {
Object.assign(schemaPointerMap, denormalizedPtr);
}
}
const hash =
JSON.stringify(schemaPointerMap) +
parsedSchemas.map(getJsObjectId).join(',');
const result = await cache('schema', hash, async () => {
// collect parsed schemas
const schemasToMerge: GraphQLSchema[] = [...parsedSchemas];
// collect schemas, provided by pointers
if (Object.keys(schemaPointerMap).length) {
schemasToMerge.push(await context.loadSchema(schemaPointerMap));
}
// merge all collected schemas into one
const outputSchemaAst =
schemasToMerge.length === 1
? schemasToMerge[0]
: buildASTSchema(mergeTypeDefs(schemasToMerge));
const outputSchema = getCachedDocumentNodeFromSchema(outputSchemaAst);
return {
outputSchemaAst,
outputSchema,
};
});
outputSchemaAst = result.outputSchemaAst;
outputSchema = result.outputSchema;
},
filename,
`Load GraphQL schemas: ${filename}`,
ctx,
),
},
{
title: 'Load GraphQL documents',
task: wrapTask(
async () => {
debugLog(`[CLI] Loading Documents`);
const populateDocumentPointerMap = (
allDocumentsDenormalizedPointers: Types.OperationDocument[],
): UnnormalizedTypeDefPointer => {
const pointer: UnnormalizedTypeDefPointer = {};
for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
if (typeof denormalizedPtr === 'string') {
pointer[denormalizedPtr] = {};
} else if (typeof denormalizedPtr === 'object') {
Object.assign(pointer, denormalizedPtr);
}
}
return pointer;
};
const allDocumentsDenormalizedPointers = [
...rootDocuments,
...outputSpecificDocuments,
];
const documentPointerMap = populateDocumentPointerMap(
allDocumentsDenormalizedPointers,
);
const hash = JSON.stringify(documentPointerMap);
const outputDocumentsStandard = await cache(
'documents',
hash,
async (): Promise<Types.DocumentFile[]> => {
try {
const documents = await context.loadDocuments(
documentPointerMap,
'standard',
);
return documents;
} catch (error) {
if (
error instanceof NoTypeDefinitionsFound &&
config.ignoreNoDocuments
) {
return [];
}
throw error;
}
},
);
const allExternalDocumentsDenormalizedPointers = [
...rootExternalDocuments,
...outputSpecificExternalDocuments,
];
const externalDocumentsPointerMap = populateDocumentPointerMap(
allExternalDocumentsDenormalizedPointers,
);
const externalDocumentHash = JSON.stringify(externalDocumentsPointerMap);
const outputExternalDocuments = await cache(
'documents',
externalDocumentHash,
async (): Promise<Types.DocumentFile[]> => {
try {
const documents = await context.loadDocuments(
externalDocumentsPointerMap,
'external',
);
return documents;
} catch (error) {
if (
error instanceof NoTypeDefinitionsFound &&
config.ignoreNoDocuments
) {
return [];
}
throw error;
}
},
);
/**
* Merging `standard` and `external` documents here,
* so they can be processed the same way,
* before passed into presets and plugins
*/
const processedFile: Record<string, true> = {};
const mergedDocuments = [
...outputDocumentsStandard,
...outputExternalDocuments,
];
for (const file of mergedDocuments) {
if (processedFile[file.hash]) {
continue;
}
outputDocuments.push(file);
processedFile[file.hash] = true;
}
},
filename,
`Load GraphQL documents: ${filename}`,
ctx,
),
},
{
title: 'Generate',
task: wrapTask(
async () => {
debugLog(`[CLI] Generating output`);
const normalizedPluginsArray = normalizeConfig(outputConfig.plugins);
const pluginLoader =
config.pluginLoader || makeDefaultLoader(context.cwd);
const pluginPackages = await Promise.all(
normalizedPluginsArray.map(plugin =>
getPluginByName(Object.keys(plugin)[0], pluginLoader),
),
);
const pluginMap: {
[name: string]: CodegenPlugin;
} = Object.fromEntries(
pluginPackages.map((pkg, i) => {
const plugin = normalizedPluginsArray[i];
const name = Object.keys(plugin)[0];
return [name, pkg];
}),
);
const rawMergedConfig = {
...rootConfig,
emitLegacyCommonJSImports: config.emitLegacyCommonJSImports,
importExtension: config.importExtension,
...(typeof outputFileTemplateConfig === 'string'
? { value: outputFileTemplateConfig }
: outputFileTemplateConfig),
};
const importExtension = normalizeImportExtension({
emitLegacyCommonJSImports: rawMergedConfig.emitLegacyCommonJSImports,
importExtension: rawMergedConfig.importExtension,
});
const mergedConfig = {
...rawMergedConfig,
importExtension,
emitLegacyCommonJSImports:
rawMergedConfig.emitLegacyCommonJSImports ?? true,
};
const documentTransforms = Array.isArray(outputConfig.documentTransforms)
? await Promise.all(
outputConfig.documentTransforms.map(async (config, index) => {
return await getDocumentTransform(
config,
makeDefaultLoader(context.cwd),
`the element at index ${index} of the documentTransforms`,
);
}),
)
: [];
const outputs: Types.GenerateOptions[] = preset
? await context.profiler.run(
async () =>
preset.buildGeneratesSection({
baseOutputDir: filename,
presetConfig: outputConfig.presetConfig || {},
plugins: normalizedPluginsArray,
schema: outputSchema,
schemaAst: outputSchemaAst,
documents: outputDocuments,
config: mergedConfig,
pluginMap,
pluginContext,
profiler: context.profiler,
documentTransforms,
}),
`Build Generates Section: ${filename}`,
)
: [
{
filename,
plugins: normalizedPluginsArray,
schema: outputSchema,
schemaAst: outputSchemaAst,
documents: outputDocuments,
config: mergedConfig,
pluginMap,
pluginContext,
profiler: context.profiler,
documentTransforms,
} satisfies Types.GenerateOptions,
];
const process = async (outputArgs: Types.GenerateOptions) => {
const output = await codegen({
...outputArgs,
importExtension,
emitLegacyCommonJSImports:
rawMergedConfig.emitLegacyCommonJSImports ?? true,
cache,
});
result.push({
filename: outputArgs.filename,
content: output,
hooks: outputConfig.hooks || {},
});
};
await context.profiler.run(
() => Promise.all(outputs.map(process)),
`Codegen: ${filename}`,
);
},
filename,
`Generate: ${filename}`,
ctx,
),
},
],
{
/**
* For each `generates` task, we must do the following in order:
*
* 1. Load schema
* 2. Load documents
* 3. Generate based on the schema + documents
*
* This way, the 3rd step has all the schema and documents loaded in previous steps to work correctly
*/
exitOnError: true,
concurrent: false,
},
);
},
// It doesn't stop when one of tasks failed, to finish at least some of outputs
exitOnError: false,
};
});
return task.newListr(generateTasks, {
concurrent: cpus().length || 1,
});
},
},
],
{
rendererOptions: {
clearOutput: false,
collapseSubtasks: true,
formatOutput: 'wrap',
removeEmptyLines: false,
},
renderer: config.verbose ? 'verbose' : 'default',
ctx: { errors: [] },
silentRendererCondition: isTest || config.silent,
exitOnError: true,
},
);
// All the errors throw in `listr2` are collected in context
// Running tasks doesn't throw anything
const executedContext = await tasks.run();
if (config.debug) {
// if we have debug logs, make sure to print them before throwing the errors
printLogs();
}
let error: Error | null = null;
if (executedContext.errors.length > 0) {
const errors = executedContext.errors.map(subErr => subErr.message || subErr.toString());
error = new AggregateError(executedContext.errors, String(errors.join('\n\n')));
// Best-effort to all stack traces for debugging
error.stack = `${error.stack}\n\n${executedContext.errors
.map(subErr => subErr.stack)
.join('\n\n')}`;
}
return { result, error };
}