@graphql-codegen/cli 2.8.0-alpha-2ada7b533.0 → 2.9.0-alpha-33d33bf6b.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/codegen.js CHANGED
@@ -5,7 +5,6 @@ const tslib_1 = require("tslib");
5
5
  const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
6
6
  const core_1 = require("@graphql-codegen/core");
7
7
  const utils_1 = require("@graphql-tools/utils");
8
- const listr_renderer_js_1 = require("./utils/listr-renderer.js");
9
8
  const graphql_1 = require("graphql");
10
9
  const plugins_js_1 = require("./plugins.js");
11
10
  const presets_js_1 = require("./presets.js");
@@ -15,8 +14,7 @@ const fs_1 = tslib_1.__importDefault(require("fs"));
15
14
  const path_1 = tslib_1.__importDefault(require("path"));
16
15
  const os_1 = require("os");
17
16
  const module_1 = require("module");
18
- const listr_1 = tslib_1.__importDefault(require("listr"));
19
- const cli_error_js_1 = require("./utils/cli-error.js");
17
+ const listr2_1 = require("listr2");
20
18
  /**
21
19
  * Poor mans ESM detection.
22
20
  * Looking at this and you have a better method?
@@ -57,39 +55,12 @@ async function executeCodegen(input) {
57
55
  const config = context.getConfig();
58
56
  const pluginContext = context.getPluginContext();
59
57
  const result = [];
60
- const commonListrOptions = {
61
- exitOnError: true,
62
- };
63
- let listr;
64
- if (process.env.VERBOSE) {
65
- listr = new listr_1.default({
66
- ...commonListrOptions,
67
- renderer: 'verbose',
68
- nonTTYRenderer: 'verbose',
69
- });
70
- }
71
- else if (process.env.NODE_ENV === 'test') {
72
- listr = new listr_1.default({
73
- ...commonListrOptions,
74
- renderer: 'silent',
75
- nonTTYRenderer: 'silent',
76
- });
77
- }
78
- else {
79
- listr = new listr_1.default({
80
- ...commonListrOptions,
81
- renderer: config.silent ? 'silent' : config.errorsOnly ? listr_renderer_js_1.ErrorRenderer : listr_renderer_js_1.Renderer,
82
- nonTTYRenderer: config.silent ? 'silent' : 'default',
83
- collapse: true,
84
- clearOutput: false,
85
- });
86
- }
87
58
  let rootConfig = {};
88
59
  let rootSchemas;
89
60
  let rootDocuments;
90
61
  const generates = {};
91
62
  const cache = createCache();
92
- function wrapTask(task, source, taskName) {
63
+ function wrapTask(task, source, taskName, ctx) {
93
64
  return () => {
94
65
  return context.profiler.run(async () => {
95
66
  try {
@@ -99,6 +70,7 @@ async function executeCodegen(input) {
99
70
  if (source && !(error instanceof graphql_1.GraphQLError)) {
100
71
  error.source = source;
101
72
  }
73
+ ctx.errors.push(error);
102
74
  throw error;
103
75
  }
104
76
  }, taskName);
@@ -169,123 +141,109 @@ async function executeCodegen(input) {
169
141
  `);
170
142
  }
171
143
  }
172
- listr.add({
173
- title: 'Parse configuration',
174
- task: () => normalize(),
175
- });
176
- listr.add({
177
- title: 'Generate outputs',
178
- task: () => {
179
- return new listr_1.default(Object.keys(generates).map(filename => {
180
- const outputConfig = generates[filename];
181
- const hasPreset = !!outputConfig.preset;
182
- return {
183
- title: hasPreset
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
184
157
  ? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
185
- : `Generate ${filename}`,
186
- task: () => {
187
- let outputSchemaAst;
188
- let outputSchema;
189
- const outputFileTemplateConfig = outputConfig.config || {};
190
- let outputDocuments = [];
191
- const outputSpecificSchemas = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.schema);
192
- const outputSpecificDocuments = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.documents);
193
- return new listr_1.default([
194
- {
195
- title: 'Load GraphQL schemas',
196
- task: wrapTask(async () => {
197
- (0, debugging_js_1.debugLog)(`[CLI] Loading Schemas`);
198
- const schemaPointerMap = {};
199
- const allSchemaUnnormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
200
- for (const unnormalizedPtr of allSchemaUnnormalizedPointers) {
201
- if (typeof unnormalizedPtr === 'string') {
202
- schemaPointerMap[unnormalizedPtr] = {};
203
- }
204
- else if (typeof unnormalizedPtr === 'object') {
205
- Object.assign(schemaPointerMap, unnormalizedPtr);
206
- }
207
- }
208
- const hash = JSON.stringify(schemaPointerMap);
209
- const result = await cache('schema', hash, async () => {
210
- const outputSchemaAst = await context.loadSchema(schemaPointerMap);
211
- const outputSchema = (0, plugin_helpers_1.getCachedDocumentNodeFromSchema)(outputSchemaAst);
212
- return {
213
- outputSchemaAst,
214
- outputSchema,
215
- };
216
- });
217
- outputSchemaAst = await result.outputSchemaAst;
218
- outputSchema = result.outputSchema;
219
- }, filename, `Load GraphQL schemas: ${filename}`),
220
- },
221
- {
222
- title: 'Load GraphQL documents',
223
- task: wrapTask(async () => {
224
- (0, debugging_js_1.debugLog)(`[CLI] Loading Documents`);
225
- // get different cache for shared docs and output specific docs
226
- const documentPointerMap = {};
227
- const allDocumentsUnnormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
228
- for (const unnormalizedPtr of allDocumentsUnnormalizedPointers) {
229
- if (typeof unnormalizedPtr === 'string') {
230
- documentPointerMap[unnormalizedPtr] = {};
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
+ }
231
182
  }
232
- else if (typeof unnormalizedPtr === 'object') {
233
- Object.assign(documentPointerMap, unnormalizedPtr);
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
+ }
234
209
  }
235
- }
236
- const hash = JSON.stringify(documentPointerMap);
237
- const result = await cache('documents', hash, async () => {
238
- const documents = await context.loadDocuments(documentPointerMap);
239
- return {
240
- documents,
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),
241
242
  };
242
- });
243
- outputDocuments = await result.documents;
244
- }, filename, `Load GraphQL documents: ${filename}`),
245
- },
246
- {
247
- title: 'Generate',
248
- task: wrapTask(async () => {
249
- (0, debugging_js_1.debugLog)(`[CLI] Generating output`);
250
- const normalizedPluginsArray = (0, plugin_helpers_1.normalizeConfig)(outputConfig.plugins);
251
- const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
252
- const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => (0, plugins_js_1.getPluginByName)(Object.keys(plugin)[0], pluginLoader)));
253
- const pluginMap = {};
254
- const preset = hasPreset
255
- ? typeof outputConfig.preset === 'string'
256
- ? await (0, presets_js_1.getPresetByName)(outputConfig.preset, makeDefaultLoader(context.cwd))
257
- : outputConfig.preset
258
- : null;
259
- pluginPackages.forEach((pluginPackage, i) => {
260
- const plugin = normalizedPluginsArray[i];
261
- const name = Object.keys(plugin)[0];
262
- pluginMap[name] = pluginPackage;
263
- });
264
- const mergedConfig = {
265
- ...rootConfig,
266
- ...(typeof outputFileTemplateConfig === 'string'
267
- ? { value: outputFileTemplateConfig }
268
- : outputFileTemplateConfig),
269
- };
270
- let outputs = [];
271
- if (hasPreset) {
272
- outputs = await context.profiler.run(async () => preset.buildGeneratesSection({
273
- baseOutputDir: filename,
274
- presetConfig: outputConfig.presetConfig || {},
275
- plugins: normalizedPluginsArray,
276
- schema: outputSchema,
277
- schemaAst: outputSchemaAst,
278
- documents: outputDocuments,
279
- config: mergedConfig,
280
- pluginMap,
281
- pluginContext,
282
- profiler: context.profiler,
283
- }), `Build Generates Section: ${filename}`);
284
- }
285
- else {
286
- outputs = [
287
- {
288
- filename,
243
+ const outputs = hasPreset
244
+ ? await context.profiler.run(async () => preset.buildGeneratesSection({
245
+ baseOutputDir: filename,
246
+ presetConfig: outputConfig.presetConfig || {},
289
247
  plugins: normalizedPluginsArray,
290
248
  schema: outputSchema,
291
249
  schemaAst: outputSchemaAst,
@@ -294,50 +252,67 @@ async function executeCodegen(input) {
294
252
  pluginMap,
295
253
  pluginContext,
296
254
  profiler: context.profiler,
297
- },
298
- ];
299
- }
300
- const process = async (outputArgs) => {
301
- const output = await (0, core_1.codegen)({
302
- ...outputArgs,
303
- cache,
304
- });
305
- result.push({
306
- filename: outputArgs.filename,
307
- content: output,
308
- hooks: outputConfig.hooks || {},
309
- });
310
- };
311
- await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
312
- }, filename, `Generate: ${filename}`),
313
- },
314
- ], {
315
- // it stops when one of tasks failed
316
- exitOnError: true,
317
- });
318
- },
319
- };
320
- }), {
321
- // it doesn't stop when one of tasks failed, to finish at least some of outputs
322
- exitOnError: false,
323
- concurrent: (0, os_1.cpus)().length,
324
- });
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
+ },
325
295
  },
296
+ ], {
297
+ rendererOptions: {
298
+ clearOutput: false,
299
+ collapse: true,
300
+ },
301
+ ctx: { errors: [] },
302
+ rendererSilent: isTest || config.silent,
303
+ exitOnError: true,
326
304
  });
327
- try {
328
- await listr.run();
329
- }
330
- catch (err) {
331
- if ((0, cli_error_js_1.isListrError)(err)) {
332
- const allErrs = err.errors.map(subErr => (0, plugin_helpers_1.isDetailedError)(subErr)
333
- ? `${subErr.message} for "${subErr.source}"${subErr.details}`
334
- : subErr.message || subErr.toString());
335
- const newErr = new utils_1.AggregateError(err.errors, `${err.message} ${allErrs.join('\n\n')}`);
336
- // Best-effort to all stack traces for debugging
337
- newErr.stack = `${newErr.stack}\n\n${err.errors.map(subErr => subErr.stack).join('\n\n')}`;
338
- throw newErr;
339
- }
340
- throw err;
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;
341
316
  }
342
317
  return result;
343
318
  }
package/cjs/config.js CHANGED
@@ -195,6 +195,10 @@ function updateContextWithCliFlags(context, cliFlags) {
195
195
  // for some reason parsed value is `'false'` string so this ensure it always is a boolean.
196
196
  config.ignoreNoDocuments = cliFlags['ignore-no-documents'] === true;
197
197
  }
198
+ if (cliFlags['emit-legacy-common-js-imports'] !== undefined) {
199
+ // for some reason parsed value is `'false'` string so this ensure it always is a boolean.
200
+ config.emitLegacyCommonJSImports = cliFlags['emit-legacy-common-js-imports'] === true;
201
+ }
198
202
  if (cliFlags.project) {
199
203
  context.useProject(cliFlags.project);
200
204
  }
package/esm/codegen.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { DetailedError, normalizeOutputParam, normalizeInstanceOrArray, normalizeConfig, getCachedDocumentNodeFromSchema, isDetailedError, } from '@graphql-codegen/plugin-helpers';
2
2
  import { codegen } from '@graphql-codegen/core';
3
3
  import { AggregateError } from '@graphql-tools/utils';
4
- import { Renderer, ErrorRenderer } from './utils/listr-renderer.js';
5
4
  import { GraphQLError } from 'graphql';
6
5
  import { getPluginByName } from './plugins.js';
7
6
  import { getPresetByName } from './presets.js';
@@ -11,8 +10,7 @@ import fs from 'fs';
11
10
  import path from 'path';
12
11
  import { cpus } from 'os';
13
12
  import { createRequire } from 'module';
14
- import Listr from 'listr';
15
- import { isListrError } from './utils/cli-error.js';
13
+ import { Listr } from 'listr2';
16
14
  /**
17
15
  * Poor mans ESM detection.
18
16
  * Looking at this and you have a better method?
@@ -53,39 +51,12 @@ export async function executeCodegen(input) {
53
51
  const config = context.getConfig();
54
52
  const pluginContext = context.getPluginContext();
55
53
  const result = [];
56
- const commonListrOptions = {
57
- exitOnError: true,
58
- };
59
- let listr;
60
- if (process.env.VERBOSE) {
61
- listr = new Listr({
62
- ...commonListrOptions,
63
- renderer: 'verbose',
64
- nonTTYRenderer: 'verbose',
65
- });
66
- }
67
- else if (process.env.NODE_ENV === 'test') {
68
- listr = new Listr({
69
- ...commonListrOptions,
70
- renderer: 'silent',
71
- nonTTYRenderer: 'silent',
72
- });
73
- }
74
- else {
75
- listr = new Listr({
76
- ...commonListrOptions,
77
- renderer: config.silent ? 'silent' : config.errorsOnly ? ErrorRenderer : Renderer,
78
- nonTTYRenderer: config.silent ? 'silent' : 'default',
79
- collapse: true,
80
- clearOutput: false,
81
- });
82
- }
83
54
  let rootConfig = {};
84
55
  let rootSchemas;
85
56
  let rootDocuments;
86
57
  const generates = {};
87
58
  const cache = createCache();
88
- function wrapTask(task, source, taskName) {
59
+ function wrapTask(task, source, taskName, ctx) {
89
60
  return () => {
90
61
  return context.profiler.run(async () => {
91
62
  try {
@@ -95,6 +66,7 @@ export async function executeCodegen(input) {
95
66
  if (source && !(error instanceof GraphQLError)) {
96
67
  error.source = source;
97
68
  }
69
+ ctx.errors.push(error);
98
70
  throw error;
99
71
  }
100
72
  }, taskName);
@@ -165,123 +137,109 @@ export async function executeCodegen(input) {
165
137
  `);
166
138
  }
167
139
  }
168
- listr.add({
169
- title: 'Parse configuration',
170
- task: () => normalize(),
171
- });
172
- listr.add({
173
- title: 'Generate outputs',
174
- task: () => {
175
- return new Listr(Object.keys(generates).map(filename => {
176
- const outputConfig = generates[filename];
177
- const hasPreset = !!outputConfig.preset;
178
- return {
179
- title: hasPreset
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
180
153
  ? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
181
- : `Generate ${filename}`,
182
- task: () => {
183
- let outputSchemaAst;
184
- let outputSchema;
185
- const outputFileTemplateConfig = outputConfig.config || {};
186
- let outputDocuments = [];
187
- const outputSpecificSchemas = normalizeInstanceOrArray(outputConfig.schema);
188
- const outputSpecificDocuments = normalizeInstanceOrArray(outputConfig.documents);
189
- return new Listr([
190
- {
191
- title: 'Load GraphQL schemas',
192
- task: wrapTask(async () => {
193
- debugLog(`[CLI] Loading Schemas`);
194
- const schemaPointerMap = {};
195
- const allSchemaUnnormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
196
- for (const unnormalizedPtr of allSchemaUnnormalizedPointers) {
197
- if (typeof unnormalizedPtr === 'string') {
198
- schemaPointerMap[unnormalizedPtr] = {};
199
- }
200
- else if (typeof unnormalizedPtr === 'object') {
201
- Object.assign(schemaPointerMap, unnormalizedPtr);
202
- }
203
- }
204
- const hash = JSON.stringify(schemaPointerMap);
205
- const result = await cache('schema', hash, async () => {
206
- const outputSchemaAst = await context.loadSchema(schemaPointerMap);
207
- const outputSchema = getCachedDocumentNodeFromSchema(outputSchemaAst);
208
- return {
209
- outputSchemaAst,
210
- outputSchema,
211
- };
212
- });
213
- outputSchemaAst = await result.outputSchemaAst;
214
- outputSchema = result.outputSchema;
215
- }, filename, `Load GraphQL schemas: ${filename}`),
216
- },
217
- {
218
- title: 'Load GraphQL documents',
219
- task: wrapTask(async () => {
220
- debugLog(`[CLI] Loading Documents`);
221
- // get different cache for shared docs and output specific docs
222
- const documentPointerMap = {};
223
- const allDocumentsUnnormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
224
- for (const unnormalizedPtr of allDocumentsUnnormalizedPointers) {
225
- if (typeof unnormalizedPtr === 'string') {
226
- documentPointerMap[unnormalizedPtr] = {};
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
+ }
227
178
  }
228
- else if (typeof unnormalizedPtr === 'object') {
229
- Object.assign(documentPointerMap, unnormalizedPtr);
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
+ }
230
205
  }
231
- }
232
- const hash = JSON.stringify(documentPointerMap);
233
- const result = await cache('documents', hash, async () => {
234
- const documents = await context.loadDocuments(documentPointerMap);
235
- return {
236
- documents,
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),
237
238
  };
238
- });
239
- outputDocuments = await result.documents;
240
- }, filename, `Load GraphQL documents: ${filename}`),
241
- },
242
- {
243
- title: 'Generate',
244
- task: wrapTask(async () => {
245
- debugLog(`[CLI] Generating output`);
246
- const normalizedPluginsArray = normalizeConfig(outputConfig.plugins);
247
- const pluginLoader = config.pluginLoader || makeDefaultLoader(context.cwd);
248
- const pluginPackages = await Promise.all(normalizedPluginsArray.map(plugin => getPluginByName(Object.keys(plugin)[0], pluginLoader)));
249
- const pluginMap = {};
250
- const preset = hasPreset
251
- ? typeof outputConfig.preset === 'string'
252
- ? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
253
- : outputConfig.preset
254
- : null;
255
- pluginPackages.forEach((pluginPackage, i) => {
256
- const plugin = normalizedPluginsArray[i];
257
- const name = Object.keys(plugin)[0];
258
- pluginMap[name] = pluginPackage;
259
- });
260
- const mergedConfig = {
261
- ...rootConfig,
262
- ...(typeof outputFileTemplateConfig === 'string'
263
- ? { value: outputFileTemplateConfig }
264
- : outputFileTemplateConfig),
265
- };
266
- let outputs = [];
267
- if (hasPreset) {
268
- outputs = await context.profiler.run(async () => preset.buildGeneratesSection({
269
- baseOutputDir: filename,
270
- presetConfig: outputConfig.presetConfig || {},
271
- plugins: normalizedPluginsArray,
272
- schema: outputSchema,
273
- schemaAst: outputSchemaAst,
274
- documents: outputDocuments,
275
- config: mergedConfig,
276
- pluginMap,
277
- pluginContext,
278
- profiler: context.profiler,
279
- }), `Build Generates Section: ${filename}`);
280
- }
281
- else {
282
- outputs = [
283
- {
284
- filename,
239
+ const outputs = hasPreset
240
+ ? await context.profiler.run(async () => preset.buildGeneratesSection({
241
+ baseOutputDir: filename,
242
+ presetConfig: outputConfig.presetConfig || {},
285
243
  plugins: normalizedPluginsArray,
286
244
  schema: outputSchema,
287
245
  schemaAst: outputSchemaAst,
@@ -290,50 +248,67 @@ export async function executeCodegen(input) {
290
248
  pluginMap,
291
249
  pluginContext,
292
250
  profiler: context.profiler,
293
- },
294
- ];
295
- }
296
- const process = async (outputArgs) => {
297
- const output = await codegen({
298
- ...outputArgs,
299
- cache,
300
- });
301
- result.push({
302
- filename: outputArgs.filename,
303
- content: output,
304
- hooks: outputConfig.hooks || {},
305
- });
306
- };
307
- await context.profiler.run(() => Promise.all(outputs.map(process)), `Codegen: ${filename}`);
308
- }, filename, `Generate: ${filename}`),
309
- },
310
- ], {
311
- // it stops when one of tasks failed
312
- exitOnError: true,
313
- });
314
- },
315
- };
316
- }), {
317
- // it doesn't stop when one of tasks failed, to finish at least some of outputs
318
- exitOnError: false,
319
- concurrent: cpus().length,
320
- });
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
+ },
321
291
  },
292
+ ], {
293
+ rendererOptions: {
294
+ clearOutput: false,
295
+ collapse: true,
296
+ },
297
+ ctx: { errors: [] },
298
+ rendererSilent: isTest || config.silent,
299
+ exitOnError: true,
322
300
  });
323
- try {
324
- await listr.run();
325
- }
326
- catch (err) {
327
- if (isListrError(err)) {
328
- const allErrs = err.errors.map(subErr => isDetailedError(subErr)
329
- ? `${subErr.message} for "${subErr.source}"${subErr.details}`
330
- : subErr.message || subErr.toString());
331
- const newErr = new AggregateError(err.errors, `${err.message} ${allErrs.join('\n\n')}`);
332
- // Best-effort to all stack traces for debugging
333
- newErr.stack = `${newErr.stack}\n\n${err.errors.map(subErr => subErr.stack).join('\n\n')}`;
334
- throw newErr;
335
- }
336
- throw err;
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;
337
312
  }
338
313
  return result;
339
314
  }
package/esm/config.js CHANGED
@@ -185,6 +185,10 @@ export function updateContextWithCliFlags(context, cliFlags) {
185
185
  // for some reason parsed value is `'false'` string so this ensure it always is a boolean.
186
186
  config.ignoreNoDocuments = cliFlags['ignore-no-documents'] === true;
187
187
  }
188
+ if (cliFlags['emit-legacy-common-js-imports'] !== undefined) {
189
+ // for some reason parsed value is `'false'` string so this ensure it always is a boolean.
190
+ config.emitLegacyCommonJSImports = cliFlags['emit-legacy-common-js-imports'] === true;
191
+ }
188
192
  if (cliFlags.project) {
189
193
  context.useProject(cliFlags.project);
190
194
  }
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@graphql-codegen/cli",
3
- "version": "2.8.0-alpha-2ada7b533.0",
3
+ "version": "2.9.0-alpha-33d33bf6b.0",
4
4
  "peerDependencies": {
5
5
  "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0"
6
6
  },
7
7
  "dependencies": {
8
- "@graphql-codegen/core": "2.5.2-alpha-2ada7b533.0",
9
- "@graphql-codegen/plugin-helpers": "^2.5.0-alpha-2ada7b533.0",
8
+ "@graphql-codegen/core": "2.6.1-alpha-33d33bf6b.0",
9
+ "@graphql-codegen/plugin-helpers": "^2.6.0-alpha-33d33bf6b.0",
10
10
  "@graphql-tools/apollo-engine-loader": "^7.3.1",
11
11
  "@graphql-tools/code-file-loader": "^7.3.0",
12
12
  "@graphql-tools/git-loader": "^7.2.0",
@@ -19,9 +19,7 @@
19
19
  "@graphql-tools/utils": "^8.8.0",
20
20
  "ansi-escapes": "^4.3.1",
21
21
  "chalk": "^4.1.0",
22
- "change-case-all": "1.0.14",
23
22
  "chokidar": "^3.5.2",
24
- "common-tags": "^1.8.0",
25
23
  "cosmiconfig": "^7.0.0",
26
24
  "cross-undici-fetch": "^0.4.11",
27
25
  "debounce": "^1.2.0",
@@ -30,13 +28,11 @@
30
28
  "inquirer": "^8.0.0",
31
29
  "is-glob": "^4.0.1",
32
30
  "json-to-pretty-yaml": "^1.2.2",
33
- "listr": "^0.14.3",
34
- "listr-update-renderer": "^0.5.0",
31
+ "listr2": "^4.0.5",
35
32
  "log-symbols": "^4.0.0",
36
33
  "mkdirp": "^1.0.4",
37
34
  "string-env-interpolation": "^1.0.1",
38
35
  "ts-log": "^2.2.3",
39
- "wrap-ansi": "^7.0.0",
40
36
  "yaml": "^1.10.0",
41
37
  "yargs": "^17.0.0"
42
38
  },
@@ -11,6 +11,7 @@ export declare type YamlCliFlags = {
11
11
  errorsOnly: boolean;
12
12
  profile: boolean;
13
13
  ignoreNoDocuments?: boolean;
14
+ emitLegacyCommonJSImports?: boolean;
14
15
  };
15
16
  export declare function generateSearchPlaces(moduleName: string): string[];
16
17
  export interface LoadCodegenConfigOptions {
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.indentString = void 0;
4
- /**
5
- Indent each line in a string.
6
- @param string - The string to indent.
7
- @param count - How many times you want `options.indent` repeated. Default: `1`.
8
- @example
9
- ```
10
- import indentString from 'indent-string';
11
- indentString('Unicorns\nRainbows', 4);
12
- //=> ' Unicorns\n Rainbows'
13
- indentString('Unicorns\nRainbows', 4, {indent: '♥'});
14
- //=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows'
15
- ```
16
- */
17
- function indentString(string, count = 1, options = {}) {
18
- const { indent = ' ', includeEmptyLines = false } = options;
19
- if (typeof string !== 'string') {
20
- throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);
21
- }
22
- if (typeof count !== 'number') {
23
- throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);
24
- }
25
- if (count < 0) {
26
- throw new RangeError(`Expected \`count\` to be at least 0, got \`${count}\``);
27
- }
28
- if (typeof indent !== 'string') {
29
- throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);
30
- }
31
- if (count === 0) {
32
- return string;
33
- }
34
- const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
35
- return string.replace(regex, indent.repeat(count));
36
- }
37
- exports.indentString = indentString;
@@ -1,136 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ErrorRenderer = exports.Renderer = void 0;
4
- const tslib_1 = require("tslib");
5
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
6
- const indentString_js_1 = require("./indentString.js");
7
- const log_symbols_1 = tslib_1.__importDefault(require("log-symbols"));
8
- const ansi_escapes_1 = tslib_1.__importDefault(require("ansi-escapes"));
9
- const wrap_ansi_1 = tslib_1.__importDefault(require("wrap-ansi"));
10
- const common_tags_1 = require("common-tags");
11
- const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
12
- const debugging_js_1 = require("./debugging.js");
13
- const listr_update_renderer_1 = tslib_1.__importDefault(require("listr-update-renderer"));
14
- class Renderer {
15
- constructor(tasks, options) {
16
- this.updateRenderer = new listr_update_renderer_1.default(tasks, options);
17
- }
18
- render() {
19
- return this.updateRenderer.render();
20
- }
21
- end(err) {
22
- this.updateRenderer.end(err);
23
- if (typeof err === 'undefined') {
24
- logUpdate.clear();
25
- return;
26
- }
27
- // persist the output
28
- logUpdate.done();
29
- // show errors
30
- if (err) {
31
- const errorCount = err.errors ? err.errors.length : 0;
32
- if (errorCount > 0) {
33
- const count = (0, indentString_js_1.indentString)(chalk_1.default.red.bold(`Found ${errorCount} error${errorCount > 1 ? 's' : ''}`), 1);
34
- const details = err.errors
35
- .map(error => {
36
- (0, debugging_js_1.debugLog)(`[CLI] Exited with an error`, error);
37
- return { msg: (0, plugin_helpers_1.isDetailedError)(error) ? error.details : null, rawError: error };
38
- })
39
- .map(({ msg, rawError }, i) => {
40
- const source = err.errors[i].source;
41
- msg = msg ? chalk_1.default.gray((0, indentString_js_1.indentString)((0, common_tags_1.stripIndent)(`${msg}`), 4)) : null;
42
- const stack = rawError.stack ? chalk_1.default.gray((0, indentString_js_1.indentString)((0, common_tags_1.stripIndent)(rawError.stack), 4)) : null;
43
- if (source) {
44
- const sourceOfError = typeof source === 'string' ? source : source.name;
45
- const title = (0, indentString_js_1.indentString)(`${log_symbols_1.default.error} ${sourceOfError}`, 2);
46
- return [title, msg, stack, stack].filter(Boolean).join('\n');
47
- }
48
- return [msg, stack].filter(Boolean).join('\n');
49
- })
50
- .join('\n\n');
51
- logUpdate.emit(['', count, details, ''].join('\n\n'));
52
- }
53
- else {
54
- const details = err.details ? err.details : '';
55
- logUpdate.emit(`${chalk_1.default.red.bold(`${(0, indentString_js_1.indentString)(err.message, 2)}`)}\n${details}\n${chalk_1.default.grey(err.stack)}`);
56
- }
57
- }
58
- logUpdate.done();
59
- (0, debugging_js_1.printLogs)();
60
- }
61
- }
62
- exports.Renderer = Renderer;
63
- const render = tasks => {
64
- for (const task of tasks) {
65
- task.subscribe(event => {
66
- if (event.type === 'SUBTASKS') {
67
- render(task.subtasks);
68
- return;
69
- }
70
- if (event.type === 'DATA') {
71
- logUpdate.emit(chalk_1.default.dim(`${event.data}`));
72
- }
73
- logUpdate.done();
74
- }, err => {
75
- logUpdate.emit(err);
76
- logUpdate.done();
77
- });
78
- }
79
- };
80
- class ErrorRenderer {
81
- constructor(tasks, _options) {
82
- this.tasks = tasks;
83
- }
84
- render() {
85
- render(this.tasks);
86
- }
87
- static get nonTTY() {
88
- return true;
89
- }
90
- end() { }
91
- }
92
- exports.ErrorRenderer = ErrorRenderer;
93
- class LogUpdate {
94
- constructor() {
95
- this.stream = process.stdout;
96
- // state
97
- this.previousLineCount = 0;
98
- this.previousOutput = '';
99
- this.previousWidth = this.getWidth();
100
- }
101
- emit(...args) {
102
- let output = args.join(' ') + '\n';
103
- const width = this.getWidth();
104
- if (output === this.previousOutput && this.previousWidth === width) {
105
- return;
106
- }
107
- this.previousOutput = output;
108
- this.previousWidth = width;
109
- output = (0, wrap_ansi_1.default)(output, width, {
110
- trim: false,
111
- hard: true,
112
- wordWrap: false,
113
- });
114
- this.stream.write(ansi_escapes_1.default.eraseLines(this.previousLineCount) + output);
115
- this.previousLineCount = output.split('\n').length;
116
- }
117
- clear() {
118
- this.stream.write(ansi_escapes_1.default.eraseLines(this.previousLineCount));
119
- this.previousOutput = '';
120
- this.previousWidth = this.getWidth();
121
- this.previousLineCount = 0;
122
- }
123
- done() {
124
- this.previousOutput = '';
125
- this.previousWidth = this.getWidth();
126
- this.previousLineCount = 0;
127
- }
128
- getWidth() {
129
- const { columns } = this.stream;
130
- if (!columns) {
131
- return 80;
132
- }
133
- return columns;
134
- }
135
- }
136
- const logUpdate = new LogUpdate();
@@ -1,33 +0,0 @@
1
- /**
2
- Indent each line in a string.
3
- @param string - The string to indent.
4
- @param count - How many times you want `options.indent` repeated. Default: `1`.
5
- @example
6
- ```
7
- import indentString from 'indent-string';
8
- indentString('Unicorns\nRainbows', 4);
9
- //=> ' Unicorns\n Rainbows'
10
- indentString('Unicorns\nRainbows', 4, {indent: '♥'});
11
- //=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows'
12
- ```
13
- */
14
- export function indentString(string, count = 1, options = {}) {
15
- const { indent = ' ', includeEmptyLines = false } = options;
16
- if (typeof string !== 'string') {
17
- throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);
18
- }
19
- if (typeof count !== 'number') {
20
- throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);
21
- }
22
- if (count < 0) {
23
- throw new RangeError(`Expected \`count\` to be at least 0, got \`${count}\``);
24
- }
25
- if (typeof indent !== 'string') {
26
- throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);
27
- }
28
- if (count === 0) {
29
- return string;
30
- }
31
- const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
32
- return string.replace(regex, indent.repeat(count));
33
- }
@@ -1,130 +0,0 @@
1
- import chalk from 'chalk';
2
- import { indentString } from './indentString.js';
3
- import logSymbol from 'log-symbols';
4
- import ansiEscapes from 'ansi-escapes';
5
- import wrapAnsi from 'wrap-ansi';
6
- import { stripIndent } from 'common-tags';
7
- import { isDetailedError } from '@graphql-codegen/plugin-helpers';
8
- import { debugLog, printLogs } from './debugging.js';
9
- import UpdateRenderer from 'listr-update-renderer';
10
- export class Renderer {
11
- constructor(tasks, options) {
12
- this.updateRenderer = new UpdateRenderer(tasks, options);
13
- }
14
- render() {
15
- return this.updateRenderer.render();
16
- }
17
- end(err) {
18
- this.updateRenderer.end(err);
19
- if (typeof err === 'undefined') {
20
- logUpdate.clear();
21
- return;
22
- }
23
- // persist the output
24
- logUpdate.done();
25
- // show errors
26
- if (err) {
27
- const errorCount = err.errors ? err.errors.length : 0;
28
- if (errorCount > 0) {
29
- const count = indentString(chalk.red.bold(`Found ${errorCount} error${errorCount > 1 ? 's' : ''}`), 1);
30
- const details = err.errors
31
- .map(error => {
32
- debugLog(`[CLI] Exited with an error`, error);
33
- return { msg: isDetailedError(error) ? error.details : null, rawError: error };
34
- })
35
- .map(({ msg, rawError }, i) => {
36
- const source = err.errors[i].source;
37
- msg = msg ? chalk.gray(indentString(stripIndent(`${msg}`), 4)) : null;
38
- const stack = rawError.stack ? chalk.gray(indentString(stripIndent(rawError.stack), 4)) : null;
39
- if (source) {
40
- const sourceOfError = typeof source === 'string' ? source : source.name;
41
- const title = indentString(`${logSymbol.error} ${sourceOfError}`, 2);
42
- return [title, msg, stack, stack].filter(Boolean).join('\n');
43
- }
44
- return [msg, stack].filter(Boolean).join('\n');
45
- })
46
- .join('\n\n');
47
- logUpdate.emit(['', count, details, ''].join('\n\n'));
48
- }
49
- else {
50
- const details = err.details ? err.details : '';
51
- logUpdate.emit(`${chalk.red.bold(`${indentString(err.message, 2)}`)}\n${details}\n${chalk.grey(err.stack)}`);
52
- }
53
- }
54
- logUpdate.done();
55
- printLogs();
56
- }
57
- }
58
- const render = tasks => {
59
- for (const task of tasks) {
60
- task.subscribe(event => {
61
- if (event.type === 'SUBTASKS') {
62
- render(task.subtasks);
63
- return;
64
- }
65
- if (event.type === 'DATA') {
66
- logUpdate.emit(chalk.dim(`${event.data}`));
67
- }
68
- logUpdate.done();
69
- }, err => {
70
- logUpdate.emit(err);
71
- logUpdate.done();
72
- });
73
- }
74
- };
75
- export class ErrorRenderer {
76
- constructor(tasks, _options) {
77
- this.tasks = tasks;
78
- }
79
- render() {
80
- render(this.tasks);
81
- }
82
- static get nonTTY() {
83
- return true;
84
- }
85
- end() { }
86
- }
87
- class LogUpdate {
88
- constructor() {
89
- this.stream = process.stdout;
90
- // state
91
- this.previousLineCount = 0;
92
- this.previousOutput = '';
93
- this.previousWidth = this.getWidth();
94
- }
95
- emit(...args) {
96
- let output = args.join(' ') + '\n';
97
- const width = this.getWidth();
98
- if (output === this.previousOutput && this.previousWidth === width) {
99
- return;
100
- }
101
- this.previousOutput = output;
102
- this.previousWidth = width;
103
- output = wrapAnsi(output, width, {
104
- trim: false,
105
- hard: true,
106
- wordWrap: false,
107
- });
108
- this.stream.write(ansiEscapes.eraseLines(this.previousLineCount) + output);
109
- this.previousLineCount = output.split('\n').length;
110
- }
111
- clear() {
112
- this.stream.write(ansiEscapes.eraseLines(this.previousLineCount));
113
- this.previousOutput = '';
114
- this.previousWidth = this.getWidth();
115
- this.previousLineCount = 0;
116
- }
117
- done() {
118
- this.previousOutput = '';
119
- this.previousWidth = this.getWidth();
120
- this.previousLineCount = 0;
121
- }
122
- getWidth() {
123
- const { columns } = this.stream;
124
- if (!columns) {
125
- return 80;
126
- }
127
- return columns;
128
- }
129
- }
130
- const logUpdate = new LogUpdate();
@@ -1,26 +0,0 @@
1
- export interface IndentStringOptions {
2
- /**
3
- The string to use for the indent.
4
- @default ' '
5
- */
6
- readonly indent?: string;
7
- /**
8
- Also indent empty lines.
9
- @default false
10
- */
11
- readonly includeEmptyLines?: boolean;
12
- }
13
- /**
14
- Indent each line in a string.
15
- @param string - The string to indent.
16
- @param count - How many times you want `options.indent` repeated. Default: `1`.
17
- @example
18
- ```
19
- import indentString from 'indent-string';
20
- indentString('Unicorns\nRainbows', 4);
21
- //=> ' Unicorns\n Rainbows'
22
- indentString('Unicorns\nRainbows', 4, {indent: '♥'});
23
- //=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows'
24
- ```
25
- */
26
- export declare function indentString(string: string, count?: number, options?: IndentStringOptions): string;
@@ -1,18 +0,0 @@
1
- import { ListrTask } from 'listr';
2
- import { DetailedError } from '@graphql-codegen/plugin-helpers';
3
- export declare class Renderer {
4
- private updateRenderer;
5
- constructor(tasks: ListrTask, options: any);
6
- render(): any;
7
- end(err: Error & {
8
- errors?: (Error | DetailedError)[];
9
- details?: string;
10
- }): void;
11
- }
12
- export declare class ErrorRenderer {
13
- private tasks;
14
- constructor(tasks: any, _options: any);
15
- render(): void;
16
- static get nonTTY(): boolean;
17
- end(): void;
18
- }