-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathcodegen.ts
426 lines (372 loc) · 16.2 KB
/
codegen.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
import fs from 'fs';
import { createRequire } from 'module';
import { cpus } from 'os';
import path from 'path';
import { codegen } from '@graphql-codegen/core';
import {
CodegenPlugin,
getCachedDocumentNodeFromSchema,
normalizeConfig,
normalizeInstanceOrArray,
normalizeOutputParam,
Types,
} from '@graphql-codegen/plugin-helpers';
import { AggregateError } from '@graphql-tools/utils';
import { DocumentNode, GraphQLError, GraphQLSchema } from 'graphql';
import { Listr, ListrTask } from 'listr2';
import { CodegenContext, ensureContext, shouldEmitLegacyCommonJSImports } from './config.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<Types.FileOutput[]> {
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[];
const generates: { [filename: string]: Types.ConfiguredOutput } = {};
const cache = createCache();
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) {
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 "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 || {};
let outputDocuments: Types.DocumentFile[] = [];
const outputSpecificSchemas = normalizeInstanceOrArray<Types.Schema>(outputConfig.schema);
let outputSpecificDocuments = normalizeInstanceOrArray<Types.OperationDocument>(outputConfig.documents);
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);
}
return subTask.newListr(
[
{
title: 'Load GraphQL schemas',
task: wrapTask(
async () => {
debugLog(`[CLI] Loading Schemas`);
const schemaPointerMap: any = {};
const allSchemaDenormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
for (const denormalizedPtr of allSchemaDenormalizedPointers) {
if (typeof denormalizedPtr === 'string') {
schemaPointerMap[denormalizedPtr] = {};
} else if (typeof denormalizedPtr === 'object') {
Object.assign(schemaPointerMap, denormalizedPtr);
}
}
const hash = JSON.stringify(schemaPointerMap);
const result = await cache('schema', hash, async () => {
const outputSchemaAst = await context.loadSchema(schemaPointerMap);
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 documentPointerMap: any = {};
const allDocumentsDenormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
if (typeof denormalizedPtr === 'string') {
documentPointerMap[denormalizedPtr] = {};
} else if (typeof denormalizedPtr === 'object') {
Object.assign(documentPointerMap, denormalizedPtr);
}
}
const hash = JSON.stringify(documentPointerMap);
const result = await cache('documents', hash, async () => {
const documents = await context.loadDocuments(documentPointerMap);
return {
documents,
};
});
outputDocuments = result.documents;
},
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 mergedConfig = {
...rootConfig,
...(typeof outputFileTemplateConfig === 'string'
? { value: outputFileTemplateConfig }
: outputFileTemplateConfig),
emitLegacyCommonJSImports: shouldEmitLegacyCommonJSImports(config),
};
const documentTransforms = await Promise.all(
normalizeConfig(outputConfig.documentTransforms).map(async pluginConfig => {
const name = Object.keys(pluginConfig)[0];
const plugin = await getPluginByName(name, pluginLoader);
return { [name]: { plugin, config: Object.values(pluginConfig)[0] } };
})
);
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,
},
];
const process = async (outputArgs: Types.GenerateOptions) => {
const output = await codegen({
...outputArgs,
// @ts-expect-error todo: fix 'emitLegacyCommonJSImports' does not exist in type 'GenerateOptions'
emitLegacyCommonJSImports: shouldEmitLegacyCommonJSImports(config, outputArgs.filename),
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
),
},
],
{
// it stops when of the tasks failed
exitOnError: true,
}
);
},
// 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 });
},
},
],
{
rendererOptions: {
clearOutput: false,
collapse: true,
},
renderer: config.verbose ? 'verbose' : 'default',
ctx: { errors: [] },
rendererSilent: 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();
}
if (executedContext.errors.length > 0) {
const errors = executedContext.errors.map(subErr => subErr.message || subErr.toString());
const newErr = new AggregateError(executedContext.errors, String(errors.join('\n\n')));
// Best-effort to all stack traces for debugging
newErr.stack = `${newErr.stack}\n\n${executedContext.errors.map(subErr => subErr.stack).join('\n\n')}`;
throw newErr;
}
return result;
}