@graphql-codegen/visitor-plugin-common 6.2.2 → 7.0.0-alpha-20251224115216-0c4a535bdb152e75b9296d4c259f7dad0a13158f

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 (45) hide show
  1. package/cjs/base-documents-visitor.js +8 -0
  2. package/cjs/base-resolvers-visitor.js +5 -7
  3. package/cjs/base-types-visitor.js +40 -87
  4. package/cjs/base-visitor.js +1 -7
  5. package/cjs/client-side-base-visitor.js +4 -14
  6. package/cjs/convert-schema-enum-to-declaration-block-string.js +164 -0
  7. package/cjs/graphql-type-utils.js +15 -0
  8. package/cjs/imports.js +55 -7
  9. package/cjs/index.js +2 -0
  10. package/cjs/selection-set-processor/pre-resolve-types.js +9 -5
  11. package/cjs/selection-set-to-object.js +12 -18
  12. package/cjs/utils.js +22 -1
  13. package/esm/base-documents-visitor.js +8 -0
  14. package/esm/base-resolvers-visitor.js +5 -7
  15. package/esm/base-types-visitor.js +41 -88
  16. package/esm/base-visitor.js +1 -7
  17. package/esm/client-side-base-visitor.js +5 -15
  18. package/esm/convert-schema-enum-to-declaration-block-string.js +159 -0
  19. package/esm/graphql-type-utils.js +11 -0
  20. package/esm/imports.js +53 -7
  21. package/esm/index.js +2 -0
  22. package/esm/selection-set-processor/pre-resolve-types.js +11 -7
  23. package/esm/selection-set-to-object.js +12 -18
  24. package/esm/utils.js +20 -0
  25. package/package.json +2 -2
  26. package/typings/base-documents-visitor.d.cts +49 -1
  27. package/typings/base-documents-visitor.d.ts +49 -1
  28. package/typings/base-types-visitor.d.cts +1 -6
  29. package/typings/base-types-visitor.d.ts +1 -6
  30. package/typings/base-visitor.d.cts +1 -8
  31. package/typings/base-visitor.d.ts +1 -8
  32. package/typings/convert-schema-enum-to-declaration-block-string.d.cts +25 -0
  33. package/typings/convert-schema-enum-to-declaration-block-string.d.ts +25 -0
  34. package/typings/graphql-type-utils.d.cts +2 -0
  35. package/typings/graphql-type-utils.d.ts +2 -0
  36. package/typings/imports.d.cts +12 -2
  37. package/typings/imports.d.ts +12 -2
  38. package/typings/index.d.cts +2 -0
  39. package/typings/index.d.ts +2 -0
  40. package/typings/selection-set-processor/base.d.cts +5 -3
  41. package/typings/selection-set-processor/base.d.ts +5 -3
  42. package/typings/selection-set-to-object.d.cts +4 -4
  43. package/typings/selection-set-to-object.d.ts +4 -4
  44. package/typings/utils.d.cts +2 -1
  45. package/typings/utils.d.ts +2 -1
@@ -41,6 +41,8 @@ class BaseDocumentsVisitor extends base_visitor_js_1.BaseVisitor {
41
41
  operationResultSuffix: (0, utils_js_1.getConfigValue)(rawConfig.operationResultSuffix, ''),
42
42
  scalars: (0, utils_js_1.buildScalarsFromConfig)(_schema, rawConfig, defaultScalars),
43
43
  customDirectives: (0, utils_js_1.getConfigValue)(rawConfig.customDirectives, { apolloUnmask: false }),
44
+ generatesOperationTypes: (0, utils_js_1.getConfigValue)(rawConfig.generatesOperationTypes, true),
45
+ importSchemaTypesFrom: (0, utils_js_1.getConfigValue)(rawConfig.importSchemaTypesFrom, ''),
44
46
  ...(additionalConfig || {}),
45
47
  });
46
48
  this._schema = _schema;
@@ -81,6 +83,9 @@ class BaseDocumentsVisitor extends base_visitor_js_1.BaseVisitor {
81
83
  });
82
84
  }
83
85
  FragmentDefinition(node) {
86
+ if (!this.config.generatesOperationTypes) {
87
+ return null;
88
+ }
84
89
  const fragmentRootType = this._schema.getType(node.typeCondition.name.value);
85
90
  const selectionSet = this._selectionSetToObject.createNext(fragmentRootType, node.selectionSet);
86
91
  const fragmentSuffix = this.getFragmentSuffix(node);
@@ -106,6 +111,9 @@ class BaseDocumentsVisitor extends base_visitor_js_1.BaseVisitor {
106
111
  return variablesBlock;
107
112
  }
108
113
  OperationDefinition(node) {
114
+ if (!this.config.generatesOperationTypes) {
115
+ return null;
116
+ }
109
117
  const name = this.handleAnonymousOperation(node);
110
118
  const operationRootType = getRootType(node.operation, this._schema);
111
119
  if (!operationRootType) {
@@ -175,17 +175,15 @@ class BaseResolversVisitor extends base_visitor_js_1.BaseVisitor {
175
175
  const isMapped = this.config.mappers[typeName];
176
176
  const isScalar = this.config.scalars[typeName];
177
177
  const hasDefaultMapper = !!this.config.defaultMapper?.type;
178
- // Check for mappers first, even for root types, to allow overriding rootValueType
179
- if (isMapped && this.config.mappers[typeName].type && !hasPlaceholder(this.config.mappers[typeName].type)) {
180
- this.markMapperAsUsed(typeName);
181
- prev[typeName] = applyWrapper(this.config.mappers[typeName].type);
182
- return prev;
183
- }
184
178
  if (isRootType) {
185
179
  prev[typeName] = applyWrapper(this.config.rootValueType.type);
186
180
  return prev;
187
181
  }
188
- if ((0, graphql_1.isEnumType)(schemaType) && this.config.enumValues[typeName]) {
182
+ if (isMapped && this.config.mappers[typeName].type && !hasPlaceholder(this.config.mappers[typeName].type)) {
183
+ this.markMapperAsUsed(typeName);
184
+ prev[typeName] = applyWrapper(this.config.mappers[typeName].type);
185
+ }
186
+ else if ((0, graphql_1.isEnumType)(schemaType) && this.config.enumValues[typeName]) {
189
187
  const isExternalFile = !!this.config.enumValues[typeName].sourceFile;
190
188
  prev[typeName] = isExternalFile
191
189
  ? this.convertName(this.config.enumValues[typeName].typeIdentifier, {
@@ -9,7 +9,8 @@ const mappers_js_1 = require("./mappers.js");
9
9
  const scalars_js_1 = require("./scalars.js");
10
10
  const utils_js_1 = require("./utils.js");
11
11
  const variables_to_object_js_1 = require("./variables-to-object.js");
12
- const onlyUnderscoresPattern = /^_+$/;
12
+ const convert_schema_enum_to_declaration_block_string_js_1 = require("./convert-schema-enum-to-declaration-block-string.js");
13
+ const imports_js_1 = require("./imports.js");
13
14
  class BaseTypesVisitor extends base_visitor_js_1.BaseVisitor {
14
15
  _schema;
15
16
  _argumentsTransformer;
@@ -58,10 +59,20 @@ class BaseTypesVisitor extends base_visitor_js_1.BaseVisitor {
58
59
  return Object.keys(this.config.scalars).reduce((res, enumName) => {
59
60
  const mappedValue = this.config.scalars[enumName];
60
61
  if (mappedValue.input.isExternal) {
61
- res.push(this._buildTypeImport(mappedValue.input.import, mappedValue.input.source, mappedValue.input.default));
62
+ res.push((0, imports_js_1.buildTypeImport)({
63
+ identifier: mappedValue.input.import,
64
+ source: mappedValue.input.source,
65
+ asDefault: mappedValue.input.default,
66
+ useTypeImports: this.config.useTypeImports,
67
+ }));
62
68
  }
63
69
  if (mappedValue.output.isExternal) {
64
- res.push(this._buildTypeImport(mappedValue.output.import, mappedValue.output.source, mappedValue.output.default));
70
+ res.push((0, imports_js_1.buildTypeImport)({
71
+ identifier: mappedValue.output.import,
72
+ source: mappedValue.output.source,
73
+ asDefault: mappedValue.output.default,
74
+ useTypeImports: this.config.useTypeImports,
75
+ }));
65
76
  }
66
77
  return res;
67
78
  }, []);
@@ -71,7 +82,12 @@ class BaseTypesVisitor extends base_visitor_js_1.BaseVisitor {
71
82
  .map(directive => {
72
83
  const mappedValue = this.config.directiveArgumentAndInputFieldMappings[directive];
73
84
  if (mappedValue.isExternal) {
74
- return this._buildTypeImport(mappedValue.import, mappedValue.source, mappedValue.default);
85
+ return (0, imports_js_1.buildTypeImport)({
86
+ identifier: mappedValue.import,
87
+ source: mappedValue.source,
88
+ asDefault: mappedValue.default,
89
+ useTypeImports: this.config.useTypeImports,
90
+ });
75
91
  }
76
92
  return null;
77
93
  })
@@ -168,7 +184,7 @@ class BaseTypesVisitor extends base_visitor_js_1.BaseVisitor {
168
184
  return '';
169
185
  const typeString = node.type;
170
186
  const { type } = this._parsedConfig.declarationKind;
171
- const comment = this.getNodeComment(node);
187
+ const comment = (0, utils_js_1.getNodeComment)(node);
172
188
  return comment + (0, utils_js_1.indent)(`${node.name.value}: ${typeString}${this.getPunctuation(type)}`);
173
189
  }
174
190
  UnionTypeDefinition(node, key, parent) {
@@ -252,43 +268,11 @@ class BaseTypesVisitor extends base_visitor_js_1.BaseVisitor {
252
268
  // We empty this because we handle scalars in a different way, see constructor.
253
269
  return '';
254
270
  }
255
- _buildTypeImport(identifier, source, asDefault = false) {
256
- const { useTypeImports } = this.config;
257
- if (asDefault) {
258
- if (useTypeImports) {
259
- return `import type { default as ${identifier} } from '${source}';`;
260
- }
261
- return `import ${identifier} from '${source}';`;
262
- }
263
- return `import${useTypeImports ? ' type' : ''} { ${identifier} } from '${source}';`;
264
- }
265
- handleEnumValueMapper(typeIdentifier, importIdentifier, sourceIdentifier, sourceFile) {
266
- if (importIdentifier !== sourceIdentifier) {
267
- // use namespace import to dereference nested enum
268
- // { enumValues: { MyEnum: './my-file#NS.NestedEnum' } }
269
- return [
270
- this._buildTypeImport(importIdentifier || sourceIdentifier, sourceFile),
271
- `import ${typeIdentifier} = ${sourceIdentifier};`,
272
- ];
273
- }
274
- if (sourceIdentifier !== typeIdentifier) {
275
- return [this._buildTypeImport(`${sourceIdentifier} as ${typeIdentifier}`, sourceFile)];
276
- }
277
- return [this._buildTypeImport(importIdentifier || sourceIdentifier, sourceFile)];
278
- }
279
271
  getEnumsImports() {
280
- return Object.keys(this.config.enumValues)
281
- .flatMap(enumName => {
282
- const mappedValue = this.config.enumValues[enumName];
283
- if (mappedValue.sourceFile) {
284
- if (mappedValue.isDefault) {
285
- return [this._buildTypeImport(mappedValue.typeIdentifier, mappedValue.sourceFile, true)];
286
- }
287
- return this.handleEnumValueMapper(mappedValue.typeIdentifier, mappedValue.importIdentifier, mappedValue.sourceIdentifier, mappedValue.sourceFile);
288
- }
289
- return [];
290
- })
291
- .filter(Boolean);
272
+ return (0, imports_js_1.getEnumsImports)({
273
+ enumValues: this.config.enumValues,
274
+ useTypeImports: this.config.useTypeImports,
275
+ });
292
276
  }
293
277
  EnumTypeDefinition(node) {
294
278
  const enumName = node.name.value;
@@ -304,7 +288,21 @@ class BaseTypesVisitor extends base_visitor_js_1.BaseVisitor {
304
288
  useTypesSuffix: this.config.enumSuffix,
305
289
  }))
306
290
  .withComment(node.description.value)
307
- .withBlock(this.buildEnumValuesBlock(enumName, node.values)).string;
291
+ .withBlock((0, convert_schema_enum_to_declaration_block_string_js_1.buildEnumValuesBlock)({
292
+ typeName: enumName,
293
+ values: node.values,
294
+ schema: this._schema,
295
+ naming: {
296
+ convert: this.config.convert,
297
+ typesPrefix: this.config.typesPrefix,
298
+ useTypesPrefix: this.config.enumPrefix,
299
+ typesSuffix: this.config.typesSuffix,
300
+ useTypesSuffix: this.config.enumSuffix,
301
+ },
302
+ ignoreEnumValuesFromSchema: this.config.ignoreEnumValuesFromSchema,
303
+ declarationBlockConfig: this._declarationBlockConfig,
304
+ enumValues: this.config.enumValues,
305
+ })).string;
308
306
  }
309
307
  makeValidEnumIdentifier(identifier) {
310
308
  if (/^[0-9]/.exec(identifier)) {
@@ -312,31 +310,6 @@ class BaseTypesVisitor extends base_visitor_js_1.BaseVisitor {
312
310
  }
313
311
  return identifier;
314
312
  }
315
- buildEnumValuesBlock(typeName, values) {
316
- const schemaEnumType = this._schema
317
- ? this._schema.getType(typeName)
318
- : undefined;
319
- return values
320
- .map(enumOption => {
321
- const optionName = this.makeValidEnumIdentifier(this.convertName(enumOption, {
322
- useTypesPrefix: false,
323
- // We can only strip out the underscores if the value contains other
324
- // characters. Otherwise we'll generate syntactically invalid code.
325
- transformUnderscore: !onlyUnderscoresPattern.test(enumOption.name.value),
326
- }));
327
- const comment = this.getNodeComment(enumOption);
328
- const schemaEnumValue = schemaEnumType && !this.config.ignoreEnumValuesFromSchema
329
- ? schemaEnumType.getValue(enumOption.name.value).value
330
- : undefined;
331
- let enumValue = typeof schemaEnumValue === 'undefined' ? enumOption.name.value : schemaEnumValue;
332
- if (typeof this.config.enumValues[typeName]?.mappedValues?.[enumValue] !== 'undefined') {
333
- enumValue = this.config.enumValues[typeName].mappedValues[enumValue];
334
- }
335
- return (comment +
336
- (0, utils_js_1.indent)(`${optionName}${this._declarationBlockConfig.enumNameValueSeparator} ${(0, utils_js_1.wrapWithSingleQuotes)(enumValue, typeof schemaEnumValue !== 'undefined')}`));
337
- })
338
- .join(',\n');
339
- }
340
313
  DirectiveDefinition(_node) {
341
314
  return '';
342
315
  }
@@ -423,26 +396,6 @@ class BaseTypesVisitor extends base_visitor_js_1.BaseVisitor {
423
396
  SchemaExtension() {
424
397
  return null;
425
398
  }
426
- getNodeComment(node) {
427
- let commentText = node.description?.value;
428
- const deprecationDirective = node.directives.find(v => v.name.value === 'deprecated');
429
- if (deprecationDirective) {
430
- const deprecationReason = this.getDeprecationReason(deprecationDirective);
431
- commentText = `${commentText ? `${commentText}\n` : ''}@deprecated ${deprecationReason}`;
432
- }
433
- const comment = (0, utils_js_1.transformComment)(commentText, 1);
434
- return comment;
435
- }
436
- getDeprecationReason(directive) {
437
- if (directive.name.value === 'deprecated') {
438
- let reason = 'Field no longer supported';
439
- const deprecatedReason = directive.arguments[0];
440
- if (deprecatedReason && deprecatedReason.value.kind === graphql_1.Kind.STRING) {
441
- reason = deprecatedReason.value.value;
442
- }
443
- return reason;
444
- }
445
- }
446
399
  wrapWithListType(str) {
447
400
  return `Array<${str}>`;
448
401
  }
@@ -4,16 +4,11 @@ exports.BaseVisitor = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const auto_bind_1 = tslib_1.__importDefault(require("auto-bind"));
6
6
  const naming_js_1 = require("./naming.js");
7
- const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
8
7
  class BaseVisitor {
9
8
  _parsedConfig;
10
9
  _declarationBlockConfig = {};
11
10
  scalars;
12
11
  constructor(rawConfig, additionalConfig) {
13
- const importExtension = (0, plugin_helpers_1.normalizeImportExtension)({
14
- emitLegacyCommonJSImports: rawConfig.emitLegacyCommonJSImports,
15
- importExtension: rawConfig.importExtension,
16
- });
17
12
  this._parsedConfig = {
18
13
  convert: (0, naming_js_1.convertFactory)(rawConfig),
19
14
  typesPrefix: rawConfig.typesPrefix || '',
@@ -25,8 +20,7 @@ class BaseVisitor {
25
20
  useTypeImports: !!rawConfig.useTypeImports,
26
21
  allowEnumStringTypes: !!rawConfig.allowEnumStringTypes,
27
22
  inlineFragmentTypes: rawConfig.inlineFragmentTypes ?? 'inline',
28
- emitLegacyCommonJSImports: rawConfig.emitLegacyCommonJSImports ?? true,
29
- importExtension,
23
+ emitLegacyCommonJSImports: rawConfig.emitLegacyCommonJSImports === undefined ? true : !!rawConfig.emitLegacyCommonJSImports,
30
24
  extractAllFieldsToTypes: rawConfig.extractAllFieldsToTypes ?? false,
31
25
  printFieldsOnNewLines: rawConfig.printFieldsOnNewLines ?? false,
32
26
  includeExternalFragments: rawConfig.includeExternalFragments ?? false,
@@ -296,11 +296,7 @@ class ClientSideBaseVisitor extends base_visitor_js_1.BaseVisitor {
296
296
  }
297
297
  clearExtension(path) {
298
298
  const extension = (0, path_1.extname)(path);
299
- const importExtension = (0, plugin_helpers_1.normalizeImportExtension)({
300
- emitLegacyCommonJSImports: this.config.emitLegacyCommonJSImports,
301
- importExtension: this.config.importExtension,
302
- });
303
- if (extension === importExtension) {
299
+ if (!this.config.emitLegacyCommonJSImports && extension === '.js') {
304
300
  return path;
305
301
  }
306
302
  if (EXTENSIONS_TO_REMOVE.includes(extension)) {
@@ -334,10 +330,9 @@ class ClientSideBaseVisitor extends base_visitor_js_1.BaseVisitor {
334
330
  if (this._collectedOperations.length > 0) {
335
331
  if (this.config.importDocumentNodeExternallyFrom === 'near-operation-file' && this._documents.length === 1) {
336
332
  let documentPath = `./${this.clearExtension((0, path_1.basename)(this._documents[0].location))}`;
337
- documentPath += (0, plugin_helpers_1.normalizeImportExtension)({
338
- emitLegacyCommonJSImports: this.config.emitLegacyCommonJSImports,
339
- importExtension: this.config.importExtension,
340
- });
333
+ if (!this.config.emitLegacyCommonJSImports) {
334
+ documentPath += '.js';
335
+ }
341
336
  this._imports.add(`import * as Operations from '${documentPath}';`);
342
337
  }
343
338
  else {
@@ -355,10 +350,6 @@ class ClientSideBaseVisitor extends base_visitor_js_1.BaseVisitor {
355
350
  }
356
351
  const excludeFragments = options.excludeFragments || this.config.globalNamespace || this.config.documentMode !== DocumentMode.graphQLTag;
357
352
  if (!excludeFragments) {
358
- const importExtension = (0, plugin_helpers_1.normalizeImportExtension)({
359
- emitLegacyCommonJSImports: this.config.emitLegacyCommonJSImports,
360
- importExtension: this.config.importExtension,
361
- });
362
353
  const deduplicatedImports = Object.values((0, utils_js_1.groupBy)(this.config.fragmentImports, fi => fi.importSource.path))
363
354
  .map((fragmentImports) => ({
364
355
  ...fragmentImports[0],
@@ -367,7 +358,6 @@ class ClientSideBaseVisitor extends base_visitor_js_1.BaseVisitor {
367
358
  identifiers: (0, utils_js_1.unique)((0, utils_js_1.flatten)(fragmentImports.map(fi => fi.importSource.identifiers)), identifier => identifier.name),
368
359
  },
369
360
  emitLegacyCommonJSImports: this.config.emitLegacyCommonJSImports,
370
- importExtension,
371
361
  }))
372
362
  .filter(fragmentImport => fragmentImport.outputPath !== fragmentImport.importSource.path);
373
363
  for (const fragmentImport of deduplicatedImports) {
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildEnumValuesBlock = exports.convertSchemaEnumToDeclarationBlockString = void 0;
4
+ const utils_js_1 = require("./utils.js");
5
+ const convertSchemaEnumToDeclarationBlockString = ({ schema, node, enumName, enumValues, futureProofEnums, ignoreEnumValuesFromSchema, outputType, declarationBlockConfig, naming, }) => {
6
+ if (enumValues[enumName]?.sourceFile) {
7
+ return `export { ${enumValues[enumName].typeIdentifier} };\n`;
8
+ }
9
+ const getValueFromConfig = (enumValue) => {
10
+ if (typeof enumValues[enumName]?.mappedValues?.[enumValue] !== 'undefined') {
11
+ return enumValues[enumName].mappedValues[enumValue];
12
+ }
13
+ return null;
14
+ };
15
+ const withFutureAddedValue = [futureProofEnums ? [(0, utils_js_1.indent)('| ' + (0, utils_js_1.wrapWithSingleQuotes)('%future added value'))] : []];
16
+ const enumTypeName = convertName({
17
+ options: {
18
+ typesPrefix: naming.typesPrefix,
19
+ typesSuffix: naming.typesSuffix,
20
+ useTypesPrefix: naming.useTypesPrefix,
21
+ useTypesSuffix: naming.useTypesSuffix,
22
+ },
23
+ convert: () => naming.convert(node),
24
+ });
25
+ if (outputType === 'string-literal') {
26
+ return new utils_js_1.DeclarationBlock(declarationBlockConfig)
27
+ .export()
28
+ .asKind('type')
29
+ .withComment(node.description?.value)
30
+ .withName(enumTypeName)
31
+ .withContent('\n' +
32
+ node.values
33
+ .map(enumOption => {
34
+ const name = enumOption.name.value;
35
+ const enumValue = getValueFromConfig(name) ?? name;
36
+ const comment = (0, utils_js_1.transformComment)(enumOption.description?.value, 1);
37
+ return comment + (0, utils_js_1.indent)('| ' + (0, utils_js_1.wrapWithSingleQuotes)(enumValue));
38
+ })
39
+ .concat(...withFutureAddedValue)
40
+ .join('\n')).string;
41
+ }
42
+ if (outputType === 'native-numeric') {
43
+ return new utils_js_1.DeclarationBlock(declarationBlockConfig)
44
+ .export()
45
+ .withComment(node.description?.value)
46
+ .withName(enumTypeName)
47
+ .asKind('enum')
48
+ .withBlock(node.values
49
+ .map((enumOption, i) => {
50
+ const valueFromConfig = getValueFromConfig(enumOption.name.value);
51
+ const enumValue = valueFromConfig ?? i;
52
+ const comment = (0, utils_js_1.transformComment)(enumOption.description?.value, 1);
53
+ const optionName = makeValidEnumIdentifier(convertName({
54
+ options: {
55
+ typesPrefix: naming.typesPrefix,
56
+ typesSuffix: naming.typesSuffix,
57
+ useTypesPrefix: false,
58
+ },
59
+ convert: () => naming.convert(enumOption, { transformUnderscore: true }),
60
+ }));
61
+ return comment + (0, utils_js_1.indent)(optionName) + ` = ${enumValue}`;
62
+ })
63
+ .concat(...withFutureAddedValue)
64
+ .join(',\n')).string;
65
+ }
66
+ if (outputType === 'const') {
67
+ const typeName = `export type ${enumTypeName} = typeof ${enumTypeName}[keyof typeof ${enumTypeName}];`;
68
+ const enumAsConst = new utils_js_1.DeclarationBlock({
69
+ ...declarationBlockConfig,
70
+ blockTransformer: block => {
71
+ return block + ' as const';
72
+ },
73
+ })
74
+ .export()
75
+ .asKind('const')
76
+ .withName(enumTypeName)
77
+ .withComment(node.description?.value)
78
+ .withBlock(node.values
79
+ .map(enumOption => {
80
+ const optionName = makeValidEnumIdentifier(convertName({
81
+ options: {
82
+ typesPrefix: naming.typesPrefix,
83
+ typesSuffix: naming.typesPrefix,
84
+ },
85
+ convert: () => naming.convert(enumOption, {
86
+ transformUnderscore: true,
87
+ }),
88
+ }));
89
+ const comment = (0, utils_js_1.transformComment)(enumOption.description?.value, 1);
90
+ const name = enumOption.name.value;
91
+ const enumValue = getValueFromConfig(name) ?? name;
92
+ return comment + (0, utils_js_1.indent)(`${optionName}: ${(0, utils_js_1.wrapWithSingleQuotes)(enumValue)}`);
93
+ })
94
+ .join(',\n')).string;
95
+ return [enumAsConst, typeName].join('\n');
96
+ }
97
+ return new utils_js_1.DeclarationBlock(declarationBlockConfig)
98
+ .export()
99
+ .asKind(outputType === 'native-const' ? 'const enum' : 'enum')
100
+ .withName(enumTypeName)
101
+ .withComment(node.description?.value)
102
+ .withBlock((0, exports.buildEnumValuesBlock)({
103
+ typeName: enumName,
104
+ values: node.values,
105
+ schema,
106
+ naming,
107
+ ignoreEnumValuesFromSchema,
108
+ declarationBlockConfig,
109
+ enumValues,
110
+ })).string;
111
+ };
112
+ exports.convertSchemaEnumToDeclarationBlockString = convertSchemaEnumToDeclarationBlockString;
113
+ const buildEnumValuesBlock = ({ typeName, values, schema, naming, ignoreEnumValuesFromSchema, declarationBlockConfig, enumValues, }) => {
114
+ const schemaEnumType = schema
115
+ ? schema.getType(typeName)
116
+ : undefined;
117
+ return values
118
+ .map(enumOption => {
119
+ const onlyUnderscoresPattern = /^_+$/;
120
+ const optionName = makeValidEnumIdentifier(convertName({
121
+ options: {
122
+ useTypesPrefix: false,
123
+ typesPrefix: naming.typesPrefix,
124
+ typesSuffix: naming.typesSuffix,
125
+ },
126
+ convert: () => naming.convert(enumOption, {
127
+ // We can only strip out the underscores if the value contains other
128
+ // characters. Otherwise we'll generate syntactically invalid code.
129
+ transformUnderscore: !onlyUnderscoresPattern.test(enumOption.name.value),
130
+ }),
131
+ }));
132
+ const comment = (0, utils_js_1.getNodeComment)(enumOption);
133
+ const schemaEnumValue = schemaEnumType && !ignoreEnumValuesFromSchema
134
+ ? schemaEnumType.getValue(enumOption.name.value).value
135
+ : undefined;
136
+ let enumValue = typeof schemaEnumValue === 'undefined' ? enumOption.name.value : schemaEnumValue;
137
+ if (typeof enumValues[typeName]?.mappedValues?.[enumValue] !== 'undefined') {
138
+ enumValue = enumValues[typeName].mappedValues[enumValue];
139
+ }
140
+ return (comment +
141
+ (0, utils_js_1.indent)(`${optionName}${declarationBlockConfig.enumNameValueSeparator} ${(0, utils_js_1.wrapWithSingleQuotes)(enumValue, typeof schemaEnumValue !== 'undefined')}`));
142
+ })
143
+ .join(',\n');
144
+ };
145
+ exports.buildEnumValuesBlock = buildEnumValuesBlock;
146
+ const makeValidEnumIdentifier = (identifier) => {
147
+ if (/^[0-9]/.exec(identifier)) {
148
+ return (0, utils_js_1.wrapWithSingleQuotes)(identifier, true);
149
+ }
150
+ return identifier;
151
+ };
152
+ const convertName = ({ convert, options, }) => {
153
+ const useTypesPrefix = typeof options.useTypesPrefix === 'boolean' ? options.useTypesPrefix : true;
154
+ const useTypesSuffix = typeof options.useTypesSuffix === 'boolean' ? options.useTypesSuffix : true;
155
+ let convertedName = '';
156
+ if (useTypesPrefix) {
157
+ convertedName += options.typesPrefix;
158
+ }
159
+ convertedName += convert();
160
+ if (useTypesSuffix) {
161
+ convertedName += options.typesSuffix;
162
+ }
163
+ return convertedName;
164
+ };
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNativeNamedType = void 0;
4
+ const graphql_1 = require("graphql");
5
+ const isNativeNamedType = (namedType) => {
6
+ // "Native" NamedType in this context means the following:
7
+ // 1. introspection types i.e. with `__` prefixes
8
+ // 2. base scalars e.g. Boolean, Int, etc.
9
+ // 3. Other natives (mostly base scalars) which was not defined in the schema i.e. no `astNode`
10
+ if ((0, graphql_1.isSpecifiedScalarType)(namedType) || (0, graphql_1.isIntrospectionType)(namedType) || !namedType.astNode) {
11
+ return true;
12
+ }
13
+ return false;
14
+ };
15
+ exports.isNativeNamedType = isNativeNamedType;
package/cjs/imports.js CHANGED
@@ -6,10 +6,11 @@ exports.resolveRelativeImport = resolveRelativeImport;
6
6
  exports.resolveImportSource = resolveImportSource;
7
7
  exports.clearExtension = clearExtension;
8
8
  exports.fixLocalFilePath = fixLocalFilePath;
9
+ exports.getEnumsImports = getEnumsImports;
10
+ exports.buildTypeImport = buildTypeImport;
9
11
  const tslib_1 = require("tslib");
10
12
  const path_1 = require("path");
11
13
  const parse_filepath_1 = tslib_1.__importDefault(require("parse-filepath"));
12
- const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
13
14
  function generateFragmentImportStatement(statement, kind) {
14
15
  const { importSource: fragmentImportSource, ...rest } = statement;
15
16
  const { identifiers, path, namespace } = fragmentImportSource;
@@ -32,12 +33,7 @@ function generateImportStatement(statement) {
32
33
  const importNames = importSource.identifiers?.length
33
34
  ? `{ ${Array.from(new Set(importSource.identifiers)).join(', ')} }`
34
35
  : '*';
35
- const importExtension = importPath.startsWith('/') || importPath.startsWith('.')
36
- ? (0, plugin_helpers_1.normalizeImportExtension)({
37
- emitLegacyCommonJSImports: statement.emitLegacyCommonJSImports,
38
- importExtension: statement.importExtension,
39
- })
40
- : '';
36
+ const importExtension = importPath.startsWith('/') || importPath.startsWith('.') ? (statement.emitLegacyCommonJSImports ? '' : '.js') : '';
41
37
  const importAlias = importSource.namespace ? ` as ${importSource.namespace}` : '';
42
38
  const importStatement = typesImport ? 'import type' : 'import';
43
39
  return `${importStatement} ${importNames}${importAlias} from '${importPath}${importExtension}';${importAlias ? '\n' : ''}`;
@@ -71,3 +67,55 @@ function clearExtension(path) {
71
67
  function fixLocalFilePath(path) {
72
68
  return path.startsWith('..') ? path : `./${path}`;
73
69
  }
70
+ function getEnumsImports({ enumValues, useTypeImports, }) {
71
+ function handleEnumValueMapper({ typeIdentifier, importIdentifier, sourceIdentifier, sourceFile, useTypeImports, }) {
72
+ if (importIdentifier !== sourceIdentifier) {
73
+ // use namespace import to dereference nested enum
74
+ // { enumValues: { MyEnum: './my-file#NS.NestedEnum' } }
75
+ return [
76
+ buildTypeImport({ identifier: importIdentifier || sourceIdentifier, source: sourceFile, useTypeImports }),
77
+ `import ${typeIdentifier} = ${sourceIdentifier};`,
78
+ ];
79
+ }
80
+ if (sourceIdentifier !== typeIdentifier) {
81
+ return [
82
+ buildTypeImport({ identifier: `${sourceIdentifier} as ${typeIdentifier}`, source: sourceFile, useTypeImports }),
83
+ ];
84
+ }
85
+ return [buildTypeImport({ identifier: importIdentifier || sourceIdentifier, source: sourceFile, useTypeImports })];
86
+ }
87
+ return Object.keys(enumValues)
88
+ .flatMap(enumName => {
89
+ const mappedValue = enumValues[enumName];
90
+ if (mappedValue.sourceFile) {
91
+ if (mappedValue.isDefault) {
92
+ return [
93
+ buildTypeImport({
94
+ identifier: mappedValue.typeIdentifier,
95
+ source: mappedValue.sourceFile,
96
+ asDefault: true,
97
+ useTypeImports,
98
+ }),
99
+ ];
100
+ }
101
+ return handleEnumValueMapper({
102
+ typeIdentifier: mappedValue.typeIdentifier,
103
+ importIdentifier: mappedValue.importIdentifier,
104
+ sourceIdentifier: mappedValue.sourceIdentifier,
105
+ sourceFile: mappedValue.sourceFile,
106
+ useTypeImports,
107
+ });
108
+ }
109
+ return [];
110
+ })
111
+ .filter(Boolean);
112
+ }
113
+ function buildTypeImport({ identifier, source, useTypeImports, asDefault = false, }) {
114
+ if (asDefault) {
115
+ if (useTypeImports) {
116
+ return `import type { default as ${identifier} } from '${source}';`;
117
+ }
118
+ return `import ${identifier} from '${source}';`;
119
+ }
120
+ return `import${useTypeImports ? ' type' : ''} { ${identifier} } from '${source}';`;
121
+ }
package/cjs/index.js CHANGED
@@ -20,3 +20,5 @@ tslib_1.__exportStar(require("./selection-set-to-object.js"), exports);
20
20
  tslib_1.__exportStar(require("./types.js"), exports);
21
21
  tslib_1.__exportStar(require("./utils.js"), exports);
22
22
  tslib_1.__exportStar(require("./variables-to-object.js"), exports);
23
+ tslib_1.__exportStar(require("./convert-schema-enum-to-declaration-block-string.js"), exports);
24
+ tslib_1.__exportStar(require("./graphql-type-utils.js"), exports);
@@ -21,9 +21,10 @@ class PreResolveTypesProcessor extends base_js_1.BaseSelectionSetProcessor {
21
21
  const fieldObj = schemaType.getFields()[field.fieldName];
22
22
  const baseType = (0, plugin_helpers_1.getBaseType)(fieldObj.type);
23
23
  let typeToUse = baseType.name;
24
- const useInnerType = field.isConditional && (0, graphql_1.isNonNullType)(fieldObj.type);
25
- const innerType = useInnerType ? (0, plugin_helpers_1.removeNonNullWrapper)(fieldObj.type) : undefined;
26
- const name = this.config.formatNamedField(field.fieldName, useInnerType ? innerType : fieldObj.type, field.isConditional, unsetTypes);
24
+ const name = this.config.formatNamedField({
25
+ name: field.fieldName,
26
+ isOptional: field.isConditional || unsetTypes,
27
+ });
27
28
  if (unsetTypes) {
28
29
  return {
29
30
  name,
@@ -54,7 +55,7 @@ class PreResolveTypesProcessor extends base_js_1.BaseSelectionSetProcessor {
54
55
  }
55
56
  return fields.map(aliasedField => {
56
57
  if (aliasedField.fieldName === '__typename') {
57
- const name = this.config.formatNamedField(aliasedField.alias, null);
58
+ const name = this.config.formatNamedField({ name: aliasedField.alias });
58
59
  return {
59
60
  name,
60
61
  type: `'${schemaType.name}'`,
@@ -71,7 +72,10 @@ class PreResolveTypesProcessor extends base_js_1.BaseSelectionSetProcessor {
71
72
  useTypesSuffix: this.config.enumSuffix,
72
73
  });
73
74
  }
74
- const name = this.config.formatNamedField(aliasedField.alias, fieldObj.type, aliasedField.isConditional, unsetTypes);
75
+ const name = this.config.formatNamedField({
76
+ name: aliasedField.alias,
77
+ isOptional: aliasedField.isConditional || unsetTypes,
78
+ });
75
79
  if (unsetTypes) {
76
80
  return {
77
81
  type: 'never',