@graphql-codegen/cli 6.2.1 → 7.0.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 (42) hide show
  1. package/README.md +2 -1
  2. package/cjs/cli.js +17 -7
  3. package/cjs/codegen.js +80 -27
  4. package/cjs/config.js +30 -17
  5. package/cjs/documentTransforms.js +5 -1
  6. package/cjs/generate-and-save.js +1 -1
  7. package/cjs/graphql-config.js +1 -1
  8. package/cjs/init/helpers.js +8 -4
  9. package/cjs/init/index.js +1 -1
  10. package/cjs/init/plugins.js +3 -1
  11. package/cjs/init/questions.js +10 -3
  12. package/cjs/init/targets.js +1 -1
  13. package/cjs/load.js +6 -3
  14. package/cjs/utils/patterns.js +17 -6
  15. package/cjs/utils/watcher.js +12 -7
  16. package/esm/codegen.js +80 -27
  17. package/esm/config.js +31 -18
  18. package/esm/documentTransforms.js +5 -1
  19. package/esm/generate-and-save.js +1 -1
  20. package/esm/graphql-config.js +1 -1
  21. package/esm/init/helpers.js +8 -4
  22. package/esm/init/index.js +1 -1
  23. package/esm/init/plugins.js +3 -1
  24. package/esm/init/questions.js +11 -4
  25. package/esm/init/targets.js +1 -1
  26. package/esm/load.js +6 -3
  27. package/esm/utils/file-system.js +1 -1
  28. package/esm/utils/patterns.js +17 -6
  29. package/esm/utils/watcher.js +12 -7
  30. package/package.json +18 -17
  31. package/typings/config.d.cts +3 -2
  32. package/typings/config.d.ts +3 -2
  33. package/typings/init/questions.d.cts +1 -1
  34. package/typings/init/questions.d.ts +1 -1
  35. package/typings/init/targets.d.cts +1 -1
  36. package/typings/init/targets.d.ts +1 -1
  37. package/typings/load.d.cts +3 -2
  38. package/typings/load.d.ts +3 -2
  39. package/cjs/utils/abort-controller-polyfill.js +0 -99
  40. package/esm/utils/abort-controller-polyfill.js +0 -96
  41. package/typings/utils/abort-controller-polyfill.d.cts +0 -5
  42. package/typings/utils/abort-controller-polyfill.d.ts +0 -5
package/esm/codegen.js CHANGED
@@ -2,17 +2,17 @@ import fs from 'fs';
2
2
  import { createRequire } from 'module';
3
3
  import { cpus } from 'os';
4
4
  import path from 'path';
5
+ import { buildASTSchema, GraphQLError, isSchema } from 'graphql';
6
+ import { Listr } from 'listr2';
5
7
  import { codegen } from '@graphql-codegen/core';
6
8
  import { getCachedDocumentNodeFromSchema, normalizeConfig, normalizeImportExtension, normalizeInstanceOrArray, normalizeOutputParam, } from '@graphql-codegen/plugin-helpers';
7
9
  import { NoTypeDefinitionsFound } from '@graphql-tools/load';
8
- import { buildASTSchema, GraphQLError, isSchema } from 'graphql';
9
10
  import { mergeTypeDefs } from '@graphql-tools/merge';
10
- import { Listr } from 'listr2';
11
11
  import { ensureContext } from './config.js';
12
+ import { getDocumentTransform } from './documentTransforms.js';
12
13
  import { getPluginByName } from './plugins.js';
13
14
  import { getPresetByName } from './presets.js';
14
15
  import { debugLog, printLogs } from './utils/debugging.js';
15
- import { getDocumentTransform } from './documentTransforms.js';
16
16
  /**
17
17
  * Poor mans ESM detection.
18
18
  * Looking at this and you have a better method?
@@ -56,6 +56,7 @@ export async function executeCodegen(input) {
56
56
  let rootConfig = {};
57
57
  let rootSchemas;
58
58
  let rootDocuments;
59
+ let rootExternalDocuments;
59
60
  const generates = {};
60
61
  const cache = createCache();
61
62
  // We need a simple string to uniqually identify the provided GraphQLSchema objects for the above cache.
@@ -97,6 +98,8 @@ export async function executeCodegen(input) {
97
98
  rootSchemas = normalizeInstanceOrArray(config.schema);
98
99
  /* Normalize root "documents" field */
99
100
  rootDocuments = normalizeInstanceOrArray(config.documents);
101
+ /* Normalize root "externalDocuments" field */
102
+ rootExternalDocuments = normalizeInstanceOrArray(config.externalDocuments);
100
103
  /* Normalize "generators" field */
101
104
  const generateKeys = Object.keys(config.generates || {});
102
105
  if (generateKeys.length === 0) {
@@ -169,9 +172,10 @@ export async function executeCodegen(input) {
169
172
  let outputSchemaAst;
170
173
  let outputSchema;
171
174
  const outputFileTemplateConfig = outputConfig.config || {};
172
- let outputDocuments = [];
175
+ const outputDocuments = [];
173
176
  const outputSpecificSchemas = normalizeInstanceOrArray(outputConfig.schema);
174
177
  let outputSpecificDocuments = normalizeInstanceOrArray(outputConfig.documents);
178
+ let outputSpecificExternalDocuments = normalizeInstanceOrArray(outputConfig.externalDocuments);
175
179
  const preset = hasPreset
176
180
  ? typeof outputConfig.preset === 'string'
177
181
  ? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
@@ -179,6 +183,7 @@ export async function executeCodegen(input) {
179
183
  : null;
180
184
  if (preset?.prepareDocuments) {
181
185
  outputSpecificDocuments = await preset.prepareDocuments(filename, outputSpecificDocuments);
186
+ outputSpecificExternalDocuments = await preset.prepareDocuments(filename, outputSpecificExternalDocuments);
182
187
  }
183
188
  return subTask.newListr([
184
189
  {
@@ -187,7 +192,10 @@ export async function executeCodegen(input) {
187
192
  debugLog(`[CLI] Loading Schemas`);
188
193
  const schemaPointerMap = {};
189
194
  const parsedSchemas = [];
190
- const allSchemaDenormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
195
+ const allSchemaDenormalizedPointers = [
196
+ ...rootSchemas,
197
+ ...outputSpecificSchemas,
198
+ ];
191
199
  for (const denormalizedPtr of allSchemaDenormalizedPointers) {
192
200
  if (isSchema(denormalizedPtr)) {
193
201
  parsedSchemas.push(denormalizedPtr);
@@ -199,7 +207,8 @@ export async function executeCodegen(input) {
199
207
  Object.assign(schemaPointerMap, denormalizedPtr);
200
208
  }
201
209
  }
202
- const hash = JSON.stringify(schemaPointerMap) + parsedSchemas.map(getJsObjectId).join(',');
210
+ const hash = JSON.stringify(schemaPointerMap) +
211
+ parsedSchemas.map(getJsObjectId).join(',');
203
212
  const result = await cache('schema', hash, async () => {
204
213
  // collect parsed schemas
205
214
  const schemasToMerge = [...parsedSchemas];
@@ -225,34 +234,74 @@ export async function executeCodegen(input) {
225
234
  title: 'Load GraphQL documents',
226
235
  task: wrapTask(async () => {
227
236
  debugLog(`[CLI] Loading Documents`);
228
- const documentPointerMap = {};
229
- const allDocumentsDenormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
230
- for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
231
- if (typeof denormalizedPtr === 'string') {
232
- documentPointerMap[denormalizedPtr] = {};
233
- }
234
- else if (typeof denormalizedPtr === 'object') {
235
- Object.assign(documentPointerMap, denormalizedPtr);
237
+ const populateDocumentPointerMap = (allDocumentsDenormalizedPointers) => {
238
+ const pointer = {};
239
+ for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
240
+ if (typeof denormalizedPtr === 'string') {
241
+ pointer[denormalizedPtr] = {};
242
+ }
243
+ else if (typeof denormalizedPtr === 'object') {
244
+ Object.assign(pointer, denormalizedPtr);
245
+ }
236
246
  }
237
- }
247
+ return pointer;
248
+ };
249
+ const allDocumentsDenormalizedPointers = [
250
+ ...rootDocuments,
251
+ ...outputSpecificDocuments,
252
+ ];
253
+ const documentPointerMap = populateDocumentPointerMap(allDocumentsDenormalizedPointers);
238
254
  const hash = JSON.stringify(documentPointerMap);
239
- const result = await cache('documents', hash, async () => {
255
+ const outputDocumentsStandard = await cache('documents', hash, async () => {
240
256
  try {
241
- const documents = await context.loadDocuments(documentPointerMap);
242
- return {
243
- documents,
244
- };
257
+ const documents = await context.loadDocuments(documentPointerMap, 'standard');
258
+ return documents;
245
259
  }
246
260
  catch (error) {
247
- if (error instanceof NoTypeDefinitionsFound && config.ignoreNoDocuments) {
248
- return {
249
- documents: [],
250
- };
261
+ if (error instanceof NoTypeDefinitionsFound &&
262
+ config.ignoreNoDocuments) {
263
+ return [];
251
264
  }
252
265
  throw error;
253
266
  }
254
267
  });
255
- outputDocuments = result.documents;
268
+ const allExternalDocumentsDenormalizedPointers = [
269
+ ...rootExternalDocuments,
270
+ ...outputSpecificExternalDocuments,
271
+ ];
272
+ const externalDocumentsPointerMap = populateDocumentPointerMap(allExternalDocumentsDenormalizedPointers);
273
+ const externalDocumentHash = JSON.stringify(externalDocumentsPointerMap);
274
+ const outputExternalDocuments = await cache('documents', externalDocumentHash, async () => {
275
+ try {
276
+ const documents = await context.loadDocuments(externalDocumentsPointerMap, 'external');
277
+ return documents;
278
+ }
279
+ catch (error) {
280
+ if (error instanceof NoTypeDefinitionsFound &&
281
+ config.ignoreNoDocuments) {
282
+ return [];
283
+ }
284
+ throw error;
285
+ }
286
+ });
287
+ /**
288
+ * Merging `standard` and `external` documents here,
289
+ * so they can be processed the same way,
290
+ * before passed into presets and plugins
291
+ */
292
+ const processedFile = {};
293
+ const mergedDocuments = [
294
+ ...outputDocumentsStandard,
295
+ ...outputExternalDocuments,
296
+ ];
297
+ for (const file of mergedDocuments) {
298
+ const fileIdentifier = (file.location || '') + (file.hash || '');
299
+ if (processedFile[fileIdentifier]) {
300
+ continue;
301
+ }
302
+ outputDocuments.push(file);
303
+ processedFile[fileIdentifier] = true;
304
+ }
256
305
  }, filename, `Load GraphQL documents: ${filename}`, ctx),
257
306
  },
258
307
  {
@@ -351,7 +400,9 @@ export async function executeCodegen(input) {
351
400
  exitOnError: false,
352
401
  };
353
402
  });
354
- return task.newListr(generateTasks, { concurrent: cpus().length || 1 });
403
+ return task.newListr(generateTasks, {
404
+ concurrent: cpus().length || 1,
405
+ });
355
406
  },
356
407
  },
357
408
  ], {
@@ -378,7 +429,9 @@ export async function executeCodegen(input) {
378
429
  const errors = executedContext.errors.map(subErr => subErr.message || subErr.toString());
379
430
  error = new AggregateError(executedContext.errors, String(errors.join('\n\n')));
380
431
  // Best-effort to all stack traces for debugging
381
- error.stack = `${error.stack}\n\n${executedContext.errors.map(subErr => subErr.stack).join('\n\n')}`;
432
+ error.stack = `${error.stack}\n\n${executedContext.errors
433
+ .map(subErr => subErr.stack)
434
+ .join('\n\n')}`;
382
435
  }
383
436
  return { result, error };
384
437
  }
package/esm/config.js CHANGED
@@ -2,15 +2,15 @@ import { createHash } from 'crypto';
2
2
  import { promises } from 'fs';
3
3
  import { createRequire } from 'module';
4
4
  import { resolve } from 'path';
5
- import { createNoopProfiler, createProfiler, getCachedDocumentNodeFromSchema, } from '@graphql-codegen/plugin-helpers';
6
5
  import { cosmiconfig, defaultLoaders } from 'cosmiconfig';
7
- import { createJiti } from 'jiti';
8
6
  import { print } from 'graphql';
7
+ import { createJiti } from 'jiti';
9
8
  import { env } from 'string-env-interpolation';
10
9
  import yaml from 'yaml';
11
10
  import yargs from 'yargs';
11
+ import { createNoopProfiler, createProfiler, getCachedDocumentNodeFromSchema, } from '@graphql-codegen/plugin-helpers';
12
12
  import { findAndLoadGraphQLConfig } from './graphql-config.js';
13
- import { defaultDocumentsLoadOptions, defaultSchemaLoadOptions, loadDocuments, loadSchema } from './load.js';
13
+ import { defaultDocumentsLoadOptions, defaultSchemaLoadOptions, loadDocuments, loadSchema, } from './load.js';
14
14
  const { lstat } = promises;
15
15
  export function generateSearchPlaces(moduleName) {
16
16
  const extensions = ['json', 'yaml', 'yml', 'js', 'ts', 'config.js'];
@@ -254,7 +254,7 @@ export class CodegenContext {
254
254
  this._config = config;
255
255
  this._graphqlConfig = graphqlConfig;
256
256
  this.filepath = this._graphqlConfig ? this._graphqlConfig.filepath : filepath;
257
- this.cwd = this._graphqlConfig ? this._graphqlConfig.dirpath : process.cwd();
257
+ this.cwd = this._graphqlConfig ? this._graphqlConfig.dirpath : config?.cwd || process.cwd();
258
258
  this.profiler = createNoopProfiler();
259
259
  }
260
260
  useProject(name) {
@@ -275,10 +275,18 @@ export class CodegenContext {
275
275
  this.config = { ...this._config, pluginContext: this._pluginContext };
276
276
  }
277
277
  }
278
- return {
278
+ const config = {
279
+ noSilentErrors: true, // When a `documents` pattern matches multiple files e.g. `*` exists in filename like `src/something.*.ts`, and some files fail but some pass syntax error check, the failed files will silently fail if `noSilentErrors: false`. So, `noSilentErrors: true` is turned on by default to help users detect errors faster.
279
280
  ...extraConfig,
280
281
  ...this.config,
281
282
  };
283
+ if (this._graphqlConfig) {
284
+ return config;
285
+ }
286
+ return {
287
+ ...config,
288
+ cwd: this.cwd,
289
+ };
282
290
  }
283
291
  updateConfig(config) {
284
292
  this.config = {
@@ -312,13 +320,15 @@ export class CodegenContext {
312
320
  }
313
321
  return addHashToSchema(loadSchema(pointer, config));
314
322
  }
315
- async loadDocuments(pointer) {
323
+ async loadDocuments(pointer, type) {
316
324
  const config = this.getConfig(defaultDocumentsLoadOptions);
317
325
  if (this._graphqlConfig) {
318
326
  // TODO: pointer won't work here
319
- return addHashToDocumentFiles(this._graphqlConfig.getProject(this._project).loadDocuments(pointer, { ...config, ...config.config }));
327
+ return addMetadataToSources(this._graphqlConfig
328
+ .getProject(this._project)
329
+ .loadDocuments(pointer, { ...config, ...config.config }), type);
320
330
  }
321
- return addHashToDocumentFiles(loadDocuments(pointer, config));
331
+ return addMetadataToSources(loadDocuments(pointer, config), type);
322
332
  }
323
333
  }
324
334
  export function ensureContext(input) {
@@ -340,18 +350,21 @@ function addHashToSchema(schemaPromise) {
340
350
  return schema;
341
351
  });
342
352
  }
343
- function hashDocument(doc) {
344
- if (doc.rawSDL) {
345
- return hashContent(doc.rawSDL);
346
- }
347
- if (doc.document) {
348
- return hashContent(print(doc.document));
353
+ async function addMetadataToSources(documentFilesPromise, type) {
354
+ function hashDocument(doc) {
355
+ if (doc.rawSDL) {
356
+ return hashContent(doc.rawSDL);
357
+ }
358
+ if (doc.document) {
359
+ return hashContent(print(doc.document));
360
+ }
361
+ return null;
349
362
  }
350
- return null;
351
- }
352
- function addHashToDocumentFiles(documentFilesPromise) {
353
- return documentFilesPromise.then(documentFiles => documentFiles.map(doc => {
363
+ return documentFilesPromise.then(documentFiles =>
364
+ // Note: `doc` here is technically `Source`, but by the end of the funciton it's `Types.DocumentFile`. This re-declaration makes TypeScript happy.
365
+ documentFiles.map((doc) => {
354
366
  doc.hash = hashDocument(doc);
367
+ doc.type = type;
355
368
  return doc;
356
369
  }));
357
370
  }
@@ -10,7 +10,11 @@ export async function getDocumentTransform(documentTransform, loader, defaultNam
10
10
  if (isTransformFileConfig(documentTransform)) {
11
11
  const name = Object.keys(documentTransform)[0];
12
12
  const transformObject = await getDocumentTransformByName(name, loader);
13
- return { name, transformObject, config: Object.values(documentTransform)[0] };
13
+ return {
14
+ name,
15
+ transformObject,
16
+ config: Object.values(documentTransform)[0],
17
+ };
14
18
  }
15
19
  throw new Error(`
16
20
  An unknown format document transform: '${defaultName}'.
@@ -6,8 +6,8 @@ import { ensureContext } from './config.js';
6
6
  import { lifecycleHooks } from './hooks.js';
7
7
  import { debugLog } from './utils/debugging.js';
8
8
  import { mkdirp, readFile, unlinkFile, writeFile } from './utils/file-system.js';
9
- import { createWatcher } from './utils/watcher.js';
10
9
  import { getLogger } from './utils/logger.js';
10
+ import { createWatcher } from './utils/watcher.js';
11
11
  const hash = (content) => createHash('sha1').update(content).digest('base64');
12
12
  export async function generate(input, saveToFile = true) {
13
13
  const context = ensureContext(input);
@@ -1,8 +1,8 @@
1
+ import { loadConfig } from 'graphql-config';
1
2
  import { ApolloEngineLoader } from '@graphql-tools/apollo-engine-loader';
2
3
  import { CodeFileLoader } from '@graphql-tools/code-file-loader';
3
4
  import { GitLoader } from '@graphql-tools/git-loader';
4
5
  import { GithubLoader } from '@graphql-tools/github-loader';
5
- import { loadConfig } from 'graphql-config';
6
6
  export const CodegenExtension = (api) => {
7
7
  // Schema
8
8
  api.loaders.schema.register(new CodeFileLoader({
@@ -1,20 +1,24 @@
1
1
  import { readFileSync, writeFileSync } from 'fs';
2
2
  import { relative, resolve } from 'path';
3
+ import chalk from 'chalk';
4
+ import detectIndent from 'detect-indent';
3
5
  import generate from '@babel/generator';
4
6
  import template from '@babel/template';
5
7
  import * as t from '@babel/types';
6
- import chalk from 'chalk';
7
- import detectIndent from 'detect-indent';
8
8
  import { getLatestVersion } from '../utils/get-latest-version.js';
9
9
  import { Tags } from './types.js';
10
10
  function jsObjectToBabelObjectExpression(obj) {
11
11
  const objExp = t.objectExpression([]);
12
12
  for (const [key, val] of Object.entries(obj)) {
13
13
  if (Array.isArray(val)) {
14
- objExp.properties.push(t.objectProperty(/^[a-zA-Z0-9]+$/.test(key) ? t.identifier(key) : t.stringLiteral(key), t.arrayExpression(val.map(v => (typeof v === 'object' ? jsObjectToBabelObjectExpression(v) : t.valueToNode(v))))));
14
+ objExp.properties.push(t.objectProperty(/^[a-zA-Z0-9]+$/.test(key) ? t.identifier(key) : t.stringLiteral(key), t.arrayExpression(val.map(v => typeof v === 'object'
15
+ ? jsObjectToBabelObjectExpression(v)
16
+ : t.valueToNode(v)))));
15
17
  }
16
18
  else {
17
- objExp.properties.push(t.objectProperty(/^[a-zA-Z0-9]+$/.test(key) ? t.identifier(key) : t.stringLiteral(key), typeof val === 'object' ? jsObjectToBabelObjectExpression(val) : t.valueToNode(val)));
19
+ objExp.properties.push(t.objectProperty(/^[a-zA-Z0-9]+$/.test(key) ? t.identifier(key) : t.stringLiteral(key), typeof val === 'object'
20
+ ? jsObjectToBabelObjectExpression(val)
21
+ : t.valueToNode(val)));
18
22
  }
19
23
  }
20
24
  return objExp;
package/esm/init/index.js CHANGED
@@ -11,7 +11,7 @@ export async function init() {
11
11
  Welcome to ${bold('GraphQL Code Generator')}!
12
12
  Answer few questions and we will setup everything for you.
13
13
  `);
14
- const possibleTargets = await guessTargets();
14
+ const possibleTargets = guessTargets();
15
15
  const answers = await getAnswers(possibleTargets);
16
16
  // define config
17
17
  const config = {
@@ -7,7 +7,9 @@ export const plugins = [
7
7
  value: 'typescript',
8
8
  pathInRepo: 'typescript/typescript',
9
9
  available: hasTag(Tags.typescript),
10
- shouldBeSelected: tags => oneOf(tags, Tags.angular, Tags.stencil) || allOf(tags, Tags.typescript, Tags.react) || noneOf(tags, Tags.flow),
10
+ shouldBeSelected: tags => oneOf(tags, Tags.angular, Tags.stencil) ||
11
+ allOf(tags, Tags.typescript, Tags.react) ||
12
+ noneOf(tags, Tags.flow),
11
13
  defaultExtension: '.ts',
12
14
  },
13
15
  {
@@ -1,4 +1,4 @@
1
- import { checkbox, input, select, confirm } from '@inquirer/prompts';
1
+ import { checkbox, confirm, input, select } from '@inquirer/prompts';
2
2
  import { grey } from './helpers.js';
3
3
  import { plugins } from './plugins.js';
4
4
  import { Tags } from './types.js';
@@ -16,7 +16,9 @@ export async function getAnswers(possibleTargets) {
16
16
  validate: str => str.length > 0,
17
17
  });
18
18
  let documents;
19
- if (targets.includes(Tags.client) || targets.includes(Tags.angular) || targets.includes(Tags.stencil))
19
+ if (targets.includes(Tags.client) ||
20
+ targets.includes(Tags.angular) ||
21
+ targets.includes(Tags.stencil))
20
22
  documents = await input({
21
23
  message: 'Where are your operations and fragments?:',
22
24
  default: getDocumentsDefaultValue(targets),
@@ -41,7 +43,9 @@ export async function getAnswers(possibleTargets) {
41
43
  });
42
44
  const config = await input({
43
45
  message: 'How to name the config file?',
44
- default: (() => targets.includes(Tags.client) || targets.includes(Tags.typescript) || targets.includes(Tags.angular)
46
+ default: (() => targets.includes(Tags.client) ||
47
+ targets.includes(Tags.typescript) ||
48
+ targets.includes(Tags.angular)
45
49
  ? 'codegen.ts'
46
50
  : 'codegen.yml')(),
47
51
  validate: str => {
@@ -131,7 +135,10 @@ export function getApplicationTypeChoices(possibleTargets) {
131
135
  name: 'Application built with other framework or vanilla JS',
132
136
  key: 'client',
133
137
  value: [Tags.typescript, Tags.flow],
134
- checked: possibleTargets.Browser && !possibleTargets.Angular && !possibleTargets.React && !possibleTargets.Stencil,
138
+ checked: possibleTargets.Browser &&
139
+ !possibleTargets.Angular &&
140
+ !possibleTargets.React &&
141
+ !possibleTargets.Stencil,
135
142
  },
136
143
  ];
137
144
  }
@@ -1,7 +1,7 @@
1
1
  import { readFileSync } from 'fs';
2
2
  import { resolve } from 'path';
3
3
  import { Tags } from './types.js';
4
- export async function guessTargets() {
4
+ export function guessTargets() {
5
5
  const pkg = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf8'));
6
6
  const dependencies = Object.keys({
7
7
  ...pkg.dependencies,
package/esm/load.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { extname, join } from 'path';
2
+ import { GraphQLError } from 'graphql';
2
3
  import { ApolloEngineLoader } from '@graphql-tools/apollo-engine-loader';
3
4
  import { CodeFileLoader } from '@graphql-tools/code-file-loader';
4
5
  import { GitLoader } from '@graphql-tools/git-loader';
@@ -7,7 +8,6 @@ import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';
7
8
  import { JsonFileLoader } from '@graphql-tools/json-file-loader';
8
9
  import { loadDocuments as loadDocumentsToolkit, loadSchema as loadSchemaToolkit, NoTypeDefinitionsFound, } from '@graphql-tools/load';
9
10
  import { UrlLoader } from '@graphql-tools/url-loader';
10
- import { GraphQLError } from 'graphql';
11
11
  export const defaultSchemaLoadOptions = {
12
12
  assumeValidSDL: true,
13
13
  sort: true,
@@ -68,7 +68,7 @@ export async function loadDocuments(documentPointers, config) {
68
68
  // we omit paths that don't resolve to a specific file
69
69
  continue;
70
70
  }
71
- ignore.push(join(process.cwd(), generatePath));
71
+ ignore.push(join(config.cwd || process.cwd(), generatePath));
72
72
  }
73
73
  try {
74
74
  const loadedFromToolkit = await loadDocumentsToolkit(documentPointers, {
@@ -86,7 +86,10 @@ export async function loadDocuments(documentPointers, config) {
86
86
  throw error;
87
87
  }
88
88
  // For other errors, we need to add an error message with documentPointers, so it's better for DevX
89
- throw new Error([`Failed to load documents from ${Object.keys(documentPointers).join(',')}:`, printError(error)].join('\n'));
89
+ throw new Error([
90
+ `Failed to load documents from ${Object.keys(documentPointers).join(',')}:`,
91
+ printError(error),
92
+ ].join('\n'));
90
93
  }
91
94
  }
92
95
  const printError = (error) => {
@@ -1,4 +1,4 @@
1
- import { promises, unlink as fsUnlink } from 'fs';
1
+ import { unlink as fsUnlink, promises } from 'fs';
2
2
  const { access: fsAccess, writeFile: fsWriteFile, readFile: fsReadFile, mkdir } = promises;
3
3
  export function access(...args) {
4
4
  return fsAccess(...args);
@@ -1,8 +1,8 @@
1
1
  import { isAbsolute, relative } from 'path';
2
- import { isValidPath } from '@graphql-tools/utils';
3
- import { normalizeInstanceOrArray } from '@graphql-codegen/plugin-helpers';
4
2
  import isGlob from 'is-glob';
5
3
  import mm from 'micromatch';
4
+ import { normalizeInstanceOrArray } from '@graphql-codegen/plugin-helpers';
5
+ import { isValidPath } from '@graphql-tools/utils';
6
6
  import { isURL } from './helpers.js';
7
7
  /**
8
8
  * Flatten a list of pattern sets to be a list of only the affirmative patterns
@@ -39,7 +39,10 @@ export const makeShouldRebuild = ({ globalPatternSet, localPatternSets, }) => {
39
39
  const localMatchers = localPatternSets.map(localPatternSet => {
40
40
  return (path) => {
41
41
  // Is path negated by any negating watch pattern?
42
- if (matchesAnyNegatedPattern(path, [...globalPatternSet.watch.negated, ...localPatternSet.watch.negated])) {
42
+ if (matchesAnyNegatedPattern(path, [
43
+ ...globalPatternSet.watch.negated,
44
+ ...localPatternSet.watch.negated,
45
+ ])) {
43
46
  // Short circut: negations in watch patterns take priority
44
47
  return false;
45
48
  }
@@ -56,7 +59,10 @@ export const makeShouldRebuild = ({ globalPatternSet, localPatternSets, }) => {
56
59
  ...globalPatternSet.documents.affirmative,
57
60
  ...localPatternSet.documents.affirmative,
58
61
  ]) &&
59
- !matchesAnyNegatedPattern(path, [...globalPatternSet.documents.negated, ...localPatternSet.documents.negated])) {
62
+ !matchesAnyNegatedPattern(path, [
63
+ ...globalPatternSet.documents.negated,
64
+ ...localPatternSet.documents.negated,
65
+ ])) {
60
66
  return true;
61
67
  }
62
68
  // Does path match schemas patterns (without being negated)?
@@ -64,7 +70,10 @@ export const makeShouldRebuild = ({ globalPatternSet, localPatternSets, }) => {
64
70
  ...globalPatternSet.schemas.affirmative,
65
71
  ...localPatternSet.schemas.affirmative,
66
72
  ]) &&
67
- !matchesAnyNegatedPattern(path, [...globalPatternSet.schemas.negated, ...localPatternSet.schemas.negated])) {
73
+ !matchesAnyNegatedPattern(path, [
74
+ ...globalPatternSet.schemas.negated,
75
+ ...localPatternSet.schemas.negated,
76
+ ])) {
68
77
  return true;
69
78
  }
70
79
  // Otherwise, there is no match
@@ -94,7 +103,9 @@ export const makeGlobalPatternSet = (initialContext) => {
94
103
  const config = initialContext.getConfig();
95
104
  return {
96
105
  watch: sortPatterns([
97
- ...(typeof config.watch === 'boolean' ? [] : normalizeInstanceOrArray(config.watch ?? [])),
106
+ ...(typeof config.watch === 'boolean'
107
+ ? []
108
+ : normalizeInstanceOrArray(config.watch ?? [])),
98
109
  relative(process.cwd(), initialContext.filepath),
99
110
  ]),
100
111
  schemas: sortPatterns(makePatternsFromSchemas(normalizeInstanceOrArray(config.schema))),
@@ -1,16 +1,15 @@
1
- import { join, isAbsolute, relative, resolve, sep } from 'path';
2
- import { normalizeOutputParam } from '@graphql-codegen/plugin-helpers';
1
+ import { isAbsolute, join, relative, resolve, sep } from 'path';
3
2
  import debounce from 'debounce';
4
- import mm from 'micromatch';
5
3
  import logSymbols from 'log-symbols';
4
+ import mm from 'micromatch';
5
+ import { normalizeOutputParam } from '@graphql-codegen/plugin-helpers';
6
6
  import { executeCodegen } from '../codegen.js';
7
7
  import { loadContext } from '../config.js';
8
8
  import { lifecycleHooks } from '../hooks.js';
9
- import { access } from './file-system.js';
10
9
  import { debugLog } from './debugging.js';
10
+ import { access } from './file-system.js';
11
11
  import { getLogger } from './logger.js';
12
12
  import { allAffirmativePatternsFromPatternSets, makeGlobalPatternSet, makeLocalPatternSet, makeShouldRebuild, } from './patterns.js';
13
- import { AbortController } from './abort-controller-polyfill.js';
14
13
  function log(msg) {
15
14
  // double spaces to inline the message with Listr
16
15
  getLogger().info(` ${msg}`);
@@ -25,8 +24,14 @@ export const createWatcher = (initialContext, onNext) => {
25
24
  const localPatternSets = Object.keys(config.generates)
26
25
  .map(filename => normalizeOutputParam(config.generates[filename]))
27
26
  .map(conf => makeLocalPatternSet(conf));
28
- const allAffirmativePatterns = allAffirmativePatternsFromPatternSets([globalPatternSet, ...localPatternSets]);
29
- const shouldRebuild = makeShouldRebuild({ globalPatternSet, localPatternSets });
27
+ const allAffirmativePatterns = allAffirmativePatternsFromPatternSets([
28
+ globalPatternSet,
29
+ ...localPatternSets,
30
+ ]);
31
+ const shouldRebuild = makeShouldRebuild({
32
+ globalPatternSet,
33
+ localPatternSets,
34
+ });
30
35
  let watcherSubscription;
31
36
  const runWatcher = async (abortSignal) => {
32
37
  const watchDirectory = await findHighestCommonDirectory(allAffirmativePatterns);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@graphql-codegen/cli",
3
- "version": "6.2.1",
3
+ "version": "7.0.0",
4
4
  "peerDependenciesMeta": {
5
5
  "@parcel/watcher": {
6
6
  "optional": true
@@ -14,9 +14,9 @@
14
14
  "@babel/generator": "^7.18.13",
15
15
  "@babel/template": "^7.18.10",
16
16
  "@babel/types": "^7.18.13",
17
- "@graphql-codegen/client-preset": "^5.2.4",
18
- "@graphql-codegen/core": "^5.0.1",
19
- "@graphql-codegen/plugin-helpers": "^6.2.0",
17
+ "@graphql-codegen/client-preset": "^6.0.0",
18
+ "@graphql-codegen/core": "^6.0.0",
19
+ "@graphql-codegen/plugin-helpers": "^7.0.0",
20
20
  "@graphql-tools/apollo-engine-loader": "^8.0.28",
21
21
  "@graphql-tools/code-file-loader": "^8.1.28",
22
22
  "@graphql-tools/git-loader": "^8.0.32",
@@ -24,28 +24,28 @@
24
24
  "@graphql-tools/graphql-file-loader": "^8.1.11",
25
25
  "@graphql-tools/json-file-loader": "^8.0.26",
26
26
  "@graphql-tools/load": "^8.1.8",
27
- "@graphql-tools/url-loader": "^9.0.6",
28
27
  "@graphql-tools/merge": "^9.0.6",
28
+ "@graphql-tools/url-loader": "^9.0.6",
29
29
  "@graphql-tools/utils": "^11.0.0",
30
- "@inquirer/prompts": "^7.8.2",
30
+ "@inquirer/prompts": "^8.3.2",
31
31
  "@whatwg-node/fetch": "^0.10.0",
32
- "chalk": "^4.1.0",
32
+ "chalk": "^5.6.0",
33
33
  "cosmiconfig": "^9.0.0",
34
- "debounce": "^2.0.0",
35
- "detect-indent": "^6.0.0",
34
+ "debounce": "^3.0.0",
35
+ "detect-indent": "^7.0.0",
36
36
  "graphql-config": "^5.1.6",
37
37
  "is-glob": "^4.0.1",
38
38
  "jiti": "^2.3.0",
39
39
  "json-to-pretty-yaml": "^1.2.2",
40
- "listr2": "^9.0.0",
41
- "log-symbols": "^4.0.0",
40
+ "listr2": "^10.2.1",
41
+ "log-symbols": "^7.0.0",
42
42
  "micromatch": "^4.0.5",
43
43
  "shell-quote": "^1.7.3",
44
44
  "string-env-interpolation": "^1.0.1",
45
- "ts-log": "^2.2.3",
45
+ "ts-log": "^3.0.0",
46
46
  "tslib": "^2.4.0",
47
47
  "yaml": "^2.3.1",
48
- "yargs": "^17.0.0"
48
+ "yargs": "^18.0.0"
49
49
  },
50
50
  "repository": {
51
51
  "type": "git",
@@ -100,9 +100,10 @@
100
100
  "./package.json": "./package.json"
101
101
  },
102
102
  "bin": {
103
- "gql-gen": "cjs/bin.js",
104
- "graphql-codegen": "cjs/bin.js",
105
- "graphql-code-generator": "cjs/bin.js",
106
- "graphql-codegen-esm": "esm/bin.js"
103
+ "gql-gen": "esm/bin.js",
104
+ "graphql-codegen": "esm/bin.js",
105
+ "graphql-code-generator": "esm/bin.js",
106
+ "graphql-codegen-esm": "esm/bin.js",
107
+ "graphql-codegen-cjs": "cjs/bin.js"
107
108
  }
108
109
  }