@graphql-codegen/cli 2.6.3 → 2.6.5-alpha-acacb9e7a.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/bin.js CHANGED
@@ -29,12 +29,6 @@ const path__default = _interopDefault(path);
29
29
  const pluginHelpers = require('@graphql-codegen/plugin-helpers');
30
30
  const core = require('@graphql-codegen/core');
31
31
  const utils = require('@graphql-tools/utils');
32
- const chalk = _interopDefault(require('chalk'));
33
- const logSymbols = _interopDefault(require('log-symbols'));
34
- const ansiEscapes = _interopDefault(require('ansi-escapes'));
35
- const wrapAnsi = _interopDefault(require('wrap-ansi'));
36
- const commonTags = require('common-tags');
37
- const UpdateRenderer = _interopDefault(require('listr-update-renderer'));
38
32
  const graphql = require('graphql');
39
33
  const cosmiconfig = require('cosmiconfig');
40
34
  const stringEnvInterpolation = require('string-env-interpolation');
@@ -55,12 +49,15 @@ const fs = require('fs');
55
49
  const fs__default = _interopDefault(fs);
56
50
  const crypto = require('crypto');
57
51
  const os = require('os');
58
- const Listr = _interopDefault(require('listr'));
52
+ const listr2 = require('listr2');
59
53
  const isGlob = _interopDefault(require('is-glob'));
60
54
  const debounce = _interopDefault(require('debounce'));
55
+ const logSymbols = _interopDefault(require('log-symbols'));
61
56
  const mkdirp = _interopDefault(require('mkdirp'));
62
57
  const inquirer = _interopDefault(require('inquirer'));
58
+ const chalk = _interopDefault(require('chalk'));
63
59
  const detectIndent = _interopDefault(require('detect-indent'));
60
+ const getLatestVersion = _interopDefault(require('latest-version'));
64
61
 
65
62
  let logger;
66
63
  function getLogger() {
@@ -74,25 +71,8 @@ function useWinstonLogger() {
74
71
  logger = console;
75
72
  }
76
73
 
77
- let queue = [];
78
74
  function debugLog(message, ...meta) {
79
- if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) {
80
- queue.push({
81
- message,
82
- meta,
83
- });
84
- }
85
- }
86
- function printLogs() {
87
- if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) {
88
- queue.forEach(log => {
89
- getLogger().info(log.message, ...log.meta);
90
- });
91
- resetLogs();
92
- }
93
- }
94
- function resetLogs() {
95
- queue = [];
75
+ if (!process.env.GQL_CODEGEN_NODEBUG && process.env.DEBUG !== undefined) ;
96
76
  }
97
77
 
98
78
  const DEFAULT_HOOKS = {
@@ -150,7 +130,7 @@ function execShellCommand(cmd) {
150
130
  });
151
131
  }
152
132
  async function executeHooks(hookName, scripts = [], args = []) {
153
- debugLog(`Running lifecycle hook "${hookName}" scripts...`);
133
+ debugLog();
154
134
  for (const script of scripts) {
155
135
  if (typeof script === 'string') {
156
136
  debugLog(`Running lifecycle hook "${hookName}" script: ${script} with args: ${args.join(' ')}...`);
@@ -176,162 +156,6 @@ const lifecycleHooks = (_hooks = {}) => {
176
156
  };
177
157
  };
178
158
 
179
- /**
180
- Indent each line in a string.
181
- @param string - The string to indent.
182
- @param count - How many times you want `options.indent` repeated. Default: `1`.
183
- @example
184
- ```
185
- import indentString from 'indent-string';
186
- indentString('Unicorns\nRainbows', 4);
187
- //=> ' Unicorns\n Rainbows'
188
- indentString('Unicorns\nRainbows', 4, {indent: '♥'});
189
- //=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows'
190
- ```
191
- */
192
- function indentString(string, count = 1, options = {}) {
193
- const { indent = ' ', includeEmptyLines = false } = options;
194
- if (typeof string !== 'string') {
195
- throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);
196
- }
197
- if (typeof count !== 'number') {
198
- throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);
199
- }
200
- if (count < 0) {
201
- throw new RangeError(`Expected \`count\` to be at least 0, got \`${count}\``);
202
- }
203
- if (typeof indent !== 'string') {
204
- throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);
205
- }
206
- if (count === 0) {
207
- return string;
208
- }
209
- const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
210
- return string.replace(regex, indent.repeat(count));
211
- }
212
-
213
- class Renderer {
214
- constructor(tasks, options) {
215
- this.updateRenderer = new UpdateRenderer(tasks, options);
216
- }
217
- render() {
218
- return this.updateRenderer.render();
219
- }
220
- end(err) {
221
- this.updateRenderer.end(err);
222
- if (typeof err === 'undefined') {
223
- logUpdate.clear();
224
- return;
225
- }
226
- // persist the output
227
- logUpdate.done();
228
- // show errors
229
- if (err) {
230
- const errorCount = err.errors ? err.errors.length : 0;
231
- if (errorCount > 0) {
232
- const count = indentString(chalk.red.bold(`Found ${errorCount} error${errorCount > 1 ? 's' : ''}`), 1);
233
- const details = err.errors
234
- .map(error => {
235
- debugLog(`[CLI] Exited with an error`, error);
236
- return { msg: pluginHelpers.isDetailedError(error) ? error.details : null, rawError: error };
237
- })
238
- .map(({ msg, rawError }, i) => {
239
- const source = err.errors[i].source;
240
- msg = msg ? chalk.gray(indentString(commonTags.stripIndent(`${msg}`), 4)) : null;
241
- const stack = rawError.stack ? chalk.gray(indentString(commonTags.stripIndent(rawError.stack), 4)) : null;
242
- if (source) {
243
- const sourceOfError = typeof source === 'string' ? source : source.name;
244
- const title = indentString(`${logSymbols.error} ${sourceOfError}`, 2);
245
- return [title, msg, stack, stack].filter(Boolean).join('\n');
246
- }
247
- return [msg, stack].filter(Boolean).join('\n');
248
- })
249
- .join('\n\n');
250
- logUpdate.emit(['', count, details, ''].join('\n\n'));
251
- }
252
- else {
253
- const details = err.details ? err.details : '';
254
- logUpdate.emit(`${chalk.red.bold(`${indentString(err.message, 2)}`)}\n${details}\n${chalk.grey(err.stack)}`);
255
- }
256
- }
257
- logUpdate.done();
258
- printLogs();
259
- }
260
- }
261
- const render = tasks => {
262
- for (const task of tasks) {
263
- task.subscribe(event => {
264
- if (event.type === 'SUBTASKS') {
265
- render(task.subtasks);
266
- return;
267
- }
268
- if (event.type === 'DATA') {
269
- logUpdate.emit(chalk.dim(`${event.data}`));
270
- }
271
- logUpdate.done();
272
- }, err => {
273
- logUpdate.emit(err);
274
- logUpdate.done();
275
- });
276
- }
277
- };
278
- class ErrorRenderer {
279
- constructor(tasks, _options) {
280
- this.tasks = tasks;
281
- }
282
- render() {
283
- render(this.tasks);
284
- }
285
- static get nonTTY() {
286
- return true;
287
- }
288
- end() { }
289
- }
290
- class LogUpdate {
291
- constructor() {
292
- this.stream = process.stdout;
293
- // state
294
- this.previousLineCount = 0;
295
- this.previousOutput = '';
296
- this.previousWidth = this.getWidth();
297
- }
298
- emit(...args) {
299
- let output = args.join(' ') + '\n';
300
- const width = this.getWidth();
301
- if (output === this.previousOutput && this.previousWidth === width) {
302
- return;
303
- }
304
- this.previousOutput = output;
305
- this.previousWidth = width;
306
- output = wrapAnsi(output, width, {
307
- trim: false,
308
- hard: true,
309
- wordWrap: false,
310
- });
311
- this.stream.write(ansiEscapes.eraseLines(this.previousLineCount) + output);
312
- this.previousLineCount = output.split('\n').length;
313
- }
314
- clear() {
315
- this.stream.write(ansiEscapes.eraseLines(this.previousLineCount));
316
- this.previousOutput = '';
317
- this.previousWidth = this.getWidth();
318
- this.previousLineCount = 0;
319
- }
320
- done() {
321
- this.previousOutput = '';
322
- this.previousWidth = this.getWidth();
323
- this.previousLineCount = 0;
324
- }
325
- getWidth() {
326
- const { columns } = this.stream;
327
- if (!columns) {
328
- return 80;
329
- }
330
- return columns;
331
- }
332
- }
333
- const logUpdate = new LogUpdate();
334
-
335
159
  async function getPluginByName(name, pluginLoader) {
336
160
  const possibleNames = [
337
161
  `@graphql-codegen/${name}`,
@@ -829,33 +653,6 @@ function addHashToDocumentFiles(documentFilesPromise) {
829
653
  }));
830
654
  }
831
655
 
832
- const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
833
- const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
834
-
835
- function isListrError(err) {
836
- return err.name === 'ListrError' && Array.isArray(err.errors) && err.errors.length > 0;
837
- }
838
- function cliError(err, exitOnError = true) {
839
- let msg;
840
- if (err instanceof Error) {
841
- msg = err.message || err.toString();
842
- }
843
- else if (typeof err === 'string') {
844
- msg = err;
845
- }
846
- else {
847
- msg = JSON.stringify(err);
848
- }
849
- // eslint-disable-next-line no-console
850
- console.error(msg);
851
- if (exitOnError && isNode) {
852
- process.exit(1);
853
- }
854
- else if (exitOnError && isBrowser) {
855
- throw err;
856
- }
857
- }
858
-
859
656
  const makeDefaultLoader = (from) => {
860
657
  if (fs__default.statSync(from).isDirectory()) {
861
658
  from = path__default.join(from, '__fake.js');
@@ -883,39 +680,12 @@ async function executeCodegen(input) {
883
680
  const config = context.getConfig();
884
681
  const pluginContext = context.getPluginContext();
885
682
  const result = [];
886
- const commonListrOptions = {
887
- exitOnError: true,
888
- };
889
- let listr;
890
- if (process.env.VERBOSE) {
891
- listr = new Listr({
892
- ...commonListrOptions,
893
- renderer: 'verbose',
894
- nonTTYRenderer: 'verbose',
895
- });
896
- }
897
- else if (process.env.NODE_ENV === 'test') {
898
- listr = new Listr({
899
- ...commonListrOptions,
900
- renderer: 'silent',
901
- nonTTYRenderer: 'silent',
902
- });
903
- }
904
- else {
905
- listr = new Listr({
906
- ...commonListrOptions,
907
- renderer: config.silent ? 'silent' : config.errorsOnly ? ErrorRenderer : Renderer,
908
- nonTTYRenderer: config.silent ? 'silent' : 'default',
909
- collapse: true,
910
- clearOutput: false,
911
- });
912
- }
913
683
  let rootConfig = {};
914
684
  let rootSchemas;
915
685
  let rootDocuments;
916
686
  const generates = {};
917
687
  const cache = createCache();
918
- function wrapTask(task, source, taskName) {
688
+ function wrapTask(task, source, taskName, ctx) {
919
689
  return () => {
920
690
  return context.profiler.run(async () => {
921
691
  try {
@@ -925,6 +695,7 @@ async function executeCodegen(input) {
925
695
  if (source && !(error instanceof graphql.GraphQLError)) {
926
696
  error.source = source;
927
697
  }
698
+ ctx.errors.push(error);
928
699
  throw error;
929
700
  }
930
701
  }, taskName);
@@ -995,119 +766,109 @@ async function executeCodegen(input) {
995
766
  `);
996
767
  }
997
768
  }
998
- listr.add({
999
- title: 'Parse configuration',
1000
- task: () => normalize(),
1001
- });
1002
- listr.add({
1003
- title: 'Generate outputs',
1004
- task: () => {
1005
- return new Listr(Object.keys(generates).map(filename => {
1006
- const outputConfig = generates[filename];
1007
- const hasPreset = !!outputConfig.preset;
1008
- return {
1009
- title: hasPreset
769
+ const isTest = process.env.NODE_ENV === 'test';
770
+ const tasks = new listr2.Listr([
771
+ {
772
+ title: 'Parse Configuration',
773
+ task: () => normalize(),
774
+ },
775
+ {
776
+ title: 'Generate outputs',
777
+ task: (ctx, task) => {
778
+ const generateTasks = Object.keys(generates).map(filename => {
779
+ const outputConfig = generates[filename];
780
+ const hasPreset = !!outputConfig.preset;
781
+ const title = hasPreset
1010
782
  ? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
1011
- : `Generate ${filename}`,
1012
- task: () => {
1013
- let outputSchemaAst;
1014
- let outputSchema;
1015
- const outputFileTemplateConfig = outputConfig.config || {};
1016
- const outputDocuments = [];
1017
- const outputSpecificSchemas = pluginHelpers.normalizeInstanceOrArray(outputConfig.schema);
1018
- const outputSpecificDocuments = pluginHelpers.normalizeInstanceOrArray(outputConfig.documents);
1019
- return new Listr([
1020
- {
1021
- title: 'Load GraphQL schemas',
1022
- task: wrapTask(async () => {
1023
- debugLog(`[CLI] Loading Schemas`);
1024
- const schemaPointerMap = {};
1025
- const allSchemaUnnormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
1026
- for (const unnormalizedPtr of allSchemaUnnormalizedPointers) {
1027
- if (typeof unnormalizedPtr === 'string') {
1028
- schemaPointerMap[unnormalizedPtr] = {};
783
+ : `Generate ${filename}`;
784
+ return {
785
+ title,
786
+ task: (_, subTask) => {
787
+ let outputSchemaAst;
788
+ let outputSchema;
789
+ const outputFileTemplateConfig = outputConfig.config || {};
790
+ let outputDocuments = [];
791
+ const outputSpecificSchemas = pluginHelpers.normalizeInstanceOrArray(outputConfig.schema);
792
+ const outputSpecificDocuments = pluginHelpers.normalizeInstanceOrArray(outputConfig.documents);
793
+ return subTask.newListr([
794
+ {
795
+ title: 'Load GraphQL schemas',
796
+ task: wrapTask(async () => {
797
+ debugLog(`[CLI] Loading Schemas`);
798
+ const schemaPointerMap = {};
799
+ const allSchemaDenormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
800
+ for (const denormalizedPtr of allSchemaDenormalizedPointers) {
801
+ if (typeof denormalizedPtr === 'string') {
802
+ schemaPointerMap[denormalizedPtr] = {};
803
+ }
804
+ else if (typeof denormalizedPtr === 'object') {
805
+ Object.assign(schemaPointerMap, denormalizedPtr);
806
+ }
1029
807
  }
1030
- else if (typeof unnormalizedPtr === 'object') {
1031
- Object.assign(schemaPointerMap, unnormalizedPtr);
808
+ const hash = JSON.stringify(schemaPointerMap);
809
+ const result = await cache('schema', hash, async () => {
810
+ const outputSchemaAst = await context.loadSchema(schemaPointerMap);
811
+ const outputSchema = pluginHelpers.getCachedDocumentNodeFromSchema(outputSchemaAst);
812
+ return {
813
+ outputSchemaAst,
814
+ outputSchema,
815
+ };
816
+ });
817
+ outputSchemaAst = result.outputSchemaAst;
818
+ outputSchema = result.outputSchema;
819
+ }, filename, `Load GraphQL schemas: ${filename}`, ctx),
820
+ },
821
+ {
822
+ title: 'Load GraphQL documents',
823
+ task: wrapTask(async () => {
824
+ debugLog(`[CLI] Loading Documents`);
825
+ const documentPointerMap = {};
826
+ const allDocumentsDenormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
827
+ for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
828
+ if (typeof denormalizedPtr === 'string') {
829
+ documentPointerMap[denormalizedPtr] = {};
830
+ }
831
+ else if (typeof denormalizedPtr === 'object') {
832
+ Object.assign(documentPointerMap, denormalizedPtr);
833
+ }
1032
834
  }
1033
- }
1034
- const hash = JSON.stringify(schemaPointerMap);
1035
- const result = await cache('schema', hash, async () => {
1036
- const outputSchemaAst = await context.loadSchema(schemaPointerMap);
1037
- const outputSchema = pluginHelpers.getCachedDocumentNodeFromSchema(outputSchemaAst);
1038
- return {
1039
- outputSchemaAst,
1040
- outputSchema,
1041
- };
1042
- });
1043
- outputSchemaAst = await result.outputSchemaAst;
1044
- outputSchema = result.outputSchema;
1045
- }, filename, `Load GraphQL schemas: ${filename}`),
1046
- },
1047
- {
1048
- title: 'Load GraphQL documents',
1049
- task: wrapTask(async () => {
1050
- debugLog(`[CLI] Loading Documents`);
1051
- // get different cache for shared docs and output specific docs
1052
- const results = await Promise.all([rootDocuments, outputSpecificDocuments].map(docs => {
1053
- const hash = JSON.stringify(docs);
1054
- return cache('documents', hash, async () => {
1055
- const documents = await context.loadDocuments(docs);
835
+ const hash = JSON.stringify(documentPointerMap);
836
+ const result = await cache('documents', hash, async () => {
837
+ const documents = await context.loadDocuments(documentPointerMap);
1056
838
  return {
1057
839
  documents,
1058
840
  };
1059
841
  });
1060
- }));
1061
- const documents = [];
1062
- results.forEach(source => documents.push(...source.documents));
1063
- if (documents.length > 0) {
1064
- outputDocuments.push(...documents);
1065
- }
1066
- }, filename, `Load GraphQL documents: ${filename}`),
1067
- },
1068
- {
1069
- title: 'Generate',
1070
- task: wrapTask(async () => {
1071
- debugLog(`[CLI] Generating output`);
1072
- const normalizedPluginsArray = pluginHelpers.normalizeConfig(outputConfig.plugins);
1073
- const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
1074
- const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => getPluginByName(Object.keys(plugin)[0], pluginLoader)));
1075
- const pluginMap = {};
1076
- const preset = hasPreset
1077
- ? typeof outputConfig.preset === 'string'
1078
- ? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
1079
- : outputConfig.preset
1080
- : null;
1081
- pluginPackages.forEach((pluginPackage, i) => {
1082
- const plugin = normalizedPluginsArray[i];
1083
- const name = Object.keys(plugin)[0];
1084
- pluginMap[name] = pluginPackage;
1085
- });
1086
- const mergedConfig = {
1087
- ...rootConfig,
1088
- ...(typeof outputFileTemplateConfig === 'string'
1089
- ? { value: outputFileTemplateConfig }
1090
- : outputFileTemplateConfig),
1091
- };
1092
- let outputs = [];
1093
- if (hasPreset) {
1094
- outputs = await context.profiler.run(async () => preset.buildGeneratesSection({
1095
- baseOutputDir: filename,
1096
- presetConfig: outputConfig.presetConfig || {},
1097
- plugins: normalizedPluginsArray,
1098
- schema: outputSchema,
1099
- schemaAst: outputSchemaAst,
1100
- documents: outputDocuments,
1101
- config: mergedConfig,
1102
- pluginMap,
1103
- pluginContext,
1104
- profiler: context.profiler,
1105
- }), `Build Generates Section: ${filename}`);
1106
- }
1107
- else {
1108
- outputs = [
1109
- {
1110
- filename,
842
+ outputDocuments = result.documents;
843
+ }, filename, `Load GraphQL documents: ${filename}`, ctx),
844
+ },
845
+ {
846
+ title: 'Generate',
847
+ task: wrapTask(async () => {
848
+ debugLog(`[CLI] Generating output`);
849
+ const normalizedPluginsArray = pluginHelpers.normalizeConfig(outputConfig.plugins);
850
+ const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
851
+ const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => getPluginByName(Object.keys(plugin)[0], pluginLoader)));
852
+ const preset = hasPreset
853
+ ? typeof outputConfig.preset === 'string'
854
+ ? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
855
+ : outputConfig.preset
856
+ : null;
857
+ const pluginMap = Object.fromEntries(pluginPackages.map((pkg, i) => {
858
+ const plugin = normalizedPluginsArray[i];
859
+ const name = Object.keys(plugin)[0];
860
+ return [name, pkg];
861
+ }));
862
+ const mergedConfig = {
863
+ ...rootConfig,
864
+ ...(typeof outputFileTemplateConfig === 'string'
865
+ ? { value: outputFileTemplateConfig }
866
+ : outputFileTemplateConfig),
867
+ };
868
+ const outputs = hasPreset
869
+ ? await context.profiler.run(async () => preset.buildGeneratesSection({
870
+ baseOutputDir: filename,
871
+ presetConfig: outputConfig.presetConfig || {},
1111
872
  plugins: normalizedPluginsArray,
1112
873
  schema: outputSchema,
1113
874
  schemaAst: outputSchemaAst,
@@ -1116,50 +877,67 @@ async function executeCodegen(input) {
1116
877
  pluginMap,
1117
878
  pluginContext,
1118
879
  profiler: context.profiler,
1119
- },
1120
- ];
1121
- }
1122
- const process = async (outputArgs) => {
1123
- const output = await core.codegen({
1124
- ...outputArgs,
1125
- cache,
1126
- });
1127
- result.push({
1128
- filename: outputArgs.filename,
1129
- content: output,
1130
- hooks: outputConfig.hooks || {},
1131
- });
1132
- };
1133
- await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
1134
- }, filename, `Generate: ${filename}`),
1135
- },
1136
- ], {
1137
- // it stops when one of tasks failed
1138
- exitOnError: true,
1139
- });
1140
- },
1141
- };
1142
- }), {
1143
- // it doesn't stop when one of tasks failed, to finish at least some of outputs
1144
- exitOnError: false,
1145
- concurrent: os.cpus().length,
1146
- });
880
+ }), `Build Generates Section: ${filename}`)
881
+ : [
882
+ {
883
+ filename,
884
+ plugins: normalizedPluginsArray,
885
+ schema: outputSchema,
886
+ schemaAst: outputSchemaAst,
887
+ documents: outputDocuments,
888
+ config: mergedConfig,
889
+ pluginMap,
890
+ pluginContext,
891
+ profiler: context.profiler,
892
+ },
893
+ ];
894
+ const process = async (outputArgs) => {
895
+ const output = await core.codegen({
896
+ ...outputArgs,
897
+ cache,
898
+ });
899
+ result.push({
900
+ filename: outputArgs.filename,
901
+ content: output,
902
+ hooks: outputConfig.hooks || {},
903
+ });
904
+ };
905
+ await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
906
+ }, filename, `Generate: ${filename}`, ctx),
907
+ },
908
+ ], {
909
+ // it stops when of the tasks failed
910
+ exitOnError: true,
911
+ });
912
+ },
913
+ // It doesn't stop when one of tasks failed, to finish at least some of outputs
914
+ exitOnError: false,
915
+ concurrent: os.cpus().length,
916
+ };
917
+ });
918
+ return task.newListr(generateTasks);
919
+ },
1147
920
  },
921
+ ], {
922
+ rendererOptions: {
923
+ clearOutput: false,
924
+ collapse: true,
925
+ },
926
+ ctx: { errors: [] },
927
+ rendererSilent: isTest || config.silent,
928
+ exitOnError: true,
1148
929
  });
1149
- try {
1150
- await listr.run();
1151
- }
1152
- catch (err) {
1153
- if (isListrError(err)) {
1154
- const allErrs = err.errors.map(subErr => pluginHelpers.isDetailedError(subErr)
1155
- ? `${subErr.message} for "${subErr.source}"${subErr.details}`
1156
- : subErr.message || subErr.toString());
1157
- const newErr = new utils.AggregateError(err.errors, `${err.message} ${allErrs.join('\n\n')}`);
1158
- // Best-effort to all stack traces for debugging
1159
- newErr.stack = `${newErr.stack}\n\n${err.errors.map(subErr => subErr.stack).join('\n\n')}`;
1160
- throw newErr;
1161
- }
1162
- throw err;
930
+ // All the errors throw in `listr2` are collected in context
931
+ // Running tasks doesn't throw anything
932
+ const executedContext = await tasks.run();
933
+ if (executedContext.errors.length > 0) {
934
+ const errors = executedContext.errors.map(subErr => pluginHelpers.isDetailedError(subErr)
935
+ ? `${subErr.message} for "${subErr.source}"${subErr.details}`
936
+ : subErr.message || subErr.toString());
937
+ const newErr = new utils.AggregateError(executedContext.errors, `${errors.join('\n\n')}`);
938
+ // Best-effort to all stack traces for debugging
939
+ newErr.stack = `${newErr.stack}\n\n${executedContext.errors.map(subErr => subErr.stack).join('\n\n')}`;
940
+ throw newErr;
1163
941
  }
1164
942
  return result;
1165
943
  }
@@ -1172,7 +950,7 @@ function emitWatching() {
1172
950
  log(`${logSymbols.info} Watching for changes...`);
1173
951
  }
1174
952
  const createWatcher = (initalContext, onNext) => {
1175
- debugLog(`[Watcher] Starting watcher...`);
953
+ debugLog();
1176
954
  let config = initalContext.getConfig();
1177
955
  const files = [initalContext.filepath].filter(a => a);
1178
956
  const documents = pluginHelpers.normalizeInstanceOrArray(config.documents);
@@ -1243,10 +1021,10 @@ const createWatcher = (initalContext, onNext) => {
1243
1021
  atomic: true,
1244
1022
  ignored,
1245
1023
  });
1246
- debugLog(`[Watcher] Started`);
1024
+ debugLog();
1247
1025
  const shutdown = () => {
1248
1026
  isShutdown = true;
1249
- debugLog(`[Watcher] Shutting down`);
1027
+ debugLog();
1250
1028
  log(`Shutting down watch...`);
1251
1029
  watcher.close();
1252
1030
  lifecycleHooks(config.hooks).beforeDone();
@@ -1254,7 +1032,7 @@ const createWatcher = (initalContext, onNext) => {
1254
1032
  // it doesn't matter what has changed, need to run whole process anyway
1255
1033
  watcher.on('all', async (eventName, path$1) => {
1256
1034
  lifecycleHooks(config.hooks).onWatchTriggered(eventName, path$1);
1257
- debugLog(`[Watcher] triggered due to a file ${eventName} event: ${path$1}`);
1035
+ debugLog();
1258
1036
  const fullPath = path.join(process.cwd(), path$1);
1259
1037
  // In ESM require is not defined
1260
1038
  try {
@@ -1323,10 +1101,10 @@ async function generate(input, saveToFile = true) {
1323
1101
  return unlinkFile(filename, err => {
1324
1102
  const prettyFilename = filename.replace(`${input.cwd || process.cwd()}/`, '');
1325
1103
  if (err) {
1326
- debugLog(`Cannot remove stale file: ${prettyFilename}\n${err}`);
1104
+ debugLog();
1327
1105
  }
1328
1106
  else {
1329
- debugLog(`Removed stale file: ${prettyFilename}`);
1107
+ debugLog();
1330
1108
  }
1331
1109
  });
1332
1110
  }
@@ -1393,7 +1171,7 @@ function shouldOverwrite(config, outputPath) {
1393
1171
  const globalValue = config.overwrite === undefined ? true : !!config.overwrite;
1394
1172
  const outputConfig = config.generates[outputPath];
1395
1173
  if (!outputConfig) {
1396
- debugLog(`Couldn't find a config of ${outputPath}`);
1174
+ debugLog();
1397
1175
  return globalValue;
1398
1176
  }
1399
1177
  if (isConfiguredOutput(outputConfig) && typeof outputConfig.overwrite === 'boolean') {
@@ -1422,8 +1200,6 @@ async function writeConfig(answers, config) {
1422
1200
  }
1423
1201
  // Updates package.json (script and plugins as dependencies)
1424
1202
  async function writePackage(answers, configLocation) {
1425
- // dynamic import because latest-version is pure ESM
1426
- const getLatestVersion = (await new Promise(function (resolve) { resolve(_interopNamespace(require('latest-version'))); })).default;
1427
1203
  // script
1428
1204
  const pkgPath = path.resolve(process.cwd(), 'package.json');
1429
1205
  const pkgContent = fs.readFileSync(pkgPath, {
@@ -1885,6 +1661,24 @@ async function ensureGraphQlPackage() {
1885
1661
  }
1886
1662
  }
1887
1663
 
1664
+ function cliError(err, exitOnError = true) {
1665
+ let msg;
1666
+ if (err instanceof Error) {
1667
+ msg = err.message || err.toString();
1668
+ }
1669
+ else if (typeof err === 'string') {
1670
+ msg = err;
1671
+ }
1672
+ else {
1673
+ msg = JSON.stringify(err);
1674
+ }
1675
+ // eslint-disable-next-line no-console
1676
+ console.error(msg);
1677
+ if (exitOnError) {
1678
+ process.exit(1);
1679
+ }
1680
+ }
1681
+
1888
1682
  const [, , cmd] = process.argv;
1889
1683
  runCli(cmd)
1890
1684
  .then(() => {