@graphql-codegen/cli 2.7.0 → 2.7.1-alpha-223b75f49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cjs/bin.js +13 -0
- package/cjs/cli.js +60 -0
- package/cjs/codegen.js +319 -0
- package/cjs/config.js +303 -0
- package/cjs/generate-and-save.js +110 -0
- package/cjs/graphql-config.js +69 -0
- package/cjs/hooks.js +87 -0
- package/cjs/index.js +13 -0
- package/cjs/init/helpers.js +64 -0
- package/cjs/init/index.js +60 -0
- package/cjs/init/plugins.js +163 -0
- package/cjs/init/questions.js +147 -0
- package/cjs/init/targets.js +44 -0
- package/cjs/init/types.js +14 -0
- package/cjs/load.js +93 -0
- package/cjs/package.json +1 -0
- package/cjs/plugins.js +45 -0
- package/cjs/presets.js +50 -0
- package/cjs/utils/cli-error.js +25 -0
- package/cjs/utils/debugging.js +27 -0
- package/cjs/utils/file-system.js +26 -0
- package/cjs/utils/logger.js +25 -0
- package/cjs/utils/watcher.js +140 -0
- package/esm/bin.js +11 -0
- package/esm/cli.js +32 -0
- package/esm/codegen.js +314 -0
- package/esm/config.js +290 -0
- package/esm/generate-and-save.js +105 -0
- package/esm/graphql-config.js +64 -0
- package/esm/hooks.js +83 -0
- package/esm/index.js +7 -0
- package/esm/init/helpers.js +55 -0
- package/esm/init/index.js +55 -0
- package/esm/init/plugins.js +160 -0
- package/esm/init/questions.js +140 -0
- package/esm/init/targets.js +40 -0
- package/esm/init/types.js +11 -0
- package/esm/load.js +88 -0
- package/esm/plugins.js +41 -0
- package/esm/presets.js +46 -0
- package/esm/utils/cli-error.js +20 -0
- package/esm/utils/debugging.js +21 -0
- package/esm/utils/file-system.js +19 -0
- package/esm/utils/logger.js +18 -0
- package/esm/utils/watcher.js +135 -0
- package/package.json +33 -29
- package/typings/bin.d.ts +2 -0
- package/{cli.d.ts → typings/cli.d.ts} +0 -0
- package/{codegen.d.ts → typings/codegen.d.ts} +1 -1
- package/{config.d.ts → typings/config.d.ts} +0 -0
- package/{generate-and-save.d.ts → typings/generate-and-save.d.ts} +1 -1
- package/{graphql-config.d.ts → typings/graphql-config.d.ts} +0 -0
- package/{hooks.d.ts → typings/hooks.d.ts} +0 -0
- package/typings/index.d.ts +7 -0
- package/{init → typings/init}/helpers.d.ts +1 -1
- package/{init → typings/init}/index.d.ts +0 -0
- package/{init → typings/init}/plugins.d.ts +1 -1
- package/{init → typings/init}/questions.d.ts +1 -1
- package/{init → typings/init}/targets.d.ts +1 -1
- package/{init → typings/init}/types.d.ts +0 -0
- package/{load.d.ts → typings/load.d.ts} +0 -0
- package/{plugins.d.ts → typings/plugins.d.ts} +0 -0
- package/{presets.d.ts → typings/presets.d.ts} +0 -0
- package/{utils → typings/utils}/cli-error.d.ts +0 -0
- package/{utils → typings/utils}/debugging.d.ts +0 -0
- package/{utils → typings/utils}/file-system.d.ts +0 -0
- package/{utils → typings/utils}/logger.d.ts +0 -0
- package/{utils → typings/utils}/watcher.d.ts +1 -1
- package/bin.d.ts +0 -1
- package/bin.js +0 -1891
- package/index.d.ts +0 -7
- package/index.js +0 -1902
- package/index.mjs +0 -1858
- package/utils/indentString.d.ts +0 -26
- package/utils/listr-renderer.d.ts +0 -18
package/index.mjs
DELETED
|
@@ -1,1858 +0,0 @@
|
|
|
1
|
-
import { isDetailedError, DetailedError, createNoopProfiler, createProfiler, getCachedDocumentNodeFromSchema, normalizeInstanceOrArray, normalizeConfig, normalizeOutputParam } from '@graphql-codegen/plugin-helpers';
|
|
2
|
-
import { codegen } from '@graphql-codegen/core';
|
|
3
|
-
import { AggregateError, isValidPath } from '@graphql-tools/utils';
|
|
4
|
-
import chalk from 'chalk';
|
|
5
|
-
import logSymbols from 'log-symbols';
|
|
6
|
-
import ansiEscapes from 'ansi-escapes';
|
|
7
|
-
import wrapAnsi from 'wrap-ansi';
|
|
8
|
-
import { stripIndent } from 'common-tags';
|
|
9
|
-
import { dummyLogger } from 'ts-log';
|
|
10
|
-
import UpdateRenderer from 'listr-update-renderer';
|
|
11
|
-
import { print, GraphQLError } from 'graphql';
|
|
12
|
-
import path, { resolve, extname, join, delimiter, sep, dirname, isAbsolute, relative } from 'path';
|
|
13
|
-
import { cosmiconfig, defaultLoaders } from 'cosmiconfig';
|
|
14
|
-
import { env } from 'string-env-interpolation';
|
|
15
|
-
import yargs from 'yargs';
|
|
16
|
-
import { loadConfig } from 'graphql-config';
|
|
17
|
-
import { ApolloEngineLoader } from '@graphql-tools/apollo-engine-loader';
|
|
18
|
-
import { CodeFileLoader } from '@graphql-tools/code-file-loader';
|
|
19
|
-
import { GitLoader } from '@graphql-tools/git-loader';
|
|
20
|
-
import { GithubLoader } from '@graphql-tools/github-loader';
|
|
21
|
-
import { PrismaLoader } from '@graphql-tools/prisma-loader';
|
|
22
|
-
import { loadSchema as loadSchema$1, loadDocuments as loadDocuments$1 } from '@graphql-tools/load';
|
|
23
|
-
import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';
|
|
24
|
-
import { JsonFileLoader } from '@graphql-tools/json-file-loader';
|
|
25
|
-
import { UrlLoader } from '@graphql-tools/url-loader';
|
|
26
|
-
import yaml from 'yaml';
|
|
27
|
-
import { createRequire } from 'module';
|
|
28
|
-
import fs, { promises, unlink, writeFileSync, readFileSync } from 'fs';
|
|
29
|
-
import { createHash } from 'crypto';
|
|
30
|
-
import { cpus } from 'os';
|
|
31
|
-
import Listr from 'listr';
|
|
32
|
-
import { exec } from 'child_process';
|
|
33
|
-
import isGlob from 'is-glob';
|
|
34
|
-
import debounce from 'debounce';
|
|
35
|
-
import mkdirp from 'mkdirp';
|
|
36
|
-
import inquirer from 'inquirer';
|
|
37
|
-
import detectIndent from 'detect-indent';
|
|
38
|
-
import getLatestVersion from 'latest-version';
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
Indent each line in a string.
|
|
42
|
-
@param string - The string to indent.
|
|
43
|
-
@param count - How many times you want `options.indent` repeated. Default: `1`.
|
|
44
|
-
@example
|
|
45
|
-
```
|
|
46
|
-
import indentString from 'indent-string';
|
|
47
|
-
indentString('Unicorns\nRainbows', 4);
|
|
48
|
-
//=> ' Unicorns\n Rainbows'
|
|
49
|
-
indentString('Unicorns\nRainbows', 4, {indent: '♥'});
|
|
50
|
-
//=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows'
|
|
51
|
-
```
|
|
52
|
-
*/
|
|
53
|
-
function indentString(string, count = 1, options = {}) {
|
|
54
|
-
const { indent = ' ', includeEmptyLines = false } = options;
|
|
55
|
-
if (typeof string !== 'string') {
|
|
56
|
-
throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);
|
|
57
|
-
}
|
|
58
|
-
if (typeof count !== 'number') {
|
|
59
|
-
throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);
|
|
60
|
-
}
|
|
61
|
-
if (count < 0) {
|
|
62
|
-
throw new RangeError(`Expected \`count\` to be at least 0, got \`${count}\``);
|
|
63
|
-
}
|
|
64
|
-
if (typeof indent !== 'string') {
|
|
65
|
-
throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);
|
|
66
|
-
}
|
|
67
|
-
if (count === 0) {
|
|
68
|
-
return string;
|
|
69
|
-
}
|
|
70
|
-
const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
|
|
71
|
-
return string.replace(regex, indent.repeat(count));
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
let logger;
|
|
75
|
-
function getLogger() {
|
|
76
|
-
return logger || dummyLogger;
|
|
77
|
-
}
|
|
78
|
-
useWinstonLogger();
|
|
79
|
-
function useWinstonLogger() {
|
|
80
|
-
if (logger && logger.levels) {
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
logger = console;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
let queue = [];
|
|
87
|
-
function debugLog(message, ...meta) {
|
|
88
|
-
if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) {
|
|
89
|
-
queue.push({
|
|
90
|
-
message,
|
|
91
|
-
meta,
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
function printLogs() {
|
|
96
|
-
if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) {
|
|
97
|
-
queue.forEach(log => {
|
|
98
|
-
getLogger().info(log.message, ...log.meta);
|
|
99
|
-
});
|
|
100
|
-
resetLogs();
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
function resetLogs() {
|
|
104
|
-
queue = [];
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
class Renderer {
|
|
108
|
-
constructor(tasks, options) {
|
|
109
|
-
this.updateRenderer = new UpdateRenderer(tasks, options);
|
|
110
|
-
}
|
|
111
|
-
render() {
|
|
112
|
-
return this.updateRenderer.render();
|
|
113
|
-
}
|
|
114
|
-
end(err) {
|
|
115
|
-
this.updateRenderer.end(err);
|
|
116
|
-
if (typeof err === 'undefined') {
|
|
117
|
-
logUpdate.clear();
|
|
118
|
-
return;
|
|
119
|
-
}
|
|
120
|
-
// persist the output
|
|
121
|
-
logUpdate.done();
|
|
122
|
-
// show errors
|
|
123
|
-
if (err) {
|
|
124
|
-
const errorCount = err.errors ? err.errors.length : 0;
|
|
125
|
-
if (errorCount > 0) {
|
|
126
|
-
const count = indentString(chalk.red.bold(`Found ${errorCount} error${errorCount > 1 ? 's' : ''}`), 1);
|
|
127
|
-
const details = err.errors
|
|
128
|
-
.map(error => {
|
|
129
|
-
debugLog(`[CLI] Exited with an error`, error);
|
|
130
|
-
return { msg: isDetailedError(error) ? error.details : null, rawError: error };
|
|
131
|
-
})
|
|
132
|
-
.map(({ msg, rawError }, i) => {
|
|
133
|
-
const source = err.errors[i].source;
|
|
134
|
-
msg = msg ? chalk.gray(indentString(stripIndent(`${msg}`), 4)) : null;
|
|
135
|
-
const stack = rawError.stack ? chalk.gray(indentString(stripIndent(rawError.stack), 4)) : null;
|
|
136
|
-
if (source) {
|
|
137
|
-
const sourceOfError = typeof source === 'string' ? source : source.name;
|
|
138
|
-
const title = indentString(`${logSymbols.error} ${sourceOfError}`, 2);
|
|
139
|
-
return [title, msg, stack, stack].filter(Boolean).join('\n');
|
|
140
|
-
}
|
|
141
|
-
return [msg, stack].filter(Boolean).join('\n');
|
|
142
|
-
})
|
|
143
|
-
.join('\n\n');
|
|
144
|
-
logUpdate.emit(['', count, details, ''].join('\n\n'));
|
|
145
|
-
}
|
|
146
|
-
else {
|
|
147
|
-
const details = err.details ? err.details : '';
|
|
148
|
-
logUpdate.emit(`${chalk.red.bold(`${indentString(err.message, 2)}`)}\n${details}\n${chalk.grey(err.stack)}`);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
logUpdate.done();
|
|
152
|
-
printLogs();
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
const render = tasks => {
|
|
156
|
-
for (const task of tasks) {
|
|
157
|
-
task.subscribe(event => {
|
|
158
|
-
if (event.type === 'SUBTASKS') {
|
|
159
|
-
render(task.subtasks);
|
|
160
|
-
return;
|
|
161
|
-
}
|
|
162
|
-
if (event.type === 'DATA') {
|
|
163
|
-
logUpdate.emit(chalk.dim(`${event.data}`));
|
|
164
|
-
}
|
|
165
|
-
logUpdate.done();
|
|
166
|
-
}, err => {
|
|
167
|
-
logUpdate.emit(err);
|
|
168
|
-
logUpdate.done();
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
};
|
|
172
|
-
class ErrorRenderer {
|
|
173
|
-
constructor(tasks, _options) {
|
|
174
|
-
this.tasks = tasks;
|
|
175
|
-
}
|
|
176
|
-
render() {
|
|
177
|
-
render(this.tasks);
|
|
178
|
-
}
|
|
179
|
-
static get nonTTY() {
|
|
180
|
-
return true;
|
|
181
|
-
}
|
|
182
|
-
end() { }
|
|
183
|
-
}
|
|
184
|
-
class LogUpdate {
|
|
185
|
-
constructor() {
|
|
186
|
-
this.stream = process.stdout;
|
|
187
|
-
// state
|
|
188
|
-
this.previousLineCount = 0;
|
|
189
|
-
this.previousOutput = '';
|
|
190
|
-
this.previousWidth = this.getWidth();
|
|
191
|
-
}
|
|
192
|
-
emit(...args) {
|
|
193
|
-
let output = args.join(' ') + '\n';
|
|
194
|
-
const width = this.getWidth();
|
|
195
|
-
if (output === this.previousOutput && this.previousWidth === width) {
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
this.previousOutput = output;
|
|
199
|
-
this.previousWidth = width;
|
|
200
|
-
output = wrapAnsi(output, width, {
|
|
201
|
-
trim: false,
|
|
202
|
-
hard: true,
|
|
203
|
-
wordWrap: false,
|
|
204
|
-
});
|
|
205
|
-
this.stream.write(ansiEscapes.eraseLines(this.previousLineCount) + output);
|
|
206
|
-
this.previousLineCount = output.split('\n').length;
|
|
207
|
-
}
|
|
208
|
-
clear() {
|
|
209
|
-
this.stream.write(ansiEscapes.eraseLines(this.previousLineCount));
|
|
210
|
-
this.previousOutput = '';
|
|
211
|
-
this.previousWidth = this.getWidth();
|
|
212
|
-
this.previousLineCount = 0;
|
|
213
|
-
}
|
|
214
|
-
done() {
|
|
215
|
-
this.previousOutput = '';
|
|
216
|
-
this.previousWidth = this.getWidth();
|
|
217
|
-
this.previousLineCount = 0;
|
|
218
|
-
}
|
|
219
|
-
getWidth() {
|
|
220
|
-
const { columns } = this.stream;
|
|
221
|
-
if (!columns) {
|
|
222
|
-
return 80;
|
|
223
|
-
}
|
|
224
|
-
return columns;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
const logUpdate = new LogUpdate();
|
|
228
|
-
|
|
229
|
-
async function getPluginByName(name, pluginLoader) {
|
|
230
|
-
const possibleNames = [
|
|
231
|
-
`@graphql-codegen/${name}`,
|
|
232
|
-
`@graphql-codegen/${name}-template`,
|
|
233
|
-
`@graphql-codegen/${name}-plugin`,
|
|
234
|
-
`graphql-codegen-${name}`,
|
|
235
|
-
`graphql-codegen-${name}-template`,
|
|
236
|
-
`graphql-codegen-${name}-plugin`,
|
|
237
|
-
`codegen-${name}`,
|
|
238
|
-
`codegen-${name}-template`,
|
|
239
|
-
name,
|
|
240
|
-
];
|
|
241
|
-
const possibleModules = possibleNames.concat(resolve(process.cwd(), name));
|
|
242
|
-
for (const moduleName of possibleModules) {
|
|
243
|
-
try {
|
|
244
|
-
return await pluginLoader(moduleName);
|
|
245
|
-
}
|
|
246
|
-
catch (err) {
|
|
247
|
-
if (err.code !== 'MODULE_NOT_FOUND') {
|
|
248
|
-
throw new DetailedError(`Unable to load template plugin matching ${name}`, `
|
|
249
|
-
Unable to load template plugin matching '${name}'.
|
|
250
|
-
Reason:
|
|
251
|
-
${err.message}
|
|
252
|
-
`);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
const possibleNamesMsg = possibleNames
|
|
257
|
-
.map(name => `
|
|
258
|
-
- ${name}
|
|
259
|
-
`.trimRight())
|
|
260
|
-
.join('');
|
|
261
|
-
throw new DetailedError(`Unable to find template plugin matching ${name}`, `
|
|
262
|
-
Unable to find template plugin matching '${name}'
|
|
263
|
-
Install one of the following packages:
|
|
264
|
-
|
|
265
|
-
${possibleNamesMsg}
|
|
266
|
-
`);
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
async function getPresetByName(name, loader) {
|
|
270
|
-
const possibleNames = [
|
|
271
|
-
`@graphql-codegen/${name}`,
|
|
272
|
-
`@graphql-codegen/${name}-preset`,
|
|
273
|
-
name,
|
|
274
|
-
resolve(process.cwd(), name),
|
|
275
|
-
];
|
|
276
|
-
for (const moduleName of possibleNames) {
|
|
277
|
-
try {
|
|
278
|
-
const loaded = await loader(moduleName);
|
|
279
|
-
if (loaded && loaded.preset) {
|
|
280
|
-
return loaded.preset;
|
|
281
|
-
}
|
|
282
|
-
if (loaded && loaded.default) {
|
|
283
|
-
return loaded.default;
|
|
284
|
-
}
|
|
285
|
-
return loaded;
|
|
286
|
-
}
|
|
287
|
-
catch (err) {
|
|
288
|
-
if (err.code !== 'MODULE_NOT_FOUND') {
|
|
289
|
-
throw new DetailedError(`Unable to load preset matching ${name}`, `
|
|
290
|
-
Unable to load preset matching '${name}'.
|
|
291
|
-
Reason:
|
|
292
|
-
${err.message}
|
|
293
|
-
`);
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
const possibleNamesMsg = possibleNames
|
|
298
|
-
.map(name => `
|
|
299
|
-
- ${name}
|
|
300
|
-
`.trimRight())
|
|
301
|
-
.join('');
|
|
302
|
-
throw new DetailedError(`Unable to find preset matching ${name}`, `
|
|
303
|
-
Unable to find preset matching '${name}'
|
|
304
|
-
Install one of the following packages:
|
|
305
|
-
|
|
306
|
-
${possibleNamesMsg}
|
|
307
|
-
`);
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
const CodegenExtension = (api) => {
|
|
311
|
-
// Schema
|
|
312
|
-
api.loaders.schema.register(new CodeFileLoader({
|
|
313
|
-
pluckConfig: {
|
|
314
|
-
skipIndent: true,
|
|
315
|
-
},
|
|
316
|
-
}));
|
|
317
|
-
api.loaders.schema.register(new GitLoader());
|
|
318
|
-
api.loaders.schema.register(new GithubLoader());
|
|
319
|
-
api.loaders.schema.register(new ApolloEngineLoader());
|
|
320
|
-
api.loaders.schema.register(new PrismaLoader());
|
|
321
|
-
// Documents
|
|
322
|
-
api.loaders.documents.register(new CodeFileLoader({
|
|
323
|
-
pluckConfig: {
|
|
324
|
-
skipIndent: true,
|
|
325
|
-
},
|
|
326
|
-
}));
|
|
327
|
-
api.loaders.documents.register(new GitLoader());
|
|
328
|
-
api.loaders.documents.register(new GithubLoader());
|
|
329
|
-
return {
|
|
330
|
-
name: 'codegen',
|
|
331
|
-
};
|
|
332
|
-
};
|
|
333
|
-
async function findAndLoadGraphQLConfig(filepath) {
|
|
334
|
-
const config = await loadConfig({
|
|
335
|
-
filepath,
|
|
336
|
-
rootDir: process.cwd(),
|
|
337
|
-
extensions: [CodegenExtension],
|
|
338
|
-
throwOnEmpty: false,
|
|
339
|
-
throwOnMissing: false,
|
|
340
|
-
});
|
|
341
|
-
if (isGraphQLConfig(config)) {
|
|
342
|
-
return config;
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
// Kamil: user might load a config that is not GraphQL Config
|
|
346
|
-
// so we need to check if it's a regular config or not
|
|
347
|
-
function isGraphQLConfig(config) {
|
|
348
|
-
if (!config) {
|
|
349
|
-
return false;
|
|
350
|
-
}
|
|
351
|
-
try {
|
|
352
|
-
return config.getDefault().hasExtension('codegen');
|
|
353
|
-
}
|
|
354
|
-
catch (e) { }
|
|
355
|
-
try {
|
|
356
|
-
for (const projectName in config.projects) {
|
|
357
|
-
if (config.projects.hasOwnProperty(projectName)) {
|
|
358
|
-
const project = config.projects[projectName];
|
|
359
|
-
if (project.hasExtension('codegen')) {
|
|
360
|
-
return true;
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
catch (e) { }
|
|
366
|
-
return false;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
const defaultSchemaLoadOptions = {
|
|
370
|
-
assumeValidSDL: true,
|
|
371
|
-
sort: true,
|
|
372
|
-
convertExtensions: true,
|
|
373
|
-
includeSources: true,
|
|
374
|
-
};
|
|
375
|
-
const defaultDocumentsLoadOptions = {
|
|
376
|
-
sort: true,
|
|
377
|
-
skipGraphQLImport: true,
|
|
378
|
-
};
|
|
379
|
-
async function loadSchema(schemaPointers, config) {
|
|
380
|
-
try {
|
|
381
|
-
const loaders = [
|
|
382
|
-
new CodeFileLoader(),
|
|
383
|
-
new GitLoader(),
|
|
384
|
-
new GithubLoader(),
|
|
385
|
-
new GraphQLFileLoader(),
|
|
386
|
-
new JsonFileLoader(),
|
|
387
|
-
new UrlLoader(),
|
|
388
|
-
new ApolloEngineLoader(),
|
|
389
|
-
new PrismaLoader(),
|
|
390
|
-
];
|
|
391
|
-
const schema = await loadSchema$1(schemaPointers, {
|
|
392
|
-
...defaultSchemaLoadOptions,
|
|
393
|
-
loaders,
|
|
394
|
-
...config,
|
|
395
|
-
...config.config,
|
|
396
|
-
});
|
|
397
|
-
return schema;
|
|
398
|
-
}
|
|
399
|
-
catch (e) {
|
|
400
|
-
throw new DetailedError('Failed to load schema', `
|
|
401
|
-
Failed to load schema from ${Object.keys(schemaPointers).join(',')}:
|
|
402
|
-
|
|
403
|
-
${e.message || e}
|
|
404
|
-
${e.stack || ''}
|
|
405
|
-
|
|
406
|
-
GraphQL Code Generator supports:
|
|
407
|
-
- ES Modules and CommonJS exports (export as default or named export "schema")
|
|
408
|
-
- Introspection JSON File
|
|
409
|
-
- URL of GraphQL endpoint
|
|
410
|
-
- Multiple files with type definitions (glob expression)
|
|
411
|
-
- String in config file
|
|
412
|
-
|
|
413
|
-
Try to use one of above options and run codegen again.
|
|
414
|
-
|
|
415
|
-
`);
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
async function loadDocuments(documentPointers, config) {
|
|
419
|
-
const loaders = [
|
|
420
|
-
new CodeFileLoader({
|
|
421
|
-
pluckConfig: {
|
|
422
|
-
skipIndent: true,
|
|
423
|
-
},
|
|
424
|
-
}),
|
|
425
|
-
new GitLoader(),
|
|
426
|
-
new GithubLoader(),
|
|
427
|
-
new GraphQLFileLoader(),
|
|
428
|
-
];
|
|
429
|
-
const ignore = [];
|
|
430
|
-
for (const generatePath of Object.keys(config.generates)) {
|
|
431
|
-
if (extname(generatePath) === '') {
|
|
432
|
-
// we omit paths that don't resolve to a specific file
|
|
433
|
-
continue;
|
|
434
|
-
}
|
|
435
|
-
ignore.push(join(process.cwd(), generatePath));
|
|
436
|
-
}
|
|
437
|
-
const loadedFromToolkit = await loadDocuments$1(documentPointers, {
|
|
438
|
-
...defaultDocumentsLoadOptions,
|
|
439
|
-
ignore,
|
|
440
|
-
loaders,
|
|
441
|
-
...config,
|
|
442
|
-
...config.config,
|
|
443
|
-
});
|
|
444
|
-
return loadedFromToolkit;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
const { lstat } = promises;
|
|
448
|
-
function generateSearchPlaces(moduleName) {
|
|
449
|
-
const extensions = ['json', 'yaml', 'yml', 'js', 'config.js'];
|
|
450
|
-
// gives codegen.json...
|
|
451
|
-
const regular = extensions.map(ext => `${moduleName}.${ext}`);
|
|
452
|
-
// gives .codegenrc.json... but no .codegenrc.config.js
|
|
453
|
-
const dot = extensions.filter(ext => ext !== 'config.js').map(ext => `.${moduleName}rc.${ext}`);
|
|
454
|
-
return [...regular.concat(dot), 'package.json'];
|
|
455
|
-
}
|
|
456
|
-
function customLoader(ext) {
|
|
457
|
-
function loader(filepath, content) {
|
|
458
|
-
if (typeof process !== 'undefined' && 'env' in process) {
|
|
459
|
-
content = env(content);
|
|
460
|
-
}
|
|
461
|
-
if (ext === 'json') {
|
|
462
|
-
return defaultLoaders['.json'](filepath, content);
|
|
463
|
-
}
|
|
464
|
-
if (ext === 'yaml') {
|
|
465
|
-
try {
|
|
466
|
-
const result = yaml.parse(content, { prettyErrors: true, merge: true });
|
|
467
|
-
return result;
|
|
468
|
-
}
|
|
469
|
-
catch (error) {
|
|
470
|
-
error.message = `YAML Error in ${filepath}:\n${error.message}`;
|
|
471
|
-
throw error;
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
if (ext === 'js') {
|
|
475
|
-
return defaultLoaders['.js'](filepath, content);
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
return loader;
|
|
479
|
-
}
|
|
480
|
-
async function loadCodegenConfig({ configFilePath, moduleName, searchPlaces: additionalSearchPlaces, packageProp, loaders: customLoaders, }) {
|
|
481
|
-
configFilePath = configFilePath || process.cwd();
|
|
482
|
-
moduleName = moduleName || 'codegen';
|
|
483
|
-
packageProp = packageProp || moduleName;
|
|
484
|
-
const cosmi = cosmiconfig(moduleName, {
|
|
485
|
-
searchPlaces: generateSearchPlaces(moduleName).concat(additionalSearchPlaces || []),
|
|
486
|
-
packageProp,
|
|
487
|
-
loaders: {
|
|
488
|
-
'.json': customLoader('json'),
|
|
489
|
-
'.yaml': customLoader('yaml'),
|
|
490
|
-
'.yml': customLoader('yaml'),
|
|
491
|
-
'.js': customLoader('js'),
|
|
492
|
-
noExt: customLoader('yaml'),
|
|
493
|
-
...customLoaders,
|
|
494
|
-
},
|
|
495
|
-
});
|
|
496
|
-
const pathStats = await lstat(configFilePath);
|
|
497
|
-
return pathStats.isDirectory() ? cosmi.search(configFilePath) : cosmi.load(configFilePath);
|
|
498
|
-
}
|
|
499
|
-
async function loadContext(configFilePath) {
|
|
500
|
-
const graphqlConfig = await findAndLoadGraphQLConfig(configFilePath);
|
|
501
|
-
if (graphqlConfig) {
|
|
502
|
-
return new CodegenContext({
|
|
503
|
-
graphqlConfig,
|
|
504
|
-
});
|
|
505
|
-
}
|
|
506
|
-
const result = await loadCodegenConfig({ configFilePath });
|
|
507
|
-
if (!result) {
|
|
508
|
-
if (configFilePath) {
|
|
509
|
-
throw new DetailedError(`Config ${configFilePath} does not exist`, `
|
|
510
|
-
Config ${configFilePath} does not exist.
|
|
511
|
-
|
|
512
|
-
$ graphql-codegen --config ${configFilePath}
|
|
513
|
-
|
|
514
|
-
Please make sure the --config points to a correct file.
|
|
515
|
-
`);
|
|
516
|
-
}
|
|
517
|
-
throw new DetailedError(`Unable to find Codegen config file!`, `
|
|
518
|
-
Please make sure that you have a configuration file under the current directory!
|
|
519
|
-
`);
|
|
520
|
-
}
|
|
521
|
-
if (result.isEmpty) {
|
|
522
|
-
throw new DetailedError(`Found Codegen config file but it was empty!`, `
|
|
523
|
-
Please make sure that you have a valid configuration file under the current directory!
|
|
524
|
-
`);
|
|
525
|
-
}
|
|
526
|
-
return new CodegenContext({
|
|
527
|
-
filepath: result.filepath,
|
|
528
|
-
config: result.config,
|
|
529
|
-
});
|
|
530
|
-
}
|
|
531
|
-
function getCustomConfigPath(cliFlags) {
|
|
532
|
-
const configFile = cliFlags.config;
|
|
533
|
-
return configFile ? resolve(process.cwd(), configFile) : null;
|
|
534
|
-
}
|
|
535
|
-
function buildOptions() {
|
|
536
|
-
return {
|
|
537
|
-
c: {
|
|
538
|
-
alias: 'config',
|
|
539
|
-
type: 'string',
|
|
540
|
-
describe: 'Path to GraphQL codegen YAML config file, defaults to "codegen.yml" on the current directory',
|
|
541
|
-
},
|
|
542
|
-
w: {
|
|
543
|
-
alias: 'watch',
|
|
544
|
-
describe: 'Watch for changes and execute generation automatically. You can also specify a glob expreession for custom watch list.',
|
|
545
|
-
coerce: (watch) => {
|
|
546
|
-
if (watch === 'false') {
|
|
547
|
-
return false;
|
|
548
|
-
}
|
|
549
|
-
if (typeof watch === 'string' || Array.isArray(watch)) {
|
|
550
|
-
return watch;
|
|
551
|
-
}
|
|
552
|
-
return !!watch;
|
|
553
|
-
},
|
|
554
|
-
},
|
|
555
|
-
r: {
|
|
556
|
-
alias: 'require',
|
|
557
|
-
describe: 'Loads specific require.extensions before running the codegen and reading the configuration',
|
|
558
|
-
type: 'array',
|
|
559
|
-
default: [],
|
|
560
|
-
},
|
|
561
|
-
o: {
|
|
562
|
-
alias: 'overwrite',
|
|
563
|
-
describe: 'Overwrites existing files',
|
|
564
|
-
type: 'boolean',
|
|
565
|
-
},
|
|
566
|
-
s: {
|
|
567
|
-
alias: 'silent',
|
|
568
|
-
describe: 'Suppresses printing errors',
|
|
569
|
-
type: 'boolean',
|
|
570
|
-
},
|
|
571
|
-
e: {
|
|
572
|
-
alias: 'errors-only',
|
|
573
|
-
describe: 'Only print errors',
|
|
574
|
-
type: 'boolean',
|
|
575
|
-
},
|
|
576
|
-
profile: {
|
|
577
|
-
describe: 'Use profiler to measure performance',
|
|
578
|
-
type: 'boolean',
|
|
579
|
-
},
|
|
580
|
-
p: {
|
|
581
|
-
alias: 'project',
|
|
582
|
-
describe: 'Name of a project in GraphQL Config',
|
|
583
|
-
type: 'string',
|
|
584
|
-
},
|
|
585
|
-
};
|
|
586
|
-
}
|
|
587
|
-
function parseArgv(argv = process.argv) {
|
|
588
|
-
return yargs.options(buildOptions()).parse(argv);
|
|
589
|
-
}
|
|
590
|
-
async function createContext(cliFlags = parseArgv(process.argv)) {
|
|
591
|
-
if (cliFlags.require && cliFlags.require.length > 0) {
|
|
592
|
-
const relativeRequire = createRequire(process.cwd());
|
|
593
|
-
await Promise.all(cliFlags.require.map(mod => import(relativeRequire.resolve(mod, {
|
|
594
|
-
paths: [process.cwd()],
|
|
595
|
-
}))));
|
|
596
|
-
}
|
|
597
|
-
const customConfigPath = getCustomConfigPath(cliFlags);
|
|
598
|
-
const context = await loadContext(customConfigPath);
|
|
599
|
-
updateContextWithCliFlags(context, cliFlags);
|
|
600
|
-
return context;
|
|
601
|
-
}
|
|
602
|
-
function updateContextWithCliFlags(context, cliFlags) {
|
|
603
|
-
const config = {
|
|
604
|
-
configFilePath: context.filepath,
|
|
605
|
-
};
|
|
606
|
-
if (cliFlags.watch) {
|
|
607
|
-
config.watch = cliFlags.watch;
|
|
608
|
-
}
|
|
609
|
-
if (cliFlags.overwrite === true) {
|
|
610
|
-
config.overwrite = cliFlags.overwrite;
|
|
611
|
-
}
|
|
612
|
-
if (cliFlags.silent === true) {
|
|
613
|
-
config.silent = cliFlags.silent;
|
|
614
|
-
}
|
|
615
|
-
if (cliFlags.errorsOnly === true) {
|
|
616
|
-
config.errorsOnly = cliFlags.errorsOnly;
|
|
617
|
-
}
|
|
618
|
-
if (cliFlags.project) {
|
|
619
|
-
context.useProject(cliFlags.project);
|
|
620
|
-
}
|
|
621
|
-
if (cliFlags.profile === true) {
|
|
622
|
-
context.useProfiler();
|
|
623
|
-
}
|
|
624
|
-
context.updateConfig(config);
|
|
625
|
-
}
|
|
626
|
-
class CodegenContext {
|
|
627
|
-
constructor({ config, graphqlConfig, filepath, }) {
|
|
628
|
-
this._pluginContext = {};
|
|
629
|
-
this._config = config;
|
|
630
|
-
this._graphqlConfig = graphqlConfig;
|
|
631
|
-
this.filepath = this._graphqlConfig ? this._graphqlConfig.filepath : filepath;
|
|
632
|
-
this.cwd = this._graphqlConfig ? this._graphqlConfig.dirpath : process.cwd();
|
|
633
|
-
this.profiler = createNoopProfiler();
|
|
634
|
-
}
|
|
635
|
-
useProject(name) {
|
|
636
|
-
this._project = name;
|
|
637
|
-
}
|
|
638
|
-
getConfig(extraConfig) {
|
|
639
|
-
if (!this.config) {
|
|
640
|
-
if (this._graphqlConfig) {
|
|
641
|
-
const project = this._graphqlConfig.getProject(this._project);
|
|
642
|
-
this.config = {
|
|
643
|
-
...project.extension('codegen'),
|
|
644
|
-
schema: project.schema,
|
|
645
|
-
documents: project.documents,
|
|
646
|
-
pluginContext: this._pluginContext,
|
|
647
|
-
};
|
|
648
|
-
}
|
|
649
|
-
else {
|
|
650
|
-
this.config = { ...this._config, pluginContext: this._pluginContext };
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
return {
|
|
654
|
-
...extraConfig,
|
|
655
|
-
...this.config,
|
|
656
|
-
};
|
|
657
|
-
}
|
|
658
|
-
updateConfig(config) {
|
|
659
|
-
this.config = {
|
|
660
|
-
...this.getConfig(),
|
|
661
|
-
...config,
|
|
662
|
-
};
|
|
663
|
-
}
|
|
664
|
-
useProfiler() {
|
|
665
|
-
this.profiler = createProfiler();
|
|
666
|
-
const now = new Date(); // 2011-10-05T14:48:00.000Z
|
|
667
|
-
const datetime = now.toISOString().split('.')[0]; // 2011-10-05T14:48:00
|
|
668
|
-
const datetimeNormalized = datetime.replace(/-|:/g, ''); // 20111005T144800
|
|
669
|
-
this.profilerOutput = `codegen-${datetimeNormalized}.json`;
|
|
670
|
-
}
|
|
671
|
-
getPluginContext() {
|
|
672
|
-
return this._pluginContext;
|
|
673
|
-
}
|
|
674
|
-
async loadSchema(pointer) {
|
|
675
|
-
const config = this.getConfig(defaultSchemaLoadOptions);
|
|
676
|
-
if (this._graphqlConfig) {
|
|
677
|
-
// TODO: SchemaWithLoader won't work here
|
|
678
|
-
return addHashToSchema(this._graphqlConfig.getProject(this._project).loadSchema(pointer, 'GraphQLSchema', config));
|
|
679
|
-
}
|
|
680
|
-
return addHashToSchema(loadSchema(pointer, config));
|
|
681
|
-
}
|
|
682
|
-
async loadDocuments(pointer) {
|
|
683
|
-
const config = this.getConfig(defaultDocumentsLoadOptions);
|
|
684
|
-
if (this._graphqlConfig) {
|
|
685
|
-
// TODO: pointer won't work here
|
|
686
|
-
return addHashToDocumentFiles(this._graphqlConfig.getProject(this._project).loadDocuments(pointer, config));
|
|
687
|
-
}
|
|
688
|
-
return addHashToDocumentFiles(loadDocuments(pointer, config));
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
function ensureContext(input) {
|
|
692
|
-
return input instanceof CodegenContext ? input : new CodegenContext({ config: input });
|
|
693
|
-
}
|
|
694
|
-
function hashContent(content) {
|
|
695
|
-
return createHash('sha256').update(content).digest('hex');
|
|
696
|
-
}
|
|
697
|
-
function hashSchema(schema) {
|
|
698
|
-
return hashContent(print(getCachedDocumentNodeFromSchema(schema)));
|
|
699
|
-
}
|
|
700
|
-
function addHashToSchema(schemaPromise) {
|
|
701
|
-
return schemaPromise.then(schema => {
|
|
702
|
-
// It's consumed later on. The general purpose is to use it for caching.
|
|
703
|
-
if (!schema.extensions) {
|
|
704
|
-
schema.extensions = {};
|
|
705
|
-
}
|
|
706
|
-
schema.extensions['hash'] = hashSchema(schema);
|
|
707
|
-
return schema;
|
|
708
|
-
});
|
|
709
|
-
}
|
|
710
|
-
function hashDocument(doc) {
|
|
711
|
-
if (doc.rawSDL) {
|
|
712
|
-
return hashContent(doc.rawSDL);
|
|
713
|
-
}
|
|
714
|
-
if (doc.document) {
|
|
715
|
-
return hashContent(print(doc.document));
|
|
716
|
-
}
|
|
717
|
-
return null;
|
|
718
|
-
}
|
|
719
|
-
function addHashToDocumentFiles(documentFilesPromise) {
|
|
720
|
-
return documentFilesPromise.then(documentFiles => documentFiles.map(doc => {
|
|
721
|
-
doc.hash = hashDocument(doc);
|
|
722
|
-
return doc;
|
|
723
|
-
}));
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
function isListrError(err) {
|
|
727
|
-
return err.name === 'ListrError' && Array.isArray(err.errors) && err.errors.length > 0;
|
|
728
|
-
}
|
|
729
|
-
function cliError(err, exitOnError = true) {
|
|
730
|
-
let msg;
|
|
731
|
-
if (err instanceof Error) {
|
|
732
|
-
msg = err.message || err.toString();
|
|
733
|
-
}
|
|
734
|
-
else if (typeof err === 'string') {
|
|
735
|
-
msg = err;
|
|
736
|
-
}
|
|
737
|
-
else {
|
|
738
|
-
msg = JSON.stringify(err);
|
|
739
|
-
}
|
|
740
|
-
// eslint-disable-next-line no-console
|
|
741
|
-
console.error(msg);
|
|
742
|
-
if (exitOnError) {
|
|
743
|
-
process.exit(1);
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
const makeDefaultLoader = (from) => {
|
|
748
|
-
if (fs.statSync(from).isDirectory()) {
|
|
749
|
-
from = path.join(from, '__fake.js');
|
|
750
|
-
}
|
|
751
|
-
const relativeRequire = createRequire(from);
|
|
752
|
-
return (mod) => {
|
|
753
|
-
return import(relativeRequire.resolve(mod));
|
|
754
|
-
};
|
|
755
|
-
};
|
|
756
|
-
function createCache() {
|
|
757
|
-
const cache = new Map();
|
|
758
|
-
return function ensure(namespace, key, factory) {
|
|
759
|
-
const cacheKey = `${namespace}:${key}`;
|
|
760
|
-
const cachedValue = cache.get(cacheKey);
|
|
761
|
-
if (cachedValue) {
|
|
762
|
-
return cachedValue;
|
|
763
|
-
}
|
|
764
|
-
const value = factory();
|
|
765
|
-
cache.set(cacheKey, value);
|
|
766
|
-
return value;
|
|
767
|
-
};
|
|
768
|
-
}
|
|
769
|
-
async function executeCodegen(input) {
|
|
770
|
-
const context = ensureContext(input);
|
|
771
|
-
const config = context.getConfig();
|
|
772
|
-
const pluginContext = context.getPluginContext();
|
|
773
|
-
const result = [];
|
|
774
|
-
const commonListrOptions = {
|
|
775
|
-
exitOnError: true,
|
|
776
|
-
};
|
|
777
|
-
let listr;
|
|
778
|
-
if (process.env.VERBOSE) {
|
|
779
|
-
listr = new Listr({
|
|
780
|
-
...commonListrOptions,
|
|
781
|
-
renderer: 'verbose',
|
|
782
|
-
nonTTYRenderer: 'verbose',
|
|
783
|
-
});
|
|
784
|
-
}
|
|
785
|
-
else if (process.env.NODE_ENV === 'test') {
|
|
786
|
-
listr = new Listr({
|
|
787
|
-
...commonListrOptions,
|
|
788
|
-
renderer: 'silent',
|
|
789
|
-
nonTTYRenderer: 'silent',
|
|
790
|
-
});
|
|
791
|
-
}
|
|
792
|
-
else {
|
|
793
|
-
listr = new Listr({
|
|
794
|
-
...commonListrOptions,
|
|
795
|
-
renderer: config.silent ? 'silent' : config.errorsOnly ? ErrorRenderer : Renderer,
|
|
796
|
-
nonTTYRenderer: config.silent ? 'silent' : 'default',
|
|
797
|
-
collapse: true,
|
|
798
|
-
clearOutput: false,
|
|
799
|
-
});
|
|
800
|
-
}
|
|
801
|
-
let rootConfig = {};
|
|
802
|
-
let rootSchemas;
|
|
803
|
-
let rootDocuments;
|
|
804
|
-
const generates = {};
|
|
805
|
-
const cache = createCache();
|
|
806
|
-
function wrapTask(task, source, taskName) {
|
|
807
|
-
return () => {
|
|
808
|
-
return context.profiler.run(async () => {
|
|
809
|
-
try {
|
|
810
|
-
await Promise.resolve().then(() => task());
|
|
811
|
-
}
|
|
812
|
-
catch (error) {
|
|
813
|
-
if (source && !(error instanceof GraphQLError)) {
|
|
814
|
-
error.source = source;
|
|
815
|
-
}
|
|
816
|
-
throw error;
|
|
817
|
-
}
|
|
818
|
-
}, taskName);
|
|
819
|
-
};
|
|
820
|
-
}
|
|
821
|
-
async function normalize() {
|
|
822
|
-
/* Load Require extensions */
|
|
823
|
-
const requireExtensions = normalizeInstanceOrArray(config.require);
|
|
824
|
-
const loader = makeDefaultLoader(context.cwd);
|
|
825
|
-
for (const mod of requireExtensions) {
|
|
826
|
-
await loader(mod);
|
|
827
|
-
}
|
|
828
|
-
/* Root plugin config */
|
|
829
|
-
rootConfig = config.config || {};
|
|
830
|
-
/* Normalize root "schema" field */
|
|
831
|
-
rootSchemas = normalizeInstanceOrArray(config.schema);
|
|
832
|
-
/* Normalize root "documents" field */
|
|
833
|
-
rootDocuments = normalizeInstanceOrArray(config.documents);
|
|
834
|
-
/* Normalize "generators" field */
|
|
835
|
-
const generateKeys = Object.keys(config.generates || {});
|
|
836
|
-
if (generateKeys.length === 0) {
|
|
837
|
-
throw new DetailedError('Invalid Codegen Configuration!', `
|
|
838
|
-
Please make sure that your codegen config file contains the "generates" field, with a specification for the plugins you need.
|
|
839
|
-
|
|
840
|
-
It should looks like that:
|
|
841
|
-
|
|
842
|
-
schema:
|
|
843
|
-
- my-schema.graphql
|
|
844
|
-
generates:
|
|
845
|
-
my-file.ts:
|
|
846
|
-
- plugin1
|
|
847
|
-
- plugin2
|
|
848
|
-
- plugin3
|
|
849
|
-
`);
|
|
850
|
-
}
|
|
851
|
-
for (const filename of generateKeys) {
|
|
852
|
-
const output = (generates[filename] = normalizeOutputParam(config.generates[filename]));
|
|
853
|
-
if (!output.preset && (!output.plugins || output.plugins.length === 0)) {
|
|
854
|
-
throw new DetailedError('Invalid Codegen Configuration!', `
|
|
855
|
-
Please make sure that your codegen config file has defined plugins list for output "${filename}".
|
|
856
|
-
|
|
857
|
-
It should looks like that:
|
|
858
|
-
|
|
859
|
-
schema:
|
|
860
|
-
- my-schema.graphql
|
|
861
|
-
generates:
|
|
862
|
-
my-file.ts:
|
|
863
|
-
- plugin1
|
|
864
|
-
- plugin2
|
|
865
|
-
- plugin3
|
|
866
|
-
`);
|
|
867
|
-
}
|
|
868
|
-
}
|
|
869
|
-
if (rootSchemas.length === 0 &&
|
|
870
|
-
Object.keys(generates).some(filename => !generates[filename].schema || generates[filename].schema.length === 0)) {
|
|
871
|
-
throw new DetailedError('Invalid Codegen Configuration!', `
|
|
872
|
-
Please make sure that your codegen config file contains either the "schema" field
|
|
873
|
-
or every generated file has its own "schema" field.
|
|
874
|
-
|
|
875
|
-
It should looks like that:
|
|
876
|
-
schema:
|
|
877
|
-
- my-schema.graphql
|
|
878
|
-
|
|
879
|
-
or:
|
|
880
|
-
generates:
|
|
881
|
-
path/to/output:
|
|
882
|
-
schema: my-schema.graphql
|
|
883
|
-
`);
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
listr.add({
|
|
887
|
-
title: 'Parse configuration',
|
|
888
|
-
task: () => normalize(),
|
|
889
|
-
});
|
|
890
|
-
listr.add({
|
|
891
|
-
title: 'Generate outputs',
|
|
892
|
-
task: () => {
|
|
893
|
-
return new Listr(Object.keys(generates).map(filename => {
|
|
894
|
-
const outputConfig = generates[filename];
|
|
895
|
-
const hasPreset = !!outputConfig.preset;
|
|
896
|
-
return {
|
|
897
|
-
title: hasPreset
|
|
898
|
-
? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
|
|
899
|
-
: `Generate ${filename}`,
|
|
900
|
-
task: () => {
|
|
901
|
-
let outputSchemaAst;
|
|
902
|
-
let outputSchema;
|
|
903
|
-
const outputFileTemplateConfig = outputConfig.config || {};
|
|
904
|
-
let outputDocuments = [];
|
|
905
|
-
const outputSpecificSchemas = normalizeInstanceOrArray(outputConfig.schema);
|
|
906
|
-
const outputSpecificDocuments = normalizeInstanceOrArray(outputConfig.documents);
|
|
907
|
-
return new Listr([
|
|
908
|
-
{
|
|
909
|
-
title: 'Load GraphQL schemas',
|
|
910
|
-
task: wrapTask(async () => {
|
|
911
|
-
debugLog(`[CLI] Loading Schemas`);
|
|
912
|
-
const schemaPointerMap = {};
|
|
913
|
-
const allSchemaUnnormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
|
|
914
|
-
for (const unnormalizedPtr of allSchemaUnnormalizedPointers) {
|
|
915
|
-
if (typeof unnormalizedPtr === 'string') {
|
|
916
|
-
schemaPointerMap[unnormalizedPtr] = {};
|
|
917
|
-
}
|
|
918
|
-
else if (typeof unnormalizedPtr === 'object') {
|
|
919
|
-
Object.assign(schemaPointerMap, unnormalizedPtr);
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
const hash = JSON.stringify(schemaPointerMap);
|
|
923
|
-
const result = await cache('schema', hash, async () => {
|
|
924
|
-
const outputSchemaAst = await context.loadSchema(schemaPointerMap);
|
|
925
|
-
const outputSchema = getCachedDocumentNodeFromSchema(outputSchemaAst);
|
|
926
|
-
return {
|
|
927
|
-
outputSchemaAst,
|
|
928
|
-
outputSchema,
|
|
929
|
-
};
|
|
930
|
-
});
|
|
931
|
-
outputSchemaAst = await result.outputSchemaAst;
|
|
932
|
-
outputSchema = result.outputSchema;
|
|
933
|
-
}, filename, `Load GraphQL schemas: ${filename}`),
|
|
934
|
-
},
|
|
935
|
-
{
|
|
936
|
-
title: 'Load GraphQL documents',
|
|
937
|
-
task: wrapTask(async () => {
|
|
938
|
-
debugLog(`[CLI] Loading Documents`);
|
|
939
|
-
// get different cache for shared docs and output specific docs
|
|
940
|
-
const documentPointerMap = {};
|
|
941
|
-
const allDocumentsUnnormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
|
|
942
|
-
for (const unnormalizedPtr of allDocumentsUnnormalizedPointers) {
|
|
943
|
-
if (typeof unnormalizedPtr === 'string') {
|
|
944
|
-
documentPointerMap[unnormalizedPtr] = {};
|
|
945
|
-
}
|
|
946
|
-
else if (typeof unnormalizedPtr === 'object') {
|
|
947
|
-
Object.assign(documentPointerMap, unnormalizedPtr);
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
const hash = JSON.stringify(documentPointerMap);
|
|
951
|
-
const result = await cache('documents', hash, async () => {
|
|
952
|
-
const documents = await context.loadDocuments(documentPointerMap);
|
|
953
|
-
return {
|
|
954
|
-
documents,
|
|
955
|
-
};
|
|
956
|
-
});
|
|
957
|
-
outputDocuments = await result.documents;
|
|
958
|
-
}, filename, `Load GraphQL documents: ${filename}`),
|
|
959
|
-
},
|
|
960
|
-
{
|
|
961
|
-
title: 'Generate',
|
|
962
|
-
task: wrapTask(async () => {
|
|
963
|
-
debugLog(`[CLI] Generating output`);
|
|
964
|
-
const normalizedPluginsArray = normalizeConfig(outputConfig.plugins);
|
|
965
|
-
const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
|
|
966
|
-
const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => getPluginByName(Object.keys(plugin)[0], pluginLoader)));
|
|
967
|
-
const pluginMap = {};
|
|
968
|
-
const preset = hasPreset
|
|
969
|
-
? typeof outputConfig.preset === 'string'
|
|
970
|
-
? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
|
|
971
|
-
: outputConfig.preset
|
|
972
|
-
: null;
|
|
973
|
-
pluginPackages.forEach((pluginPackage, i) => {
|
|
974
|
-
const plugin = normalizedPluginsArray[i];
|
|
975
|
-
const name = Object.keys(plugin)[0];
|
|
976
|
-
pluginMap[name] = pluginPackage;
|
|
977
|
-
});
|
|
978
|
-
const mergedConfig = {
|
|
979
|
-
...rootConfig,
|
|
980
|
-
...(typeof outputFileTemplateConfig === 'string'
|
|
981
|
-
? { value: outputFileTemplateConfig }
|
|
982
|
-
: outputFileTemplateConfig),
|
|
983
|
-
};
|
|
984
|
-
let outputs = [];
|
|
985
|
-
if (hasPreset) {
|
|
986
|
-
outputs = await context.profiler.run(async () => preset.buildGeneratesSection({
|
|
987
|
-
baseOutputDir: filename,
|
|
988
|
-
presetConfig: outputConfig.presetConfig || {},
|
|
989
|
-
plugins: normalizedPluginsArray,
|
|
990
|
-
schema: outputSchema,
|
|
991
|
-
schemaAst: outputSchemaAst,
|
|
992
|
-
documents: outputDocuments,
|
|
993
|
-
config: mergedConfig,
|
|
994
|
-
pluginMap,
|
|
995
|
-
pluginContext,
|
|
996
|
-
profiler: context.profiler,
|
|
997
|
-
}), `Build Generates Section: ${filename}`);
|
|
998
|
-
}
|
|
999
|
-
else {
|
|
1000
|
-
outputs = [
|
|
1001
|
-
{
|
|
1002
|
-
filename,
|
|
1003
|
-
plugins: normalizedPluginsArray,
|
|
1004
|
-
schema: outputSchema,
|
|
1005
|
-
schemaAst: outputSchemaAst,
|
|
1006
|
-
documents: outputDocuments,
|
|
1007
|
-
config: mergedConfig,
|
|
1008
|
-
pluginMap,
|
|
1009
|
-
pluginContext,
|
|
1010
|
-
profiler: context.profiler,
|
|
1011
|
-
},
|
|
1012
|
-
];
|
|
1013
|
-
}
|
|
1014
|
-
const process = async (outputArgs) => {
|
|
1015
|
-
const output = await codegen({
|
|
1016
|
-
...outputArgs,
|
|
1017
|
-
cache,
|
|
1018
|
-
});
|
|
1019
|
-
result.push({
|
|
1020
|
-
filename: outputArgs.filename,
|
|
1021
|
-
content: output,
|
|
1022
|
-
hooks: outputConfig.hooks || {},
|
|
1023
|
-
});
|
|
1024
|
-
};
|
|
1025
|
-
await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
|
|
1026
|
-
}, filename, `Generate: ${filename}`),
|
|
1027
|
-
},
|
|
1028
|
-
], {
|
|
1029
|
-
// it stops when one of tasks failed
|
|
1030
|
-
exitOnError: true,
|
|
1031
|
-
});
|
|
1032
|
-
},
|
|
1033
|
-
};
|
|
1034
|
-
}), {
|
|
1035
|
-
// it doesn't stop when one of tasks failed, to finish at least some of outputs
|
|
1036
|
-
exitOnError: false,
|
|
1037
|
-
concurrent: cpus().length,
|
|
1038
|
-
});
|
|
1039
|
-
},
|
|
1040
|
-
});
|
|
1041
|
-
try {
|
|
1042
|
-
await listr.run();
|
|
1043
|
-
}
|
|
1044
|
-
catch (err) {
|
|
1045
|
-
if (isListrError(err)) {
|
|
1046
|
-
const allErrs = err.errors.map(subErr => isDetailedError(subErr)
|
|
1047
|
-
? `${subErr.message} for "${subErr.source}"${subErr.details}`
|
|
1048
|
-
: subErr.message || subErr.toString());
|
|
1049
|
-
const newErr = new AggregateError(err.errors, `${err.message} ${allErrs.join('\n\n')}`);
|
|
1050
|
-
// Best-effort to all stack traces for debugging
|
|
1051
|
-
newErr.stack = `${newErr.stack}\n\n${err.errors.map(subErr => subErr.stack).join('\n\n')}`;
|
|
1052
|
-
throw newErr;
|
|
1053
|
-
}
|
|
1054
|
-
throw err;
|
|
1055
|
-
}
|
|
1056
|
-
return result;
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
const DEFAULT_HOOKS = {
|
|
1060
|
-
afterStart: [],
|
|
1061
|
-
beforeDone: [],
|
|
1062
|
-
onWatchTriggered: [],
|
|
1063
|
-
onError: [],
|
|
1064
|
-
afterOneFileWrite: [],
|
|
1065
|
-
afterAllFileWrite: [],
|
|
1066
|
-
beforeOneFileWrite: [],
|
|
1067
|
-
beforeAllFileWrite: [],
|
|
1068
|
-
};
|
|
1069
|
-
function normalizeHooks(_hooks) {
|
|
1070
|
-
const keys = Object.keys({
|
|
1071
|
-
...DEFAULT_HOOKS,
|
|
1072
|
-
..._hooks,
|
|
1073
|
-
});
|
|
1074
|
-
return keys.reduce((prev, hookName) => {
|
|
1075
|
-
if (typeof _hooks[hookName] === 'string') {
|
|
1076
|
-
return {
|
|
1077
|
-
...prev,
|
|
1078
|
-
[hookName]: [_hooks[hookName]],
|
|
1079
|
-
};
|
|
1080
|
-
}
|
|
1081
|
-
if (typeof _hooks[hookName] === 'function') {
|
|
1082
|
-
return {
|
|
1083
|
-
...prev,
|
|
1084
|
-
[hookName]: [_hooks[hookName]],
|
|
1085
|
-
};
|
|
1086
|
-
}
|
|
1087
|
-
if (Array.isArray(_hooks[hookName])) {
|
|
1088
|
-
return {
|
|
1089
|
-
...prev,
|
|
1090
|
-
[hookName]: _hooks[hookName],
|
|
1091
|
-
};
|
|
1092
|
-
}
|
|
1093
|
-
return prev;
|
|
1094
|
-
}, {});
|
|
1095
|
-
}
|
|
1096
|
-
function execShellCommand(cmd) {
|
|
1097
|
-
return new Promise((resolve, reject) => {
|
|
1098
|
-
exec(cmd, {
|
|
1099
|
-
env: {
|
|
1100
|
-
...process.env,
|
|
1101
|
-
PATH: `${process.env.PATH}${delimiter}${process.cwd()}${sep}node_modules${sep}.bin`,
|
|
1102
|
-
},
|
|
1103
|
-
}, (error, stdout, stderr) => {
|
|
1104
|
-
if (error) {
|
|
1105
|
-
reject(error);
|
|
1106
|
-
}
|
|
1107
|
-
else {
|
|
1108
|
-
resolve(stdout || stderr);
|
|
1109
|
-
}
|
|
1110
|
-
});
|
|
1111
|
-
});
|
|
1112
|
-
}
|
|
1113
|
-
async function executeHooks(hookName, scripts = [], args = []) {
|
|
1114
|
-
debugLog(`Running lifecycle hook "${hookName}" scripts...`);
|
|
1115
|
-
for (const script of scripts) {
|
|
1116
|
-
if (typeof script === 'string') {
|
|
1117
|
-
debugLog(`Running lifecycle hook "${hookName}" script: ${script} with args: ${args.join(' ')}...`);
|
|
1118
|
-
await execShellCommand(`${script} ${args.join(' ')}`);
|
|
1119
|
-
}
|
|
1120
|
-
else {
|
|
1121
|
-
debugLog(`Running lifecycle hook "${hookName}" script: ${script.name} with args: ${args.join(' ')}...`);
|
|
1122
|
-
await script(...args);
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
const lifecycleHooks = (_hooks = {}) => {
|
|
1127
|
-
const hooks = normalizeHooks(_hooks);
|
|
1128
|
-
return {
|
|
1129
|
-
afterStart: async () => executeHooks('afterStart', hooks.afterStart),
|
|
1130
|
-
onWatchTriggered: async (event, path) => executeHooks('onWatchTriggered', hooks.onWatchTriggered, [event, path]),
|
|
1131
|
-
onError: async (error) => executeHooks('onError', hooks.onError, [`"${error}"`]),
|
|
1132
|
-
afterOneFileWrite: async (path) => executeHooks('afterOneFileWrite', hooks.afterOneFileWrite, [path]),
|
|
1133
|
-
afterAllFileWrite: async (paths) => executeHooks('afterAllFileWrite', hooks.afterAllFileWrite, paths),
|
|
1134
|
-
beforeOneFileWrite: async (path) => executeHooks('beforeOneFileWrite', hooks.beforeOneFileWrite, [path]),
|
|
1135
|
-
beforeAllFileWrite: async (paths) => executeHooks('beforeAllFileWrite', hooks.beforeAllFileWrite, paths),
|
|
1136
|
-
beforeDone: async () => executeHooks('beforeDone', hooks.beforeDone),
|
|
1137
|
-
};
|
|
1138
|
-
};
|
|
1139
|
-
|
|
1140
|
-
function log(msg) {
|
|
1141
|
-
// double spaces to inline the message with Listr
|
|
1142
|
-
getLogger().info(` ${msg}`);
|
|
1143
|
-
}
|
|
1144
|
-
function emitWatching() {
|
|
1145
|
-
log(`${logSymbols.info} Watching for changes...`);
|
|
1146
|
-
}
|
|
1147
|
-
const createWatcher = (initalContext, onNext) => {
|
|
1148
|
-
debugLog(`[Watcher] Starting watcher...`);
|
|
1149
|
-
let config = initalContext.getConfig();
|
|
1150
|
-
const files = [initalContext.filepath].filter(a => a);
|
|
1151
|
-
const documents = normalizeInstanceOrArray(config.documents);
|
|
1152
|
-
const schemas = normalizeInstanceOrArray(config.schema);
|
|
1153
|
-
// Add schemas and documents from "generates"
|
|
1154
|
-
Object.keys(config.generates)
|
|
1155
|
-
.map(filename => normalizeOutputParam(config.generates[filename]))
|
|
1156
|
-
.forEach(conf => {
|
|
1157
|
-
schemas.push(...normalizeInstanceOrArray(conf.schema));
|
|
1158
|
-
documents.push(...normalizeInstanceOrArray(conf.documents));
|
|
1159
|
-
});
|
|
1160
|
-
if (documents) {
|
|
1161
|
-
documents.forEach(doc => {
|
|
1162
|
-
if (typeof doc === 'string') {
|
|
1163
|
-
files.push(doc);
|
|
1164
|
-
}
|
|
1165
|
-
else {
|
|
1166
|
-
files.push(...Object.keys(doc));
|
|
1167
|
-
}
|
|
1168
|
-
});
|
|
1169
|
-
}
|
|
1170
|
-
schemas.forEach((schema) => {
|
|
1171
|
-
if (isGlob(schema) || isValidPath(schema)) {
|
|
1172
|
-
files.push(schema);
|
|
1173
|
-
}
|
|
1174
|
-
});
|
|
1175
|
-
if (typeof config.watch !== 'boolean') {
|
|
1176
|
-
files.push(...normalizeInstanceOrArray(config.watch));
|
|
1177
|
-
}
|
|
1178
|
-
let watcher;
|
|
1179
|
-
const runWatcher = async () => {
|
|
1180
|
-
var _a, _b;
|
|
1181
|
-
const chokidar = await import('chokidar');
|
|
1182
|
-
let isShutdown = false;
|
|
1183
|
-
const debouncedExec = debounce(() => {
|
|
1184
|
-
if (!isShutdown) {
|
|
1185
|
-
executeCodegen(initalContext)
|
|
1186
|
-
.then(onNext, () => Promise.resolve())
|
|
1187
|
-
.then(() => emitWatching());
|
|
1188
|
-
}
|
|
1189
|
-
}, 100);
|
|
1190
|
-
emitWatching();
|
|
1191
|
-
const ignored = [];
|
|
1192
|
-
Object.keys(config.generates)
|
|
1193
|
-
.map(filename => ({ filename, config: normalizeOutputParam(config.generates[filename]) }))
|
|
1194
|
-
.forEach(entry => {
|
|
1195
|
-
if (entry.config.preset) {
|
|
1196
|
-
const extension = entry.config.presetConfig && entry.config.presetConfig.extension;
|
|
1197
|
-
if (extension) {
|
|
1198
|
-
ignored.push(join(entry.filename, '**', '*' + extension));
|
|
1199
|
-
}
|
|
1200
|
-
}
|
|
1201
|
-
else {
|
|
1202
|
-
ignored.push(entry.filename);
|
|
1203
|
-
}
|
|
1204
|
-
});
|
|
1205
|
-
watcher = chokidar.watch(files, {
|
|
1206
|
-
persistent: true,
|
|
1207
|
-
ignoreInitial: true,
|
|
1208
|
-
followSymlinks: true,
|
|
1209
|
-
cwd: process.cwd(),
|
|
1210
|
-
disableGlobbing: false,
|
|
1211
|
-
usePolling: (_a = config.watchConfig) === null || _a === void 0 ? void 0 : _a.usePolling,
|
|
1212
|
-
interval: (_b = config.watchConfig) === null || _b === void 0 ? void 0 : _b.interval,
|
|
1213
|
-
depth: 99,
|
|
1214
|
-
awaitWriteFinish: true,
|
|
1215
|
-
ignorePermissionErrors: false,
|
|
1216
|
-
atomic: true,
|
|
1217
|
-
ignored,
|
|
1218
|
-
});
|
|
1219
|
-
debugLog(`[Watcher] Started`);
|
|
1220
|
-
const shutdown = () => {
|
|
1221
|
-
isShutdown = true;
|
|
1222
|
-
debugLog(`[Watcher] Shutting down`);
|
|
1223
|
-
log(`Shutting down watch...`);
|
|
1224
|
-
watcher.close();
|
|
1225
|
-
lifecycleHooks(config.hooks).beforeDone();
|
|
1226
|
-
};
|
|
1227
|
-
// it doesn't matter what has changed, need to run whole process anyway
|
|
1228
|
-
watcher.on('all', async (eventName, path) => {
|
|
1229
|
-
lifecycleHooks(config.hooks).onWatchTriggered(eventName, path);
|
|
1230
|
-
debugLog(`[Watcher] triggered due to a file ${eventName} event: ${path}`);
|
|
1231
|
-
const fullPath = join(process.cwd(), path);
|
|
1232
|
-
// In ESM require is not defined
|
|
1233
|
-
try {
|
|
1234
|
-
delete require.cache[fullPath];
|
|
1235
|
-
}
|
|
1236
|
-
catch (err) { }
|
|
1237
|
-
if (eventName === 'change' && config.configFilePath && fullPath === config.configFilePath) {
|
|
1238
|
-
log(`${logSymbols.info} Config file has changed, reloading...`);
|
|
1239
|
-
const context = await loadContext(config.configFilePath);
|
|
1240
|
-
const newParsedConfig = context.getConfig();
|
|
1241
|
-
newParsedConfig.watch = config.watch;
|
|
1242
|
-
newParsedConfig.silent = config.silent;
|
|
1243
|
-
newParsedConfig.overwrite = config.overwrite;
|
|
1244
|
-
newParsedConfig.configFilePath = config.configFilePath;
|
|
1245
|
-
config = newParsedConfig;
|
|
1246
|
-
initalContext.updateConfig(config);
|
|
1247
|
-
}
|
|
1248
|
-
debouncedExec();
|
|
1249
|
-
});
|
|
1250
|
-
process.once('SIGINT', shutdown);
|
|
1251
|
-
process.once('SIGTERM', shutdown);
|
|
1252
|
-
};
|
|
1253
|
-
// the promise never resolves to keep process running
|
|
1254
|
-
return new Promise((resolve, reject) => {
|
|
1255
|
-
executeCodegen(initalContext)
|
|
1256
|
-
.then(onNext, () => Promise.resolve())
|
|
1257
|
-
.then(runWatcher)
|
|
1258
|
-
.catch(err => {
|
|
1259
|
-
watcher.close();
|
|
1260
|
-
reject(err);
|
|
1261
|
-
});
|
|
1262
|
-
});
|
|
1263
|
-
};
|
|
1264
|
-
|
|
1265
|
-
const { writeFile: fsWriteFile, readFile: fsReadFile, stat: fsStat } = promises;
|
|
1266
|
-
function writeFile(filepath, content) {
|
|
1267
|
-
return fsWriteFile(filepath, content);
|
|
1268
|
-
}
|
|
1269
|
-
function readFile(filepath) {
|
|
1270
|
-
return fsReadFile(filepath, 'utf-8');
|
|
1271
|
-
}
|
|
1272
|
-
async function fileExists(filePath) {
|
|
1273
|
-
try {
|
|
1274
|
-
return (await fsStat(filePath)).isFile();
|
|
1275
|
-
}
|
|
1276
|
-
catch (err) {
|
|
1277
|
-
return false;
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
function unlinkFile(filePath, cb) {
|
|
1281
|
-
unlink(filePath, cb);
|
|
1282
|
-
}
|
|
1283
|
-
|
|
1284
|
-
const hash = (content) => createHash('sha1').update(content).digest('base64');
|
|
1285
|
-
async function generate(input, saveToFile = true) {
|
|
1286
|
-
const context = ensureContext(input);
|
|
1287
|
-
const config = context.getConfig();
|
|
1288
|
-
await context.profiler.run(() => lifecycleHooks(config.hooks).afterStart(), 'Lifecycle: afterStart');
|
|
1289
|
-
let previouslyGeneratedFilenames = [];
|
|
1290
|
-
function removeStaleFiles(config, generationResult) {
|
|
1291
|
-
const filenames = generationResult.map(o => o.filename);
|
|
1292
|
-
// find stale files from previous build which are not present in current build
|
|
1293
|
-
const staleFilenames = previouslyGeneratedFilenames.filter(f => !filenames.includes(f));
|
|
1294
|
-
staleFilenames.forEach(filename => {
|
|
1295
|
-
if (shouldOverwrite(config, filename)) {
|
|
1296
|
-
return unlinkFile(filename, err => {
|
|
1297
|
-
const prettyFilename = filename.replace(`${input.cwd || process.cwd()}/`, '');
|
|
1298
|
-
if (err) {
|
|
1299
|
-
debugLog(`Cannot remove stale file: ${prettyFilename}\n${err}`);
|
|
1300
|
-
}
|
|
1301
|
-
else {
|
|
1302
|
-
debugLog(`Removed stale file: ${prettyFilename}`);
|
|
1303
|
-
}
|
|
1304
|
-
});
|
|
1305
|
-
}
|
|
1306
|
-
});
|
|
1307
|
-
previouslyGeneratedFilenames = filenames;
|
|
1308
|
-
}
|
|
1309
|
-
const recentOutputHash = new Map();
|
|
1310
|
-
async function writeOutput(generationResult) {
|
|
1311
|
-
if (!saveToFile) {
|
|
1312
|
-
return generationResult;
|
|
1313
|
-
}
|
|
1314
|
-
if (config.watch) {
|
|
1315
|
-
removeStaleFiles(config, generationResult);
|
|
1316
|
-
}
|
|
1317
|
-
await context.profiler.run(async () => {
|
|
1318
|
-
await lifecycleHooks(config.hooks).beforeAllFileWrite(generationResult.map(r => r.filename));
|
|
1319
|
-
}, 'Lifecycle: beforeAllFileWrite');
|
|
1320
|
-
await context.profiler.run(() => Promise.all(generationResult.map(async (result) => {
|
|
1321
|
-
const exists = await fileExists(result.filename);
|
|
1322
|
-
if (!shouldOverwrite(config, result.filename) && exists) {
|
|
1323
|
-
return;
|
|
1324
|
-
}
|
|
1325
|
-
const content = result.content || '';
|
|
1326
|
-
const currentHash = hash(content);
|
|
1327
|
-
let previousHash = recentOutputHash.get(result.filename);
|
|
1328
|
-
if (!previousHash && exists) {
|
|
1329
|
-
previousHash = hash(await readFile(result.filename));
|
|
1330
|
-
}
|
|
1331
|
-
if (previousHash && currentHash === previousHash) {
|
|
1332
|
-
debugLog(`Skipping file (${result.filename}) writing due to indentical hash...`);
|
|
1333
|
-
return;
|
|
1334
|
-
}
|
|
1335
|
-
if (content.length === 0) {
|
|
1336
|
-
return;
|
|
1337
|
-
}
|
|
1338
|
-
recentOutputHash.set(result.filename, currentHash);
|
|
1339
|
-
const basedir = dirname(result.filename);
|
|
1340
|
-
await lifecycleHooks(result.hooks).beforeOneFileWrite(result.filename);
|
|
1341
|
-
await lifecycleHooks(config.hooks).beforeOneFileWrite(result.filename);
|
|
1342
|
-
await mkdirp(basedir);
|
|
1343
|
-
const absolutePath = isAbsolute(result.filename)
|
|
1344
|
-
? result.filename
|
|
1345
|
-
: join(input.cwd || process.cwd(), result.filename);
|
|
1346
|
-
await writeFile(absolutePath, result.content);
|
|
1347
|
-
await lifecycleHooks(result.hooks).afterOneFileWrite(result.filename);
|
|
1348
|
-
await lifecycleHooks(config.hooks).afterOneFileWrite(result.filename);
|
|
1349
|
-
})), 'Write files');
|
|
1350
|
-
await context.profiler.run(() => lifecycleHooks(config.hooks).afterAllFileWrite(generationResult.map(r => r.filename)), 'Lifecycle: afterAllFileWrite');
|
|
1351
|
-
return generationResult;
|
|
1352
|
-
}
|
|
1353
|
-
// watch mode
|
|
1354
|
-
if (config.watch) {
|
|
1355
|
-
return createWatcher(context, writeOutput);
|
|
1356
|
-
}
|
|
1357
|
-
const outputFiles = await context.profiler.run(() => executeCodegen(context), 'executeCodegen');
|
|
1358
|
-
await context.profiler.run(() => writeOutput(outputFiles), 'writeOutput');
|
|
1359
|
-
await context.profiler.run(() => lifecycleHooks(config.hooks).beforeDone(), 'Lifecycle: beforeDone');
|
|
1360
|
-
if (context.profilerOutput) {
|
|
1361
|
-
await writeFile(join(context.cwd, context.profilerOutput), JSON.stringify(context.profiler.collect()));
|
|
1362
|
-
}
|
|
1363
|
-
return outputFiles;
|
|
1364
|
-
}
|
|
1365
|
-
function shouldOverwrite(config, outputPath) {
|
|
1366
|
-
const globalValue = config.overwrite === undefined ? true : !!config.overwrite;
|
|
1367
|
-
const outputConfig = config.generates[outputPath];
|
|
1368
|
-
if (!outputConfig) {
|
|
1369
|
-
debugLog(`Couldn't find a config of ${outputPath}`);
|
|
1370
|
-
return globalValue;
|
|
1371
|
-
}
|
|
1372
|
-
if (isConfiguredOutput(outputConfig) && typeof outputConfig.overwrite === 'boolean') {
|
|
1373
|
-
return outputConfig.overwrite;
|
|
1374
|
-
}
|
|
1375
|
-
return globalValue;
|
|
1376
|
-
}
|
|
1377
|
-
function isConfiguredOutput(output) {
|
|
1378
|
-
return typeof output.plugins !== 'undefined';
|
|
1379
|
-
}
|
|
1380
|
-
|
|
1381
|
-
// Parses config and writes it to a file
|
|
1382
|
-
async function writeConfig(answers, config) {
|
|
1383
|
-
const YAML = await import('json-to-pretty-yaml').then(m => ('default' in m ? m.default : m));
|
|
1384
|
-
const ext = answers.config.toLocaleLowerCase().endsWith('.json') ? 'json' : 'yml';
|
|
1385
|
-
const content = ext === 'json' ? JSON.stringify(config) : YAML.stringify(config);
|
|
1386
|
-
const fullPath = resolve(process.cwd(), answers.config);
|
|
1387
|
-
const relativePath = relative(process.cwd(), answers.config);
|
|
1388
|
-
writeFileSync(fullPath, content, {
|
|
1389
|
-
encoding: 'utf-8',
|
|
1390
|
-
});
|
|
1391
|
-
return {
|
|
1392
|
-
relativePath,
|
|
1393
|
-
fullPath,
|
|
1394
|
-
};
|
|
1395
|
-
}
|
|
1396
|
-
// Updates package.json (script and plugins as dependencies)
|
|
1397
|
-
async function writePackage(answers, configLocation) {
|
|
1398
|
-
// script
|
|
1399
|
-
const pkgPath = resolve(process.cwd(), 'package.json');
|
|
1400
|
-
const pkgContent = readFileSync(pkgPath, {
|
|
1401
|
-
encoding: 'utf-8',
|
|
1402
|
-
});
|
|
1403
|
-
const pkg = JSON.parse(pkgContent);
|
|
1404
|
-
const { indent } = detectIndent(pkgContent);
|
|
1405
|
-
if (!pkg.scripts) {
|
|
1406
|
-
pkg.scripts = {};
|
|
1407
|
-
}
|
|
1408
|
-
pkg.scripts[answers.script] = `graphql-codegen --config ${configLocation}`;
|
|
1409
|
-
// plugin
|
|
1410
|
-
if (!pkg.devDependencies) {
|
|
1411
|
-
pkg.devDependencies = {};
|
|
1412
|
-
}
|
|
1413
|
-
await Promise.all(answers.plugins.map(async (plugin) => {
|
|
1414
|
-
pkg.devDependencies[plugin.package] = await getLatestVersion(plugin.package);
|
|
1415
|
-
}));
|
|
1416
|
-
if (answers.introspection) {
|
|
1417
|
-
pkg.devDependencies['@graphql-codegen/introspection'] = await getLatestVersion('@graphql-codegen/introspection');
|
|
1418
|
-
}
|
|
1419
|
-
pkg.devDependencies['@graphql-codegen/cli'] = await getLatestVersion('@graphql-codegen/cli');
|
|
1420
|
-
writeFileSync(pkgPath, JSON.stringify(pkg, null, indent));
|
|
1421
|
-
}
|
|
1422
|
-
function bold(str) {
|
|
1423
|
-
return chalk.bold(str);
|
|
1424
|
-
}
|
|
1425
|
-
function grey(str) {
|
|
1426
|
-
return chalk.grey(str);
|
|
1427
|
-
}
|
|
1428
|
-
function italic(str) {
|
|
1429
|
-
return chalk.italic(str);
|
|
1430
|
-
}
|
|
1431
|
-
|
|
1432
|
-
var Tags;
|
|
1433
|
-
(function (Tags) {
|
|
1434
|
-
Tags["browser"] = "Browser";
|
|
1435
|
-
Tags["node"] = "Node";
|
|
1436
|
-
Tags["typescript"] = "TypeScript";
|
|
1437
|
-
Tags["flow"] = "Flow";
|
|
1438
|
-
Tags["angular"] = "Angular";
|
|
1439
|
-
Tags["stencil"] = "Stencil";
|
|
1440
|
-
Tags["react"] = "React";
|
|
1441
|
-
Tags["vue"] = "Vue";
|
|
1442
|
-
})(Tags || (Tags = {}));
|
|
1443
|
-
|
|
1444
|
-
const plugins = [
|
|
1445
|
-
{
|
|
1446
|
-
name: `TypeScript ${italic('(required by other typescript plugins)')}`,
|
|
1447
|
-
package: '@graphql-codegen/typescript',
|
|
1448
|
-
value: 'typescript',
|
|
1449
|
-
pathInRepo: 'typescript/typescript',
|
|
1450
|
-
available: hasTag(Tags.typescript),
|
|
1451
|
-
shouldBeSelected: tags => oneOf(tags, Tags.angular, Tags.stencil) || allOf(tags, Tags.typescript, Tags.react) || noneOf(tags, Tags.flow),
|
|
1452
|
-
defaultExtension: '.ts',
|
|
1453
|
-
},
|
|
1454
|
-
{
|
|
1455
|
-
name: `TypeScript Operations ${italic('(operations and fragments)')}`,
|
|
1456
|
-
package: '@graphql-codegen/typescript-operations',
|
|
1457
|
-
value: 'typescript-operations',
|
|
1458
|
-
pathInRepo: 'typescript/operations',
|
|
1459
|
-
available: tags => allOf(tags, Tags.browser, Tags.typescript),
|
|
1460
|
-
shouldBeSelected: tags => oneOf(tags, Tags.angular, Tags.stencil) || allOf(tags, Tags.typescript, Tags.react),
|
|
1461
|
-
defaultExtension: '.ts',
|
|
1462
|
-
},
|
|
1463
|
-
{
|
|
1464
|
-
name: `TypeScript Resolvers ${italic('(strongly typed resolve functions)')}`,
|
|
1465
|
-
package: '@graphql-codegen/typescript-resolvers',
|
|
1466
|
-
value: 'typescript-resolvers',
|
|
1467
|
-
pathInRepo: 'typescript/resolvers',
|
|
1468
|
-
available: tags => allOf(tags, Tags.node, Tags.typescript),
|
|
1469
|
-
shouldBeSelected: tags => noneOf(tags, Tags.flow),
|
|
1470
|
-
defaultExtension: '.ts',
|
|
1471
|
-
},
|
|
1472
|
-
{
|
|
1473
|
-
name: `Flow ${italic('(required by other flow plugins)')}`,
|
|
1474
|
-
package: '@graphql-codegen/flow',
|
|
1475
|
-
value: 'flow',
|
|
1476
|
-
pathInRepo: 'flow/flow',
|
|
1477
|
-
available: hasTag(Tags.flow),
|
|
1478
|
-
shouldBeSelected: tags => noneOf(tags, Tags.typescript),
|
|
1479
|
-
defaultExtension: '.js',
|
|
1480
|
-
},
|
|
1481
|
-
{
|
|
1482
|
-
name: `Flow Operations ${italic('(operations and fragments)')}`,
|
|
1483
|
-
package: '@graphql-codegen/flow-operations',
|
|
1484
|
-
value: 'flow-operations',
|
|
1485
|
-
pathInRepo: 'flow/operations',
|
|
1486
|
-
available: tags => allOf(tags, Tags.browser, Tags.flow),
|
|
1487
|
-
shouldBeSelected: tags => noneOf(tags, Tags.typescript),
|
|
1488
|
-
defaultExtension: '.js',
|
|
1489
|
-
},
|
|
1490
|
-
{
|
|
1491
|
-
name: `Flow Resolvers ${italic('(strongly typed resolve functions)')}`,
|
|
1492
|
-
package: '@graphql-codegen/flow-resolvers',
|
|
1493
|
-
value: 'flow-resolvers',
|
|
1494
|
-
pathInRepo: 'flow/resolvers',
|
|
1495
|
-
available: tags => allOf(tags, Tags.node, Tags.flow),
|
|
1496
|
-
shouldBeSelected: tags => noneOf(tags, Tags.typescript),
|
|
1497
|
-
defaultExtension: '.js',
|
|
1498
|
-
},
|
|
1499
|
-
{
|
|
1500
|
-
name: `TypeScript Apollo Angular ${italic('(typed GQL services)')}`,
|
|
1501
|
-
package: '@graphql-codegen/typescript-apollo-angular',
|
|
1502
|
-
value: 'typescript-apollo-angular',
|
|
1503
|
-
pathInRepo: 'typescript/apollo-angular',
|
|
1504
|
-
available: hasTag(Tags.angular),
|
|
1505
|
-
shouldBeSelected: () => true,
|
|
1506
|
-
defaultExtension: '.js',
|
|
1507
|
-
},
|
|
1508
|
-
{
|
|
1509
|
-
name: `TypeScript Vue Apollo Composition API ${italic('(typed functions)')}`,
|
|
1510
|
-
package: '@graphql-codegen/typescript-vue-apollo',
|
|
1511
|
-
value: 'typescript-vue-apollo',
|
|
1512
|
-
pathInRepo: 'typescript/vue-apollo',
|
|
1513
|
-
available: tags => allOf(tags, Tags.vue, Tags.typescript),
|
|
1514
|
-
shouldBeSelected: () => true,
|
|
1515
|
-
defaultExtension: '.ts',
|
|
1516
|
-
},
|
|
1517
|
-
{
|
|
1518
|
-
name: `TypeScript Vue Apollo Smart Operations ${italic('(typed functions)')}`,
|
|
1519
|
-
package: '@graphql-codegen/typescript-vue-apollo-smart-ops',
|
|
1520
|
-
value: 'typescript-vue-apollo-smart-ops',
|
|
1521
|
-
pathInRepo: 'typescript/vue-apollo-smart-ops',
|
|
1522
|
-
available: tags => allOf(tags, Tags.vue, Tags.typescript),
|
|
1523
|
-
shouldBeSelected: () => true,
|
|
1524
|
-
defaultExtension: '.ts',
|
|
1525
|
-
},
|
|
1526
|
-
{
|
|
1527
|
-
name: `TypeScript React Apollo ${italic('(typed components and HOCs)')}`,
|
|
1528
|
-
package: '@graphql-codegen/typescript-react-apollo',
|
|
1529
|
-
value: 'typescript-react-apollo',
|
|
1530
|
-
pathInRepo: 'typescript/react-apollo',
|
|
1531
|
-
available: tags => allOf(tags, Tags.react, Tags.typescript),
|
|
1532
|
-
shouldBeSelected: () => true,
|
|
1533
|
-
defaultExtension: '.tsx',
|
|
1534
|
-
},
|
|
1535
|
-
{
|
|
1536
|
-
name: `TypeScript Stencil Apollo ${italic('(typed components)')}`,
|
|
1537
|
-
package: '@graphql-codegen/typescript-stencil-apollo',
|
|
1538
|
-
value: 'typescript-stencil-apollo',
|
|
1539
|
-
pathInRepo: 'typescript/stencil-apollo',
|
|
1540
|
-
available: hasTag(Tags.stencil),
|
|
1541
|
-
shouldBeSelected: () => true,
|
|
1542
|
-
defaultExtension: '.tsx',
|
|
1543
|
-
},
|
|
1544
|
-
{
|
|
1545
|
-
name: `TypeScript MongoDB ${italic('(typed MongoDB objects)')}`,
|
|
1546
|
-
package: '@graphql-codegen/typescript-mongodb',
|
|
1547
|
-
value: 'typescript-mongodb',
|
|
1548
|
-
pathInRepo: 'typescript/mongodb',
|
|
1549
|
-
available: tags => allOf(tags, Tags.node, Tags.typescript),
|
|
1550
|
-
shouldBeSelected: () => false,
|
|
1551
|
-
defaultExtension: '.ts',
|
|
1552
|
-
},
|
|
1553
|
-
{
|
|
1554
|
-
name: `TypeScript GraphQL files modules ${italic('(declarations for .graphql files)')}`,
|
|
1555
|
-
package: '@graphql-codegen/typescript-graphql-files-modules',
|
|
1556
|
-
value: 'typescript-graphql-files-modules',
|
|
1557
|
-
pathInRepo: 'typescript/graphql-files-modules',
|
|
1558
|
-
available: tags => allOf(tags, Tags.browser, Tags.typescript),
|
|
1559
|
-
shouldBeSelected: () => false,
|
|
1560
|
-
defaultExtension: '.ts',
|
|
1561
|
-
},
|
|
1562
|
-
{
|
|
1563
|
-
name: `TypeScript GraphQL document nodes ${italic('(embedded GraphQL document)')}`,
|
|
1564
|
-
package: '@graphql-codegen/typescript-document-nodes',
|
|
1565
|
-
value: 'typescript-document-nodes',
|
|
1566
|
-
pathInRepo: 'typescript/document-nodes',
|
|
1567
|
-
available: tags => allOf(tags, Tags.typescript),
|
|
1568
|
-
shouldBeSelected: () => false,
|
|
1569
|
-
defaultExtension: '.ts',
|
|
1570
|
-
},
|
|
1571
|
-
{
|
|
1572
|
-
name: `Introspection Fragment Matcher ${italic('(for Apollo Client)')}`,
|
|
1573
|
-
package: '@graphql-codegen/fragment-matcher',
|
|
1574
|
-
value: 'fragment-matcher',
|
|
1575
|
-
pathInRepo: 'other/fragment-matcher',
|
|
1576
|
-
available: hasTag(Tags.browser),
|
|
1577
|
-
shouldBeSelected: () => false,
|
|
1578
|
-
defaultExtension: '.ts',
|
|
1579
|
-
},
|
|
1580
|
-
{
|
|
1581
|
-
name: `Urql Introspection ${italic('(for Urql Client)')}`,
|
|
1582
|
-
package: '@graphql-codegen/urql-introspection',
|
|
1583
|
-
value: 'urql-introspection',
|
|
1584
|
-
pathInRepo: 'other/urql-introspection',
|
|
1585
|
-
available: hasTag(Tags.browser),
|
|
1586
|
-
shouldBeSelected: () => false,
|
|
1587
|
-
defaultExtension: '.ts',
|
|
1588
|
-
},
|
|
1589
|
-
];
|
|
1590
|
-
function hasTag(tag) {
|
|
1591
|
-
return (tags) => tags.includes(tag);
|
|
1592
|
-
}
|
|
1593
|
-
function oneOf(list, ...items) {
|
|
1594
|
-
return list.some(i => items.includes(i));
|
|
1595
|
-
}
|
|
1596
|
-
function noneOf(list, ...items) {
|
|
1597
|
-
return !list.some(i => items.includes(i));
|
|
1598
|
-
}
|
|
1599
|
-
function allOf(list, ...items) {
|
|
1600
|
-
return items.every(i => list.includes(i));
|
|
1601
|
-
}
|
|
1602
|
-
|
|
1603
|
-
function getQuestions(possibleTargets) {
|
|
1604
|
-
return [
|
|
1605
|
-
{
|
|
1606
|
-
type: 'checkbox',
|
|
1607
|
-
name: 'targets',
|
|
1608
|
-
message: `What type of application are you building?`,
|
|
1609
|
-
choices: getApplicationTypeChoices(possibleTargets),
|
|
1610
|
-
validate: ((targets) => targets.length > 0),
|
|
1611
|
-
},
|
|
1612
|
-
{
|
|
1613
|
-
type: 'input',
|
|
1614
|
-
name: 'schema',
|
|
1615
|
-
message: 'Where is your schema?:',
|
|
1616
|
-
suffix: grey(' (path or url)'),
|
|
1617
|
-
default: 'http://localhost:4000',
|
|
1618
|
-
validate: (str) => str.length > 0,
|
|
1619
|
-
},
|
|
1620
|
-
{
|
|
1621
|
-
type: 'input',
|
|
1622
|
-
name: 'documents',
|
|
1623
|
-
message: 'Where are your operations and fragments?:',
|
|
1624
|
-
when: answers => {
|
|
1625
|
-
// flatten targets
|
|
1626
|
-
// I can't find an API in Inquirer that would do that
|
|
1627
|
-
answers.targets = normalizeTargets(answers.targets);
|
|
1628
|
-
return answers.targets.includes(Tags.browser);
|
|
1629
|
-
},
|
|
1630
|
-
default: 'src/**/*.graphql',
|
|
1631
|
-
validate: (str) => str.length > 0,
|
|
1632
|
-
},
|
|
1633
|
-
{
|
|
1634
|
-
type: 'checkbox',
|
|
1635
|
-
name: 'plugins',
|
|
1636
|
-
message: 'Pick plugins:',
|
|
1637
|
-
choices: getPluginChoices,
|
|
1638
|
-
validate: ((plugins) => plugins.length > 0),
|
|
1639
|
-
},
|
|
1640
|
-
{
|
|
1641
|
-
type: 'input',
|
|
1642
|
-
name: 'output',
|
|
1643
|
-
message: 'Where to write the output:',
|
|
1644
|
-
default: getOutputDefaultValue,
|
|
1645
|
-
validate: (str) => str.length > 0,
|
|
1646
|
-
},
|
|
1647
|
-
{
|
|
1648
|
-
type: 'confirm',
|
|
1649
|
-
name: 'introspection',
|
|
1650
|
-
message: 'Do you want to generate an introspection file?',
|
|
1651
|
-
},
|
|
1652
|
-
{
|
|
1653
|
-
type: 'input',
|
|
1654
|
-
name: 'config',
|
|
1655
|
-
message: 'How to name the config file?',
|
|
1656
|
-
default: 'codegen.yml',
|
|
1657
|
-
validate: (str) => {
|
|
1658
|
-
const isNotEmpty = str.length > 0;
|
|
1659
|
-
const hasCorrectExtension = ['json', 'yml', 'yaml'].some(ext => str.toLocaleLowerCase().endsWith(`.${ext}`));
|
|
1660
|
-
return isNotEmpty && hasCorrectExtension;
|
|
1661
|
-
},
|
|
1662
|
-
},
|
|
1663
|
-
{
|
|
1664
|
-
type: 'input',
|
|
1665
|
-
name: 'script',
|
|
1666
|
-
message: 'What script in package.json should run the codegen?',
|
|
1667
|
-
validate: (str) => str.length > 0,
|
|
1668
|
-
},
|
|
1669
|
-
];
|
|
1670
|
-
}
|
|
1671
|
-
function getApplicationTypeChoices(possibleTargets) {
|
|
1672
|
-
function withFlowOrTypescript(tags) {
|
|
1673
|
-
if (possibleTargets.TypeScript) {
|
|
1674
|
-
tags.push(Tags.typescript);
|
|
1675
|
-
}
|
|
1676
|
-
else if (possibleTargets.Flow) {
|
|
1677
|
-
tags.push(Tags.flow);
|
|
1678
|
-
}
|
|
1679
|
-
else {
|
|
1680
|
-
tags.push(Tags.flow, Tags.typescript);
|
|
1681
|
-
}
|
|
1682
|
-
return tags;
|
|
1683
|
-
}
|
|
1684
|
-
return [
|
|
1685
|
-
{
|
|
1686
|
-
name: 'Backend - API or server',
|
|
1687
|
-
key: 'backend',
|
|
1688
|
-
value: withFlowOrTypescript([Tags.node]),
|
|
1689
|
-
checked: possibleTargets.Node,
|
|
1690
|
-
},
|
|
1691
|
-
{
|
|
1692
|
-
name: 'Application built with Angular',
|
|
1693
|
-
key: 'angular',
|
|
1694
|
-
value: [Tags.angular, Tags.browser, Tags.typescript],
|
|
1695
|
-
checked: possibleTargets.Angular,
|
|
1696
|
-
},
|
|
1697
|
-
{
|
|
1698
|
-
name: 'Application built with React',
|
|
1699
|
-
key: 'react',
|
|
1700
|
-
value: withFlowOrTypescript([Tags.react, Tags.browser]),
|
|
1701
|
-
checked: possibleTargets.React,
|
|
1702
|
-
},
|
|
1703
|
-
{
|
|
1704
|
-
name: 'Application built with Stencil',
|
|
1705
|
-
key: 'stencil',
|
|
1706
|
-
value: [Tags.stencil, Tags.browser, Tags.typescript],
|
|
1707
|
-
checked: possibleTargets.Stencil,
|
|
1708
|
-
},
|
|
1709
|
-
{
|
|
1710
|
-
name: 'Application built with other framework or vanilla JS',
|
|
1711
|
-
key: 'client',
|
|
1712
|
-
value: [Tags.browser, Tags.typescript, Tags.flow],
|
|
1713
|
-
checked: possibleTargets.Browser && !possibleTargets.Angular && !possibleTargets.React && !possibleTargets.Stencil,
|
|
1714
|
-
},
|
|
1715
|
-
];
|
|
1716
|
-
}
|
|
1717
|
-
function getPluginChoices(answers) {
|
|
1718
|
-
return plugins
|
|
1719
|
-
.filter(p => p.available(answers.targets))
|
|
1720
|
-
.map(p => {
|
|
1721
|
-
return {
|
|
1722
|
-
name: p.name,
|
|
1723
|
-
value: p,
|
|
1724
|
-
checked: p.shouldBeSelected(answers.targets),
|
|
1725
|
-
};
|
|
1726
|
-
});
|
|
1727
|
-
}
|
|
1728
|
-
function normalizeTargets(targets) {
|
|
1729
|
-
return [].concat(...targets);
|
|
1730
|
-
}
|
|
1731
|
-
function getOutputDefaultValue(answers) {
|
|
1732
|
-
if (answers.plugins.some(plugin => plugin.defaultExtension === '.tsx')) {
|
|
1733
|
-
return 'src/generated/graphql.tsx';
|
|
1734
|
-
}
|
|
1735
|
-
if (answers.plugins.some(plugin => plugin.defaultExtension === '.ts')) {
|
|
1736
|
-
return 'src/generated/graphql.ts';
|
|
1737
|
-
}
|
|
1738
|
-
return 'src/generated/graphql.js';
|
|
1739
|
-
}
|
|
1740
|
-
|
|
1741
|
-
async function guessTargets() {
|
|
1742
|
-
const pkg = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), {
|
|
1743
|
-
encoding: 'utf-8',
|
|
1744
|
-
}));
|
|
1745
|
-
const dependencies = Object.keys({
|
|
1746
|
-
...pkg.dependencies,
|
|
1747
|
-
...pkg.devDependencies,
|
|
1748
|
-
});
|
|
1749
|
-
return {
|
|
1750
|
-
[Tags.angular]: isAngular(dependencies),
|
|
1751
|
-
[Tags.react]: isReact(dependencies),
|
|
1752
|
-
[Tags.stencil]: isStencil(dependencies),
|
|
1753
|
-
[Tags.vue]: isVue(dependencies),
|
|
1754
|
-
[Tags.browser]: false,
|
|
1755
|
-
[Tags.node]: false,
|
|
1756
|
-
[Tags.typescript]: isTypescript(dependencies),
|
|
1757
|
-
[Tags.flow]: isFlow(dependencies),
|
|
1758
|
-
};
|
|
1759
|
-
}
|
|
1760
|
-
function isAngular(dependencies) {
|
|
1761
|
-
return dependencies.includes('@angular/core');
|
|
1762
|
-
}
|
|
1763
|
-
function isReact(dependencies) {
|
|
1764
|
-
return dependencies.includes('react');
|
|
1765
|
-
}
|
|
1766
|
-
function isStencil(dependencies) {
|
|
1767
|
-
return dependencies.includes('@stencil/core');
|
|
1768
|
-
}
|
|
1769
|
-
function isVue(dependencies) {
|
|
1770
|
-
return dependencies.includes('vue') || dependencies.includes('nuxt');
|
|
1771
|
-
}
|
|
1772
|
-
function isTypescript(dependencies) {
|
|
1773
|
-
return dependencies.includes('typescript');
|
|
1774
|
-
}
|
|
1775
|
-
function isFlow(dependencies) {
|
|
1776
|
-
return dependencies.includes('flow');
|
|
1777
|
-
}
|
|
1778
|
-
|
|
1779
|
-
function log$1(...msgs) {
|
|
1780
|
-
// eslint-disable-next-line no-console
|
|
1781
|
-
console.log(...msgs);
|
|
1782
|
-
}
|
|
1783
|
-
async function init() {
|
|
1784
|
-
log$1(`
|
|
1785
|
-
Welcome to ${bold('GraphQL Code Generator')}!
|
|
1786
|
-
Answer few questions and we will setup everything for you.
|
|
1787
|
-
`);
|
|
1788
|
-
const possibleTargets = await guessTargets();
|
|
1789
|
-
const answers = await inquirer.prompt(getQuestions(possibleTargets));
|
|
1790
|
-
// define config
|
|
1791
|
-
const config = {
|
|
1792
|
-
overwrite: true,
|
|
1793
|
-
schema: answers.schema,
|
|
1794
|
-
documents: answers.targets.includes(Tags.browser) ? answers.documents : null,
|
|
1795
|
-
generates: {
|
|
1796
|
-
[answers.output]: {
|
|
1797
|
-
plugins: answers.plugins.map(p => p.value),
|
|
1798
|
-
},
|
|
1799
|
-
},
|
|
1800
|
-
};
|
|
1801
|
-
// introspection
|
|
1802
|
-
if (answers.introspection) {
|
|
1803
|
-
addIntrospection(config);
|
|
1804
|
-
}
|
|
1805
|
-
// config file
|
|
1806
|
-
const { relativePath } = await writeConfig(answers, config);
|
|
1807
|
-
log$1(`Fetching latest versions of selected plugins...`);
|
|
1808
|
-
// write package.json
|
|
1809
|
-
await writePackage(answers, relativePath);
|
|
1810
|
-
// Emit status to the terminal
|
|
1811
|
-
log$1(`
|
|
1812
|
-
Config file generated at ${bold(relativePath)}
|
|
1813
|
-
|
|
1814
|
-
${bold('$ npm install')}
|
|
1815
|
-
|
|
1816
|
-
To install the plugins.
|
|
1817
|
-
|
|
1818
|
-
${bold(`$ npm run ${answers.script}`)}
|
|
1819
|
-
|
|
1820
|
-
To run GraphQL Code Generator.
|
|
1821
|
-
`);
|
|
1822
|
-
}
|
|
1823
|
-
// adds an introspection to `generates`
|
|
1824
|
-
function addIntrospection(config) {
|
|
1825
|
-
config.generates['./graphql.schema.json'] = {
|
|
1826
|
-
plugins: ['introspection'],
|
|
1827
|
-
};
|
|
1828
|
-
}
|
|
1829
|
-
|
|
1830
|
-
async function runCli(cmd) {
|
|
1831
|
-
await ensureGraphQlPackage();
|
|
1832
|
-
if (cmd === 'init') {
|
|
1833
|
-
return init();
|
|
1834
|
-
}
|
|
1835
|
-
const context = await createContext();
|
|
1836
|
-
try {
|
|
1837
|
-
return await generate(context);
|
|
1838
|
-
}
|
|
1839
|
-
catch (error) {
|
|
1840
|
-
await lifecycleHooks(context.getConfig().hooks).onError(error.toString());
|
|
1841
|
-
throw error;
|
|
1842
|
-
}
|
|
1843
|
-
}
|
|
1844
|
-
async function ensureGraphQlPackage() {
|
|
1845
|
-
try {
|
|
1846
|
-
await import('graphql');
|
|
1847
|
-
}
|
|
1848
|
-
catch (e) {
|
|
1849
|
-
throw new DetailedError(`Unable to load "graphql" package. Please make sure to install "graphql" as a dependency!`, `
|
|
1850
|
-
To install "graphql", run:
|
|
1851
|
-
yarn add graphql
|
|
1852
|
-
Or, with NPM:
|
|
1853
|
-
npm install --save graphql
|
|
1854
|
-
`);
|
|
1855
|
-
}
|
|
1856
|
-
}
|
|
1857
|
-
|
|
1858
|
-
export { CodegenContext, CodegenExtension, buildOptions, cliError, createContext, ensureContext, ensureGraphQlPackage, executeCodegen, findAndLoadGraphQLConfig, generate, generateSearchPlaces, init, isListrError, loadCodegenConfig, loadContext, parseArgv, runCli, updateContextWithCliFlags };
|