@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.
Files changed (75) hide show
  1. package/cjs/bin.js +13 -0
  2. package/cjs/cli.js +60 -0
  3. package/cjs/codegen.js +319 -0
  4. package/cjs/config.js +303 -0
  5. package/cjs/generate-and-save.js +110 -0
  6. package/cjs/graphql-config.js +69 -0
  7. package/cjs/hooks.js +87 -0
  8. package/cjs/index.js +13 -0
  9. package/cjs/init/helpers.js +64 -0
  10. package/cjs/init/index.js +60 -0
  11. package/cjs/init/plugins.js +163 -0
  12. package/cjs/init/questions.js +147 -0
  13. package/cjs/init/targets.js +44 -0
  14. package/cjs/init/types.js +14 -0
  15. package/cjs/load.js +93 -0
  16. package/cjs/package.json +1 -0
  17. package/cjs/plugins.js +45 -0
  18. package/cjs/presets.js +50 -0
  19. package/cjs/utils/cli-error.js +25 -0
  20. package/cjs/utils/debugging.js +27 -0
  21. package/cjs/utils/file-system.js +26 -0
  22. package/cjs/utils/logger.js +25 -0
  23. package/cjs/utils/watcher.js +140 -0
  24. package/esm/bin.js +11 -0
  25. package/esm/cli.js +32 -0
  26. package/esm/codegen.js +314 -0
  27. package/esm/config.js +290 -0
  28. package/esm/generate-and-save.js +105 -0
  29. package/esm/graphql-config.js +64 -0
  30. package/esm/hooks.js +83 -0
  31. package/esm/index.js +7 -0
  32. package/esm/init/helpers.js +55 -0
  33. package/esm/init/index.js +55 -0
  34. package/esm/init/plugins.js +160 -0
  35. package/esm/init/questions.js +140 -0
  36. package/esm/init/targets.js +40 -0
  37. package/esm/init/types.js +11 -0
  38. package/esm/load.js +88 -0
  39. package/esm/plugins.js +41 -0
  40. package/esm/presets.js +46 -0
  41. package/esm/utils/cli-error.js +20 -0
  42. package/esm/utils/debugging.js +21 -0
  43. package/esm/utils/file-system.js +19 -0
  44. package/esm/utils/logger.js +18 -0
  45. package/esm/utils/watcher.js +135 -0
  46. package/package.json +33 -29
  47. package/typings/bin.d.ts +2 -0
  48. package/{cli.d.ts → typings/cli.d.ts} +0 -0
  49. package/{codegen.d.ts → typings/codegen.d.ts} +1 -1
  50. package/{config.d.ts → typings/config.d.ts} +0 -0
  51. package/{generate-and-save.d.ts → typings/generate-and-save.d.ts} +1 -1
  52. package/{graphql-config.d.ts → typings/graphql-config.d.ts} +0 -0
  53. package/{hooks.d.ts → typings/hooks.d.ts} +0 -0
  54. package/typings/index.d.ts +7 -0
  55. package/{init → typings/init}/helpers.d.ts +1 -1
  56. package/{init → typings/init}/index.d.ts +0 -0
  57. package/{init → typings/init}/plugins.d.ts +1 -1
  58. package/{init → typings/init}/questions.d.ts +1 -1
  59. package/{init → typings/init}/targets.d.ts +1 -1
  60. package/{init → typings/init}/types.d.ts +0 -0
  61. package/{load.d.ts → typings/load.d.ts} +0 -0
  62. package/{plugins.d.ts → typings/plugins.d.ts} +0 -0
  63. package/{presets.d.ts → typings/presets.d.ts} +0 -0
  64. package/{utils → typings/utils}/cli-error.d.ts +0 -0
  65. package/{utils → typings/utils}/debugging.d.ts +0 -0
  66. package/{utils → typings/utils}/file-system.d.ts +0 -0
  67. package/{utils → typings/utils}/logger.d.ts +0 -0
  68. package/{utils → typings/utils}/watcher.d.ts +1 -1
  69. package/bin.d.ts +0 -1
  70. package/bin.js +0 -1891
  71. package/index.d.ts +0 -7
  72. package/index.js +0 -1902
  73. package/index.mjs +0 -1858
  74. package/utils/indentString.d.ts +0 -26
  75. package/utils/listr-renderer.d.ts +0 -18
package/cjs/bin.js ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const cli_js_1 = require("./cli.js");
5
+ const cli_error_js_1 = require("./utils/cli-error.js");
6
+ const [, , cmd] = process.argv;
7
+ (0, cli_js_1.runCli)(cmd)
8
+ .then(() => {
9
+ process.exit(0);
10
+ })
11
+ .catch(error => {
12
+ (0, cli_error_js_1.cliError)(error);
13
+ });
package/cjs/cli.js ADDED
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.ensureGraphQlPackage = exports.runCli = void 0;
27
+ const generate_and_save_js_1 = require("./generate-and-save.js");
28
+ const index_js_1 = require("./init/index.js");
29
+ const config_js_1 = require("./config.js");
30
+ const hooks_js_1 = require("./hooks.js");
31
+ const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
32
+ async function runCli(cmd) {
33
+ await ensureGraphQlPackage();
34
+ if (cmd === 'init') {
35
+ return (0, index_js_1.init)();
36
+ }
37
+ const context = await (0, config_js_1.createContext)();
38
+ try {
39
+ return await (0, generate_and_save_js_1.generate)(context);
40
+ }
41
+ catch (error) {
42
+ await (0, hooks_js_1.lifecycleHooks)(context.getConfig().hooks).onError(error.toString());
43
+ throw error;
44
+ }
45
+ }
46
+ exports.runCli = runCli;
47
+ async function ensureGraphQlPackage() {
48
+ try {
49
+ await Promise.resolve().then(() => __importStar(require('graphql')));
50
+ }
51
+ catch (e) {
52
+ throw new plugin_helpers_1.DetailedError(`Unable to load "graphql" package. Please make sure to install "graphql" as a dependency!`, `
53
+ To install "graphql", run:
54
+ yarn add graphql
55
+ Or, with NPM:
56
+ npm install --save graphql
57
+ `);
58
+ }
59
+ }
60
+ exports.ensureGraphQlPackage = ensureGraphQlPackage;
package/cjs/codegen.js ADDED
@@ -0,0 +1,319 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeCodegen = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
6
+ const core_1 = require("@graphql-codegen/core");
7
+ const utils_1 = require("@graphql-tools/utils");
8
+ const graphql_1 = require("graphql");
9
+ const plugins_js_1 = require("./plugins.js");
10
+ const presets_js_1 = require("./presets.js");
11
+ const debugging_js_1 = require("./utils/debugging.js");
12
+ const config_js_1 = require("./config.js");
13
+ const fs_1 = tslib_1.__importDefault(require("fs"));
14
+ const path_1 = tslib_1.__importDefault(require("path"));
15
+ const os_1 = require("os");
16
+ const module_1 = require("module");
17
+ const listr2_1 = require("listr2");
18
+ /**
19
+ * Poor mans ESM detection.
20
+ * Looking at this and you have a better method?
21
+ * Send a PR.
22
+ */
23
+ const isESMModule = (typeof __dirname === 'string') === false;
24
+ const makeDefaultLoader = (from) => {
25
+ if (fs_1.default.statSync(from).isDirectory()) {
26
+ from = path_1.default.join(from, '__fake.js');
27
+ }
28
+ const relativeRequire = (0, module_1.createRequire)(from);
29
+ return async (mod) => {
30
+ return Promise.resolve().then(() => tslib_1.__importStar(require(isESMModule
31
+ ? /**
32
+ * For ESM we currently have no "resolve path" solution
33
+ * as import.meta is unavailable in a CommonJS context
34
+ * and furthermore unavailable in stable Node.js.
35
+ **/
36
+ mod
37
+ : relativeRequire.resolve(mod))));
38
+ };
39
+ };
40
+ function createCache() {
41
+ const cache = new Map();
42
+ return function ensure(namespace, key, factory) {
43
+ const cacheKey = `${namespace}:${key}`;
44
+ const cachedValue = cache.get(cacheKey);
45
+ if (cachedValue) {
46
+ return cachedValue;
47
+ }
48
+ const value = factory();
49
+ cache.set(cacheKey, value);
50
+ return value;
51
+ };
52
+ }
53
+ async function executeCodegen(input) {
54
+ const context = (0, config_js_1.ensureContext)(input);
55
+ const config = context.getConfig();
56
+ const pluginContext = context.getPluginContext();
57
+ const result = [];
58
+ let rootConfig = {};
59
+ let rootSchemas;
60
+ let rootDocuments;
61
+ const generates = {};
62
+ const cache = createCache();
63
+ function wrapTask(task, source, taskName, ctx) {
64
+ return () => {
65
+ return context.profiler.run(async () => {
66
+ try {
67
+ await Promise.resolve().then(() => task());
68
+ }
69
+ catch (error) {
70
+ if (source && !(error instanceof graphql_1.GraphQLError)) {
71
+ error.source = source;
72
+ }
73
+ ctx.errors.push(error);
74
+ throw error;
75
+ }
76
+ }, taskName);
77
+ };
78
+ }
79
+ async function normalize() {
80
+ /* Load Require extensions */
81
+ const requireExtensions = (0, plugin_helpers_1.normalizeInstanceOrArray)(config.require);
82
+ const loader = makeDefaultLoader(context.cwd);
83
+ for (const mod of requireExtensions) {
84
+ await loader(mod);
85
+ }
86
+ /* Root plugin config */
87
+ rootConfig = config.config || {};
88
+ /* Normalize root "schema" field */
89
+ rootSchemas = (0, plugin_helpers_1.normalizeInstanceOrArray)(config.schema);
90
+ /* Normalize root "documents" field */
91
+ rootDocuments = (0, plugin_helpers_1.normalizeInstanceOrArray)(config.documents);
92
+ /* Normalize "generators" field */
93
+ const generateKeys = Object.keys(config.generates || {});
94
+ if (generateKeys.length === 0) {
95
+ throw new plugin_helpers_1.DetailedError('Invalid Codegen Configuration!', `
96
+ Please make sure that your codegen config file contains the "generates" field, with a specification for the plugins you need.
97
+
98
+ It should looks like that:
99
+
100
+ schema:
101
+ - my-schema.graphql
102
+ generates:
103
+ my-file.ts:
104
+ - plugin1
105
+ - plugin2
106
+ - plugin3
107
+ `);
108
+ }
109
+ for (const filename of generateKeys) {
110
+ const output = (generates[filename] = (0, plugin_helpers_1.normalizeOutputParam)(config.generates[filename]));
111
+ if (!output.preset && (!output.plugins || output.plugins.length === 0)) {
112
+ throw new plugin_helpers_1.DetailedError('Invalid Codegen Configuration!', `
113
+ Please make sure that your codegen config file has defined plugins list for output "${filename}".
114
+
115
+ It should looks like that:
116
+
117
+ schema:
118
+ - my-schema.graphql
119
+ generates:
120
+ my-file.ts:
121
+ - plugin1
122
+ - plugin2
123
+ - plugin3
124
+ `);
125
+ }
126
+ }
127
+ if (rootSchemas.length === 0 &&
128
+ Object.keys(generates).some(filename => !generates[filename].schema || generates[filename].schema.length === 0)) {
129
+ throw new plugin_helpers_1.DetailedError('Invalid Codegen Configuration!', `
130
+ Please make sure that your codegen config file contains either the "schema" field
131
+ or every generated file has its own "schema" field.
132
+
133
+ It should looks like that:
134
+ schema:
135
+ - my-schema.graphql
136
+
137
+ or:
138
+ generates:
139
+ path/to/output:
140
+ schema: my-schema.graphql
141
+ `);
142
+ }
143
+ }
144
+ const isTest = process.env.NODE_ENV === 'test';
145
+ const tasks = new listr2_1.Listr([
146
+ {
147
+ title: 'Parse Configuration',
148
+ task: () => normalize(),
149
+ },
150
+ {
151
+ title: 'Generate outputs',
152
+ task: (ctx, task) => {
153
+ const generateTasks = Object.keys(generates).map(filename => {
154
+ const outputConfig = generates[filename];
155
+ const hasPreset = !!outputConfig.preset;
156
+ const title = hasPreset
157
+ ? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
158
+ : `Generate ${filename}`;
159
+ return {
160
+ title,
161
+ task: (_, subTask) => {
162
+ let outputSchemaAst;
163
+ let outputSchema;
164
+ const outputFileTemplateConfig = outputConfig.config || {};
165
+ let outputDocuments = [];
166
+ const outputSpecificSchemas = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.schema);
167
+ const outputSpecificDocuments = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.documents);
168
+ return subTask.newListr([
169
+ {
170
+ title: 'Load GraphQL schemas',
171
+ task: wrapTask(async () => {
172
+ (0, debugging_js_1.debugLog)(`[CLI] Loading Schemas`);
173
+ const schemaPointerMap = {};
174
+ const allSchemaDenormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
175
+ for (const denormalizedPtr of allSchemaDenormalizedPointers) {
176
+ if (typeof denormalizedPtr === 'string') {
177
+ schemaPointerMap[denormalizedPtr] = {};
178
+ }
179
+ else if (typeof denormalizedPtr === 'object') {
180
+ Object.assign(schemaPointerMap, denormalizedPtr);
181
+ }
182
+ }
183
+ const hash = JSON.stringify(schemaPointerMap);
184
+ const result = await cache('schema', hash, async () => {
185
+ const outputSchemaAst = await context.loadSchema(schemaPointerMap);
186
+ const outputSchema = (0, plugin_helpers_1.getCachedDocumentNodeFromSchema)(outputSchemaAst);
187
+ return {
188
+ outputSchemaAst,
189
+ outputSchema,
190
+ };
191
+ });
192
+ outputSchemaAst = result.outputSchemaAst;
193
+ outputSchema = result.outputSchema;
194
+ }, filename, `Load GraphQL schemas: ${filename}`, ctx),
195
+ },
196
+ {
197
+ title: 'Load GraphQL documents',
198
+ task: wrapTask(async () => {
199
+ (0, debugging_js_1.debugLog)(`[CLI] Loading Documents`);
200
+ const documentPointerMap = {};
201
+ const allDocumentsDenormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
202
+ for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
203
+ if (typeof denormalizedPtr === 'string') {
204
+ documentPointerMap[denormalizedPtr] = {};
205
+ }
206
+ else if (typeof denormalizedPtr === 'object') {
207
+ Object.assign(documentPointerMap, denormalizedPtr);
208
+ }
209
+ }
210
+ const hash = JSON.stringify(documentPointerMap);
211
+ const result = await cache('documents', hash, async () => {
212
+ const documents = await context.loadDocuments(documentPointerMap);
213
+ return {
214
+ documents,
215
+ };
216
+ });
217
+ outputDocuments = result.documents;
218
+ }, filename, `Load GraphQL documents: ${filename}`, ctx),
219
+ },
220
+ {
221
+ title: 'Generate',
222
+ task: wrapTask(async () => {
223
+ (0, debugging_js_1.debugLog)(`[CLI] Generating output`);
224
+ const normalizedPluginsArray = (0, plugin_helpers_1.normalizeConfig)(outputConfig.plugins);
225
+ const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
226
+ const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => (0, plugins_js_1.getPluginByName)(Object.keys(plugin)[0], pluginLoader)));
227
+ const preset = hasPreset
228
+ ? typeof outputConfig.preset === 'string'
229
+ ? await (0, presets_js_1.getPresetByName)(outputConfig.preset, makeDefaultLoader(context.cwd))
230
+ : outputConfig.preset
231
+ : null;
232
+ const pluginMap = Object.fromEntries(pluginPackages.map((pkg, i) => {
233
+ const plugin = normalizedPluginsArray[i];
234
+ const name = Object.keys(plugin)[0];
235
+ return [name, pkg];
236
+ }));
237
+ const mergedConfig = {
238
+ ...rootConfig,
239
+ ...(typeof outputFileTemplateConfig === 'string'
240
+ ? { value: outputFileTemplateConfig }
241
+ : outputFileTemplateConfig),
242
+ };
243
+ const outputs = hasPreset
244
+ ? await context.profiler.run(async () => preset.buildGeneratesSection({
245
+ baseOutputDir: filename,
246
+ presetConfig: outputConfig.presetConfig || {},
247
+ plugins: normalizedPluginsArray,
248
+ schema: outputSchema,
249
+ schemaAst: outputSchemaAst,
250
+ documents: outputDocuments,
251
+ config: mergedConfig,
252
+ pluginMap,
253
+ pluginContext,
254
+ profiler: context.profiler,
255
+ }), `Build Generates Section: ${filename}`)
256
+ : [
257
+ {
258
+ filename,
259
+ plugins: normalizedPluginsArray,
260
+ schema: outputSchema,
261
+ schemaAst: outputSchemaAst,
262
+ documents: outputDocuments,
263
+ config: mergedConfig,
264
+ pluginMap,
265
+ pluginContext,
266
+ profiler: context.profiler,
267
+ },
268
+ ];
269
+ const process = async (outputArgs) => {
270
+ const output = await (0, core_1.codegen)({
271
+ ...outputArgs,
272
+ cache,
273
+ });
274
+ result.push({
275
+ filename: outputArgs.filename,
276
+ content: output,
277
+ hooks: outputConfig.hooks || {},
278
+ });
279
+ };
280
+ await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
281
+ }, filename, `Generate: ${filename}`, ctx),
282
+ },
283
+ ], {
284
+ // it stops when of the tasks failed
285
+ exitOnError: true,
286
+ });
287
+ },
288
+ // It doesn't stop when one of tasks failed, to finish at least some of outputs
289
+ exitOnError: false,
290
+ concurrent: (0, os_1.cpus)().length,
291
+ };
292
+ });
293
+ return task.newListr(generateTasks);
294
+ },
295
+ },
296
+ ], {
297
+ rendererOptions: {
298
+ clearOutput: false,
299
+ collapse: true,
300
+ },
301
+ ctx: { errors: [] },
302
+ rendererSilent: isTest || config.silent,
303
+ exitOnError: true,
304
+ });
305
+ // All the errors throw in `listr2` are collected in context
306
+ // Running tasks doesn't throw anything
307
+ const executedContext = await tasks.run();
308
+ if (executedContext.errors.length > 0) {
309
+ const errors = executedContext.errors.map(subErr => (0, plugin_helpers_1.isDetailedError)(subErr)
310
+ ? `${subErr.message} for "${subErr.source}"${subErr.details}`
311
+ : subErr.message || subErr.toString());
312
+ const newErr = new utils_1.AggregateError(executedContext.errors, `${errors.join('\n\n')}`);
313
+ // Best-effort to all stack traces for debugging
314
+ newErr.stack = `${newErr.stack}\n\n${executedContext.errors.map(subErr => subErr.stack).join('\n\n')}`;
315
+ throw newErr;
316
+ }
317
+ return result;
318
+ }
319
+ exports.executeCodegen = executeCodegen;