@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/README.md CHANGED
@@ -4,6 +4,7 @@
4
4
  <img src="https://github.com/dotansimha/graphql-code-generator/blob/master/logo.png?raw=true" />
5
5
  </p>
6
6
 
7
- Live demo and full documentation: [the-guild.dev/graphql/codegen](https://the-guild.dev/graphql/codegen)
7
+ Live demo and full documentation:
8
+ [the-guild.dev/graphql/codegen](https://the-guild.dev/graphql/codegen)
8
9
 
9
10
  Project repository: [graphql-code-generator](https://github.com/dotansimha/graphql-code-generator)
package/cjs/cli.js CHANGED
@@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
36
  exports.runCli = runCli;
27
37
  exports.ensureGraphQlPackage = ensureGraphQlPackage;
package/cjs/codegen.js CHANGED
@@ -6,17 +6,17 @@ const fs_1 = tslib_1.__importDefault(require("fs"));
6
6
  const module_1 = require("module");
7
7
  const os_1 = require("os");
8
8
  const path_1 = tslib_1.__importDefault(require("path"));
9
+ const graphql_1 = require("graphql");
10
+ const listr2_1 = require("listr2");
9
11
  const core_1 = require("@graphql-codegen/core");
10
12
  const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
11
13
  const load_1 = require("@graphql-tools/load");
12
- const graphql_1 = require("graphql");
13
14
  const merge_1 = require("@graphql-tools/merge");
14
- const listr2_1 = require("listr2");
15
15
  const config_js_1 = require("./config.js");
16
+ const documentTransforms_js_1 = require("./documentTransforms.js");
16
17
  const plugins_js_1 = require("./plugins.js");
17
18
  const presets_js_1 = require("./presets.js");
18
19
  const debugging_js_1 = require("./utils/debugging.js");
19
- const documentTransforms_js_1 = require("./documentTransforms.js");
20
20
  /**
21
21
  * Poor mans ESM detection.
22
22
  * Looking at this and you have a better method?
@@ -60,6 +60,7 @@ async function executeCodegen(input) {
60
60
  let rootConfig = {};
61
61
  let rootSchemas;
62
62
  let rootDocuments;
63
+ let rootExternalDocuments;
63
64
  const generates = {};
64
65
  const cache = createCache();
65
66
  // We need a simple string to uniqually identify the provided GraphQLSchema objects for the above cache.
@@ -101,6 +102,8 @@ async function executeCodegen(input) {
101
102
  rootSchemas = (0, plugin_helpers_1.normalizeInstanceOrArray)(config.schema);
102
103
  /* Normalize root "documents" field */
103
104
  rootDocuments = (0, plugin_helpers_1.normalizeInstanceOrArray)(config.documents);
105
+ /* Normalize root "externalDocuments" field */
106
+ rootExternalDocuments = (0, plugin_helpers_1.normalizeInstanceOrArray)(config.externalDocuments);
104
107
  /* Normalize "generators" field */
105
108
  const generateKeys = Object.keys(config.generates || {});
106
109
  if (generateKeys.length === 0) {
@@ -173,9 +176,10 @@ async function executeCodegen(input) {
173
176
  let outputSchemaAst;
174
177
  let outputSchema;
175
178
  const outputFileTemplateConfig = outputConfig.config || {};
176
- let outputDocuments = [];
179
+ const outputDocuments = [];
177
180
  const outputSpecificSchemas = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.schema);
178
181
  let outputSpecificDocuments = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.documents);
182
+ let outputSpecificExternalDocuments = (0, plugin_helpers_1.normalizeInstanceOrArray)(outputConfig.externalDocuments);
179
183
  const preset = hasPreset
180
184
  ? typeof outputConfig.preset === 'string'
181
185
  ? await (0, presets_js_1.getPresetByName)(outputConfig.preset, makeDefaultLoader(context.cwd))
@@ -183,6 +187,7 @@ async function executeCodegen(input) {
183
187
  : null;
184
188
  if (preset?.prepareDocuments) {
185
189
  outputSpecificDocuments = await preset.prepareDocuments(filename, outputSpecificDocuments);
190
+ outputSpecificExternalDocuments = await preset.prepareDocuments(filename, outputSpecificExternalDocuments);
186
191
  }
187
192
  return subTask.newListr([
188
193
  {
@@ -191,7 +196,10 @@ async function executeCodegen(input) {
191
196
  (0, debugging_js_1.debugLog)(`[CLI] Loading Schemas`);
192
197
  const schemaPointerMap = {};
193
198
  const parsedSchemas = [];
194
- const allSchemaDenormalizedPointers = [...rootSchemas, ...outputSpecificSchemas];
199
+ const allSchemaDenormalizedPointers = [
200
+ ...rootSchemas,
201
+ ...outputSpecificSchemas,
202
+ ];
195
203
  for (const denormalizedPtr of allSchemaDenormalizedPointers) {
196
204
  if ((0, graphql_1.isSchema)(denormalizedPtr)) {
197
205
  parsedSchemas.push(denormalizedPtr);
@@ -203,7 +211,8 @@ async function executeCodegen(input) {
203
211
  Object.assign(schemaPointerMap, denormalizedPtr);
204
212
  }
205
213
  }
206
- const hash = JSON.stringify(schemaPointerMap) + parsedSchemas.map(getJsObjectId).join(',');
214
+ const hash = JSON.stringify(schemaPointerMap) +
215
+ parsedSchemas.map(getJsObjectId).join(',');
207
216
  const result = await cache('schema', hash, async () => {
208
217
  // collect parsed schemas
209
218
  const schemasToMerge = [...parsedSchemas];
@@ -229,34 +238,74 @@ async function executeCodegen(input) {
229
238
  title: 'Load GraphQL documents',
230
239
  task: wrapTask(async () => {
231
240
  (0, debugging_js_1.debugLog)(`[CLI] Loading Documents`);
232
- const documentPointerMap = {};
233
- const allDocumentsDenormalizedPointers = [...rootDocuments, ...outputSpecificDocuments];
234
- for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
235
- if (typeof denormalizedPtr === 'string') {
236
- documentPointerMap[denormalizedPtr] = {};
237
- }
238
- else if (typeof denormalizedPtr === 'object') {
239
- Object.assign(documentPointerMap, denormalizedPtr);
241
+ const populateDocumentPointerMap = (allDocumentsDenormalizedPointers) => {
242
+ const pointer = {};
243
+ for (const denormalizedPtr of allDocumentsDenormalizedPointers) {
244
+ if (typeof denormalizedPtr === 'string') {
245
+ pointer[denormalizedPtr] = {};
246
+ }
247
+ else if (typeof denormalizedPtr === 'object') {
248
+ Object.assign(pointer, denormalizedPtr);
249
+ }
240
250
  }
241
- }
251
+ return pointer;
252
+ };
253
+ const allDocumentsDenormalizedPointers = [
254
+ ...rootDocuments,
255
+ ...outputSpecificDocuments,
256
+ ];
257
+ const documentPointerMap = populateDocumentPointerMap(allDocumentsDenormalizedPointers);
242
258
  const hash = JSON.stringify(documentPointerMap);
243
- const result = await cache('documents', hash, async () => {
259
+ const outputDocumentsStandard = await cache('documents', hash, async () => {
244
260
  try {
245
- const documents = await context.loadDocuments(documentPointerMap);
246
- return {
247
- documents,
248
- };
261
+ const documents = await context.loadDocuments(documentPointerMap, 'standard');
262
+ return documents;
249
263
  }
250
264
  catch (error) {
251
- if (error instanceof load_1.NoTypeDefinitionsFound && config.ignoreNoDocuments) {
252
- return {
253
- documents: [],
254
- };
265
+ if (error instanceof load_1.NoTypeDefinitionsFound &&
266
+ config.ignoreNoDocuments) {
267
+ return [];
255
268
  }
256
269
  throw error;
257
270
  }
258
271
  });
259
- outputDocuments = result.documents;
272
+ const allExternalDocumentsDenormalizedPointers = [
273
+ ...rootExternalDocuments,
274
+ ...outputSpecificExternalDocuments,
275
+ ];
276
+ const externalDocumentsPointerMap = populateDocumentPointerMap(allExternalDocumentsDenormalizedPointers);
277
+ const externalDocumentHash = JSON.stringify(externalDocumentsPointerMap);
278
+ const outputExternalDocuments = await cache('documents', externalDocumentHash, async () => {
279
+ try {
280
+ const documents = await context.loadDocuments(externalDocumentsPointerMap, 'external');
281
+ return documents;
282
+ }
283
+ catch (error) {
284
+ if (error instanceof load_1.NoTypeDefinitionsFound &&
285
+ config.ignoreNoDocuments) {
286
+ return [];
287
+ }
288
+ throw error;
289
+ }
290
+ });
291
+ /**
292
+ * Merging `standard` and `external` documents here,
293
+ * so they can be processed the same way,
294
+ * before passed into presets and plugins
295
+ */
296
+ const processedFile = {};
297
+ const mergedDocuments = [
298
+ ...outputDocumentsStandard,
299
+ ...outputExternalDocuments,
300
+ ];
301
+ for (const file of mergedDocuments) {
302
+ const fileIdentifier = (file.location || '') + (file.hash || '');
303
+ if (processedFile[fileIdentifier]) {
304
+ continue;
305
+ }
306
+ outputDocuments.push(file);
307
+ processedFile[fileIdentifier] = true;
308
+ }
260
309
  }, filename, `Load GraphQL documents: ${filename}`, ctx),
261
310
  },
262
311
  {
@@ -355,7 +404,9 @@ async function executeCodegen(input) {
355
404
  exitOnError: false,
356
405
  };
357
406
  });
358
- return task.newListr(generateTasks, { concurrent: (0, os_1.cpus)().length || 1 });
407
+ return task.newListr(generateTasks, {
408
+ concurrent: (0, os_1.cpus)().length || 1,
409
+ });
359
410
  },
360
411
  },
361
412
  ], {
@@ -382,7 +433,9 @@ async function executeCodegen(input) {
382
433
  const errors = executedContext.errors.map(subErr => subErr.message || subErr.toString());
383
434
  error = new AggregateError(executedContext.errors, String(errors.join('\n\n')));
384
435
  // Best-effort to all stack traces for debugging
385
- error.stack = `${error.stack}\n\n${executedContext.errors.map(subErr => subErr.stack).join('\n\n')}`;
436
+ error.stack = `${error.stack}\n\n${executedContext.errors
437
+ .map(subErr => subErr.stack)
438
+ .join('\n\n')}`;
386
439
  }
387
440
  return { result, error };
388
441
  }
package/cjs/config.js CHANGED
@@ -14,13 +14,13 @@ const crypto_1 = require("crypto");
14
14
  const fs_1 = require("fs");
15
15
  const module_1 = require("module");
16
16
  const path_1 = require("path");
17
- const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
18
17
  const cosmiconfig_1 = require("cosmiconfig");
19
- const jiti_1 = require("jiti");
20
18
  const graphql_1 = require("graphql");
19
+ const jiti_1 = require("jiti");
21
20
  const string_env_interpolation_1 = require("string-env-interpolation");
22
21
  const yaml_1 = tslib_1.__importDefault(require("yaml"));
23
22
  const yargs_1 = tslib_1.__importDefault(require("yargs"));
23
+ const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
24
24
  const graphql_config_js_1 = require("./graphql-config.js");
25
25
  const load_js_1 = require("./load.js");
26
26
  const { lstat } = fs_1.promises;
@@ -266,7 +266,7 @@ class CodegenContext {
266
266
  this._config = config;
267
267
  this._graphqlConfig = graphqlConfig;
268
268
  this.filepath = this._graphqlConfig ? this._graphqlConfig.filepath : filepath;
269
- this.cwd = this._graphqlConfig ? this._graphqlConfig.dirpath : process.cwd();
269
+ this.cwd = this._graphqlConfig ? this._graphqlConfig.dirpath : config?.cwd || process.cwd();
270
270
  this.profiler = (0, plugin_helpers_1.createNoopProfiler)();
271
271
  }
272
272
  useProject(name) {
@@ -287,10 +287,18 @@ class CodegenContext {
287
287
  this.config = { ...this._config, pluginContext: this._pluginContext };
288
288
  }
289
289
  }
290
- return {
290
+ const config = {
291
+ 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.
291
292
  ...extraConfig,
292
293
  ...this.config,
293
294
  };
295
+ if (this._graphqlConfig) {
296
+ return config;
297
+ }
298
+ return {
299
+ ...config,
300
+ cwd: this.cwd,
301
+ };
294
302
  }
295
303
  updateConfig(config) {
296
304
  this.config = {
@@ -324,13 +332,15 @@ class CodegenContext {
324
332
  }
325
333
  return addHashToSchema((0, load_js_1.loadSchema)(pointer, config));
326
334
  }
327
- async loadDocuments(pointer) {
335
+ async loadDocuments(pointer, type) {
328
336
  const config = this.getConfig(load_js_1.defaultDocumentsLoadOptions);
329
337
  if (this._graphqlConfig) {
330
338
  // TODO: pointer won't work here
331
- return addHashToDocumentFiles(this._graphqlConfig.getProject(this._project).loadDocuments(pointer, { ...config, ...config.config }));
339
+ return addMetadataToSources(this._graphqlConfig
340
+ .getProject(this._project)
341
+ .loadDocuments(pointer, { ...config, ...config.config }), type);
332
342
  }
333
- return addHashToDocumentFiles((0, load_js_1.loadDocuments)(pointer, config));
343
+ return addMetadataToSources((0, load_js_1.loadDocuments)(pointer, config), type);
334
344
  }
335
345
  }
336
346
  exports.CodegenContext = CodegenContext;
@@ -353,18 +363,21 @@ function addHashToSchema(schemaPromise) {
353
363
  return schema;
354
364
  });
355
365
  }
356
- function hashDocument(doc) {
357
- if (doc.rawSDL) {
358
- return hashContent(doc.rawSDL);
359
- }
360
- if (doc.document) {
361
- return hashContent((0, graphql_1.print)(doc.document));
366
+ async function addMetadataToSources(documentFilesPromise, type) {
367
+ function hashDocument(doc) {
368
+ if (doc.rawSDL) {
369
+ return hashContent(doc.rawSDL);
370
+ }
371
+ if (doc.document) {
372
+ return hashContent((0, graphql_1.print)(doc.document));
373
+ }
374
+ return null;
362
375
  }
363
- return null;
364
- }
365
- function addHashToDocumentFiles(documentFilesPromise) {
366
- return documentFilesPromise.then(documentFiles => documentFiles.map(doc => {
376
+ return documentFilesPromise.then(documentFiles =>
377
+ // Note: `doc` here is technically `Source`, but by the end of the funciton it's `Types.DocumentFile`. This re-declaration makes TypeScript happy.
378
+ documentFiles.map((doc) => {
367
379
  doc.hash = hashDocument(doc);
380
+ doc.type = type;
368
381
  return doc;
369
382
  }));
370
383
  }
@@ -14,7 +14,11 @@ async function getDocumentTransform(documentTransform, loader, defaultName) {
14
14
  if (isTransformFileConfig(documentTransform)) {
15
15
  const name = Object.keys(documentTransform)[0];
16
16
  const transformObject = await getDocumentTransformByName(name, loader);
17
- return { name, transformObject, config: Object.values(documentTransform)[0] };
17
+ return {
18
+ name,
19
+ transformObject,
20
+ config: Object.values(documentTransform)[0],
21
+ };
18
22
  }
19
23
  throw new Error(`
20
24
  An unknown format document transform: '${defaultName}'.
@@ -10,8 +10,8 @@ const config_js_1 = require("./config.js");
10
10
  const hooks_js_1 = require("./hooks.js");
11
11
  const debugging_js_1 = require("./utils/debugging.js");
12
12
  const file_system_js_1 = require("./utils/file-system.js");
13
- const watcher_js_1 = require("./utils/watcher.js");
14
13
  const logger_js_1 = require("./utils/logger.js");
14
+ const watcher_js_1 = require("./utils/watcher.js");
15
15
  const hash = (content) => (0, crypto_1.createHash)('sha1').update(content).digest('base64');
16
16
  async function generate(input, saveToFile = true) {
17
17
  const context = (0, config_js_1.ensureContext)(input);
@@ -2,11 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CodegenExtension = void 0;
4
4
  exports.findAndLoadGraphQLConfig = findAndLoadGraphQLConfig;
5
+ const graphql_config_1 = require("graphql-config");
5
6
  const apollo_engine_loader_1 = require("@graphql-tools/apollo-engine-loader");
6
7
  const code_file_loader_1 = require("@graphql-tools/code-file-loader");
7
8
  const git_loader_1 = require("@graphql-tools/git-loader");
8
9
  const github_loader_1 = require("@graphql-tools/github-loader");
9
- const graphql_config_1 = require("graphql-config");
10
10
  const CodegenExtension = (api) => {
11
11
  // Schema
12
12
  api.loaders.schema.register(new code_file_loader_1.CodeFileLoader({
@@ -8,21 +8,25 @@ exports.italic = italic;
8
8
  const tslib_1 = require("tslib");
9
9
  const fs_1 = require("fs");
10
10
  const path_1 = require("path");
11
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
12
+ const detect_indent_1 = tslib_1.__importDefault(require("detect-indent"));
11
13
  const generator_1 = tslib_1.__importDefault(require("@babel/generator"));
12
14
  const template_1 = tslib_1.__importDefault(require("@babel/template"));
13
15
  const t = tslib_1.__importStar(require("@babel/types"));
14
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
15
- const detect_indent_1 = tslib_1.__importDefault(require("detect-indent"));
16
16
  const get_latest_version_js_1 = require("../utils/get-latest-version.js");
17
17
  const types_js_1 = require("./types.js");
18
18
  function jsObjectToBabelObjectExpression(obj) {
19
19
  const objExp = t.objectExpression([]);
20
20
  for (const [key, val] of Object.entries(obj)) {
21
21
  if (Array.isArray(val)) {
22
- 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))))));
22
+ 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'
23
+ ? jsObjectToBabelObjectExpression(v)
24
+ : t.valueToNode(v)))));
23
25
  }
24
26
  else {
25
- 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)));
27
+ objExp.properties.push(t.objectProperty(/^[a-zA-Z0-9]+$/.test(key) ? t.identifier(key) : t.stringLiteral(key), typeof val === 'object'
28
+ ? jsObjectToBabelObjectExpression(val)
29
+ : t.valueToNode(val)));
26
30
  }
27
31
  }
28
32
  return objExp;
package/cjs/init/index.js CHANGED
@@ -14,7 +14,7 @@ async function init() {
14
14
  Welcome to ${(0, helpers_js_1.bold)('GraphQL Code Generator')}!
15
15
  Answer few questions and we will setup everything for you.
16
16
  `);
17
- const possibleTargets = await (0, targets_js_1.guessTargets)();
17
+ const possibleTargets = (0, targets_js_1.guessTargets)();
18
18
  const answers = await (0, questions_js_1.getAnswers)(possibleTargets);
19
19
  // define config
20
20
  const config = {
@@ -10,7 +10,9 @@ exports.plugins = [
10
10
  value: 'typescript',
11
11
  pathInRepo: 'typescript/typescript',
12
12
  available: hasTag(types_js_1.Tags.typescript),
13
- shouldBeSelected: tags => oneOf(tags, types_js_1.Tags.angular, types_js_1.Tags.stencil) || allOf(tags, types_js_1.Tags.typescript, types_js_1.Tags.react) || noneOf(tags, types_js_1.Tags.flow),
13
+ shouldBeSelected: tags => oneOf(tags, types_js_1.Tags.angular, types_js_1.Tags.stencil) ||
14
+ allOf(tags, types_js_1.Tags.typescript, types_js_1.Tags.react) ||
15
+ noneOf(tags, types_js_1.Tags.flow),
14
16
  defaultExtension: '.ts',
15
17
  },
16
18
  {
@@ -21,7 +21,9 @@ async function getAnswers(possibleTargets) {
21
21
  validate: str => str.length > 0,
22
22
  });
23
23
  let documents;
24
- if (targets.includes(types_js_1.Tags.client) || targets.includes(types_js_1.Tags.angular) || targets.includes(types_js_1.Tags.stencil))
24
+ if (targets.includes(types_js_1.Tags.client) ||
25
+ targets.includes(types_js_1.Tags.angular) ||
26
+ targets.includes(types_js_1.Tags.stencil))
25
27
  documents = await (0, prompts_1.input)({
26
28
  message: 'Where are your operations and fragments?:',
27
29
  default: getDocumentsDefaultValue(targets),
@@ -46,7 +48,9 @@ async function getAnswers(possibleTargets) {
46
48
  });
47
49
  const config = await (0, prompts_1.input)({
48
50
  message: 'How to name the config file?',
49
- default: (() => targets.includes(types_js_1.Tags.client) || targets.includes(types_js_1.Tags.typescript) || targets.includes(types_js_1.Tags.angular)
51
+ default: (() => targets.includes(types_js_1.Tags.client) ||
52
+ targets.includes(types_js_1.Tags.typescript) ||
53
+ targets.includes(types_js_1.Tags.angular)
50
54
  ? 'codegen.ts'
51
55
  : 'codegen.yml')(),
52
56
  validate: str => {
@@ -136,7 +140,10 @@ function getApplicationTypeChoices(possibleTargets) {
136
140
  name: 'Application built with other framework or vanilla JS',
137
141
  key: 'client',
138
142
  value: [types_js_1.Tags.typescript, types_js_1.Tags.flow],
139
- checked: possibleTargets.Browser && !possibleTargets.Angular && !possibleTargets.React && !possibleTargets.Stencil,
143
+ checked: possibleTargets.Browser &&
144
+ !possibleTargets.Angular &&
145
+ !possibleTargets.React &&
146
+ !possibleTargets.Stencil,
140
147
  },
141
148
  ];
142
149
  }
@@ -4,7 +4,7 @@ exports.guessTargets = guessTargets;
4
4
  const fs_1 = require("fs");
5
5
  const path_1 = require("path");
6
6
  const types_js_1 = require("./types.js");
7
- async function guessTargets() {
7
+ function guessTargets() {
8
8
  const pkg = JSON.parse((0, fs_1.readFileSync)((0, path_1.resolve)(process.cwd(), 'package.json'), 'utf8'));
9
9
  const dependencies = Object.keys({
10
10
  ...pkg.dependencies,
package/cjs/load.js CHANGED
@@ -4,6 +4,7 @@ exports.defaultDocumentsLoadOptions = exports.defaultSchemaLoadOptions = void 0;
4
4
  exports.loadSchema = loadSchema;
5
5
  exports.loadDocuments = loadDocuments;
6
6
  const path_1 = require("path");
7
+ const graphql_1 = require("graphql");
7
8
  const apollo_engine_loader_1 = require("@graphql-tools/apollo-engine-loader");
8
9
  const code_file_loader_1 = require("@graphql-tools/code-file-loader");
9
10
  const git_loader_1 = require("@graphql-tools/git-loader");
@@ -12,7 +13,6 @@ const graphql_file_loader_1 = require("@graphql-tools/graphql-file-loader");
12
13
  const json_file_loader_1 = require("@graphql-tools/json-file-loader");
13
14
  const load_1 = require("@graphql-tools/load");
14
15
  const url_loader_1 = require("@graphql-tools/url-loader");
15
- const graphql_1 = require("graphql");
16
16
  exports.defaultSchemaLoadOptions = {
17
17
  assumeValidSDL: true,
18
18
  sort: true,
@@ -73,7 +73,7 @@ async function loadDocuments(documentPointers, config) {
73
73
  // we omit paths that don't resolve to a specific file
74
74
  continue;
75
75
  }
76
- ignore.push((0, path_1.join)(process.cwd(), generatePath));
76
+ ignore.push((0, path_1.join)(config.cwd || process.cwd(), generatePath));
77
77
  }
78
78
  try {
79
79
  const loadedFromToolkit = await (0, load_1.loadDocuments)(documentPointers, {
@@ -91,7 +91,10 @@ async function loadDocuments(documentPointers, config) {
91
91
  throw error;
92
92
  }
93
93
  // For other errors, we need to add an error message with documentPointers, so it's better for DevX
94
- throw new Error([`Failed to load documents from ${Object.keys(documentPointers).join(',')}:`, printError(error)].join('\n'));
94
+ throw new Error([
95
+ `Failed to load documents from ${Object.keys(documentPointers).join(',')}:`,
96
+ printError(error),
97
+ ].join('\n'));
95
98
  }
96
99
  }
97
100
  const printError = (error) => {
@@ -3,10 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.sortPatterns = exports.makeLocalPatternSet = exports.makeGlobalPatternSet = exports.makeShouldRebuild = exports.allAffirmativePatternsFromPatternSets = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const path_1 = require("path");
6
- const utils_1 = require("@graphql-tools/utils");
7
- const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
8
6
  const is_glob_1 = tslib_1.__importDefault(require("is-glob"));
9
7
  const micromatch_1 = tslib_1.__importDefault(require("micromatch"));
8
+ const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
9
+ const utils_1 = require("@graphql-tools/utils");
10
10
  const helpers_js_1 = require("./helpers.js");
11
11
  /**
12
12
  * Flatten a list of pattern sets to be a list of only the affirmative patterns
@@ -44,7 +44,10 @@ const makeShouldRebuild = ({ globalPatternSet, localPatternSets, }) => {
44
44
  const localMatchers = localPatternSets.map(localPatternSet => {
45
45
  return (path) => {
46
46
  // Is path negated by any negating watch pattern?
47
- if (matchesAnyNegatedPattern(path, [...globalPatternSet.watch.negated, ...localPatternSet.watch.negated])) {
47
+ if (matchesAnyNegatedPattern(path, [
48
+ ...globalPatternSet.watch.negated,
49
+ ...localPatternSet.watch.negated,
50
+ ])) {
48
51
  // Short circut: negations in watch patterns take priority
49
52
  return false;
50
53
  }
@@ -61,7 +64,10 @@ const makeShouldRebuild = ({ globalPatternSet, localPatternSets, }) => {
61
64
  ...globalPatternSet.documents.affirmative,
62
65
  ...localPatternSet.documents.affirmative,
63
66
  ]) &&
64
- !matchesAnyNegatedPattern(path, [...globalPatternSet.documents.negated, ...localPatternSet.documents.negated])) {
67
+ !matchesAnyNegatedPattern(path, [
68
+ ...globalPatternSet.documents.negated,
69
+ ...localPatternSet.documents.negated,
70
+ ])) {
65
71
  return true;
66
72
  }
67
73
  // Does path match schemas patterns (without being negated)?
@@ -69,7 +75,10 @@ const makeShouldRebuild = ({ globalPatternSet, localPatternSets, }) => {
69
75
  ...globalPatternSet.schemas.affirmative,
70
76
  ...localPatternSet.schemas.affirmative,
71
77
  ]) &&
72
- !matchesAnyNegatedPattern(path, [...globalPatternSet.schemas.negated, ...localPatternSet.schemas.negated])) {
78
+ !matchesAnyNegatedPattern(path, [
79
+ ...globalPatternSet.schemas.negated,
80
+ ...localPatternSet.schemas.negated,
81
+ ])) {
73
82
  return true;
74
83
  }
75
84
  // Otherwise, there is no match
@@ -100,7 +109,9 @@ const makeGlobalPatternSet = (initialContext) => {
100
109
  const config = initialContext.getConfig();
101
110
  return {
102
111
  watch: (0, exports.sortPatterns)([
103
- ...(typeof config.watch === 'boolean' ? [] : (0, plugin_helpers_1.normalizeInstanceOrArray)(config.watch ?? [])),
112
+ ...(typeof config.watch === 'boolean'
113
+ ? []
114
+ : (0, plugin_helpers_1.normalizeInstanceOrArray)(config.watch ?? [])),
104
115
  (0, path_1.relative)(process.cwd(), initialContext.filepath),
105
116
  ]),
106
117
  schemas: (0, exports.sortPatterns)(makePatternsFromSchemas((0, plugin_helpers_1.normalizeInstanceOrArray)(config.schema))),
@@ -3,18 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createWatcher = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const path_1 = require("path");
6
- const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
7
6
  const debounce_1 = tslib_1.__importDefault(require("debounce"));
8
- const micromatch_1 = tslib_1.__importDefault(require("micromatch"));
9
7
  const log_symbols_1 = tslib_1.__importDefault(require("log-symbols"));
8
+ const micromatch_1 = tslib_1.__importDefault(require("micromatch"));
9
+ const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
10
10
  const codegen_js_1 = require("../codegen.js");
11
11
  const config_js_1 = require("../config.js");
12
12
  const hooks_js_1 = require("../hooks.js");
13
- const file_system_js_1 = require("./file-system.js");
14
13
  const debugging_js_1 = require("./debugging.js");
14
+ const file_system_js_1 = require("./file-system.js");
15
15
  const logger_js_1 = require("./logger.js");
16
16
  const patterns_js_1 = require("./patterns.js");
17
- const abort_controller_polyfill_js_1 = require("./abort-controller-polyfill.js");
18
17
  function log(msg) {
19
18
  // double spaces to inline the message with Listr
20
19
  (0, logger_js_1.getLogger)().info(` ${msg}`);
@@ -29,8 +28,14 @@ const createWatcher = (initialContext, onNext) => {
29
28
  const localPatternSets = Object.keys(config.generates)
30
29
  .map(filename => (0, plugin_helpers_1.normalizeOutputParam)(config.generates[filename]))
31
30
  .map(conf => (0, patterns_js_1.makeLocalPatternSet)(conf));
32
- const allAffirmativePatterns = (0, patterns_js_1.allAffirmativePatternsFromPatternSets)([globalPatternSet, ...localPatternSets]);
33
- const shouldRebuild = (0, patterns_js_1.makeShouldRebuild)({ globalPatternSet, localPatternSets });
31
+ const allAffirmativePatterns = (0, patterns_js_1.allAffirmativePatternsFromPatternSets)([
32
+ globalPatternSet,
33
+ ...localPatternSets,
34
+ ]);
35
+ const shouldRebuild = (0, patterns_js_1.makeShouldRebuild)({
36
+ globalPatternSet,
37
+ localPatternSets,
38
+ });
34
39
  let watcherSubscription;
35
40
  const runWatcher = async (abortSignal) => {
36
41
  const watchDirectory = await findHighestCommonDirectory(allAffirmativePatterns);
@@ -133,7 +138,7 @@ const createWatcher = (initialContext, onNext) => {
133
138
  };
134
139
  // Use an AbortController for shutdown signals
135
140
  // NOTE: This will be polyfilled on Node 14 (or any environment without it defined)
136
- const abortController = new abort_controller_polyfill_js_1.AbortController();
141
+ const abortController = new AbortController();
137
142
  /**
138
143
  * Send shutdown signal and return a promise that only resolves after the
139
144
  * runningWatcher has resolved, which only resolved after the shutdown signal has been handled