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