-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
codegen.ts
390 lines (340 loc) · 13.3 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
import {
DetailedError,
Types,
CodegenPlugin,
normalizeOutputParam,
normalizeInstanceOrArray,
normalizeConfig,
getCachedDocumentNodeFromSchema,
} from '@graphql-codegen/plugin-helpers';
import { codegen } from '@graphql-codegen/core';
import { Renderer, ErrorRenderer } from './utils/listr-renderer';
import { GraphQLError, GraphQLSchema, DocumentNode } from 'graphql';
import { getPluginByName } from './plugins';
import { getPresetByName } from './presets';
import { debugLog } from './utils/debugging';
import { CodegenContext, ensureContext } from './config';
import fs from 'fs';
import path from 'path';
// eslint-disable-next-line
import { createRequire } from 'module';
import Listr from 'listr';
const makeDefaultLoader = (from: string) => {
if (fs.statSync(from).isDirectory()) {
from = path.join(from, '__fake.js');
}
const relativeRequire = createRequire(from);
return (mod: string) => {
return import(relativeRequire.resolve(mod));
};
};
// TODO: Replace any with types
function createCache<T>(loader: (key: string) => Promise<T>) {
const cache = new Map<string, Promise<T>>();
return {
load(key: string): Promise<T> {
if (cache.has(key)) {
return cache.get(key);
}
const value = loader(key);
cache.set(key, 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[] = [];
const commonListrOptions = {
exitOnError: true,
};
let listr: Listr;
if (process.env.VERBOSE) {
listr = new Listr({
...commonListrOptions,
renderer: 'verbose',
nonTTYRenderer: 'verbose',
});
} else if (process.env.NODE_ENV === 'test') {
listr = new Listr({
...commonListrOptions,
renderer: 'silent',
nonTTYRenderer: 'silent',
});
} else {
listr = new Listr({
...commonListrOptions,
renderer: config.silent ? 'silent' : config.errorsOnly ? ErrorRenderer : Renderer,
nonTTYRenderer: config.silent ? 'silent' : 'default',
collapse: true,
clearOutput: false,
} as any);
}
let rootConfig: { [key: string]: any } = {};
let rootSchemas: Types.Schema[];
let rootDocuments: Types.OperationDocument[];
const generates: { [filename: string]: Types.ConfiguredOutput } = {};
const schemaLoadingCache = createCache(async function (hash) {
const outputSchemaAst = await context.loadSchema(JSON.parse(hash));
const outputSchema = getCachedDocumentNodeFromSchema(outputSchemaAst);
return {
outputSchemaAst: outputSchemaAst,
outputSchema: outputSchema,
};
});
const documentsLoadingCache = createCache(async function (hash) {
const documents = await context.loadDocuments(JSON.parse(hash));
return {
documents: documents,
};
});
function wrapTask(task: () => void | Promise<void>, source: string, taskName: string) {
return () => {
return context.profiler.run(async () => {
try {
await Promise.resolve().then(() => task());
} catch (error) {
if (source && !(error instanceof GraphQLError)) {
error.source = source;
}
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 DetailedError(
'Invalid Codegen Configuration!',
`
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 DetailedError(
'Invalid Codegen Configuration!',
`
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 || generates[filename].schema.length === 0)
) {
throw new DetailedError(
'Invalid Codegen Configuration!',
`
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
`
);
}
}
listr.add({
title: 'Parse configuration',
task: () => normalize(),
});
listr.add({
title: 'Generate outputs',
task: () => {
return new Listr(
Object.keys(generates).map<import('listr').ListrTask>(filename => {
const outputConfig = generates[filename];
const hasPreset = !!outputConfig.preset;
return {
title: hasPreset
? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
: `Generate ${filename}`,
task: () => {
let outputSchemaAst: GraphQLSchema;
let outputSchema: DocumentNode;
const outputFileTemplateConfig = outputConfig.config || {};
const outputDocuments: Types.DocumentFile[] = [];
const outputSpecificSchemas = normalizeInstanceOrArray<Types.Schema>(outputConfig.schema);
const outputSpecificDocuments = normalizeInstanceOrArray<Types.OperationDocument>(outputConfig.documents);
return new Listr(
[
{
title: 'Load GraphQL schemas',
task: wrapTask(
async () => {
debugLog(`[CLI] Loading Schemas`);
const schemaPointerMap: any = {};
const allSchemaUnnormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
for (const unnormalizedPtr of allSchemaUnnormalizedPointers) {
if (typeof unnormalizedPtr === 'string') {
schemaPointerMap[unnormalizedPtr] = {};
} else if (typeof unnormalizedPtr === 'object') {
Object.assign(schemaPointerMap, unnormalizedPtr);
}
}
const hash = JSON.stringify(schemaPointerMap);
const result = await schemaLoadingCache.load(hash);
outputSchemaAst = await result.outputSchemaAst;
outputSchema = result.outputSchema;
},
filename,
`Load GraphQL schemas: ${filename}`
),
},
{
title: 'Load GraphQL documents',
task: wrapTask(
async () => {
debugLog(`[CLI] Loading Documents`);
// get different cache for shared docs and output specific docs
const results = await Promise.all(
[rootDocuments, outputSpecificDocuments].map(docs => {
const hash = JSON.stringify(docs);
return documentsLoadingCache.load(hash);
})
);
const documents: Types.DocumentFile[] = [];
results.forEach(source => documents.push(...source.documents));
if (documents.length > 0) {
outputDocuments.push(...documents);
}
},
filename,
`Load GraphQL documents: ${filename}`
),
},
{
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 } = {};
const preset: Types.OutputPreset = hasPreset
? typeof outputConfig.preset === 'string'
? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
: outputConfig.preset
: null;
pluginPackages.forEach((pluginPackage, i) => {
const plugin = normalizedPluginsArray[i];
const name = Object.keys(plugin)[0];
pluginMap[name] = pluginPackage;
});
const mergedConfig = {
...rootConfig,
...(typeof outputFileTemplateConfig === 'string'
? { value: outputFileTemplateConfig }
: outputFileTemplateConfig),
};
let outputs: Types.GenerateOptions[] = [];
if (hasPreset) {
outputs = 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,
}),
`Build Generates Section: ${filename}`
);
} else {
outputs = [
{
filename,
plugins: normalizedPluginsArray,
schema: outputSchema,
schemaAst: outputSchemaAst,
documents: outputDocuments,
config: mergedConfig,
pluginMap,
pluginContext,
profiler: context.profiler,
},
];
}
const process = async (outputArgs: Types.GenerateOptions) => {
const output = await codegen(outputArgs);
result.push({
filename: outputArgs.filename,
content: output,
hooks: outputConfig.hooks || {},
});
};
await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
},
filename,
`Generate: ${filename}`
),
},
],
{
// it stops when one of tasks failed
exitOnError: true,
}
);
},
};
}),
{
// it doesn't stop when one of tasks failed, to finish at least some of outputs
exitOnError: false,
// run 4 at once
concurrent: 4,
}
);
},
});
await listr.run();
return result;
}