@graphql-codegen/graphql-modules-preset 2.3.14 → 2.4.0-alpha-bd464a586.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js DELETED
@@ -1,625 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- const graphql = require('graphql');
8
- const path = require('path');
9
- const parse = _interopDefault(require('parse-filepath'));
10
- const changeCaseAll = require('change-case-all');
11
- const visitorPluginCommon = require('@graphql-codegen/visitor-plugin-common');
12
-
13
- const sep = '/';
14
- /**
15
- * Searches every node to collect used types
16
- */
17
- function collectUsedTypes(doc) {
18
- const used = [];
19
- doc.definitions.forEach(findRelated);
20
- function markAsUsed(type) {
21
- pushUnique(used, type);
22
- }
23
- function findRelated(node) {
24
- if (node.kind === graphql.Kind.OBJECT_TYPE_DEFINITION || node.kind === graphql.Kind.OBJECT_TYPE_EXTENSION) {
25
- // Object
26
- markAsUsed(node.name.value);
27
- if (node.fields) {
28
- node.fields.forEach(findRelated);
29
- }
30
- if (node.interfaces) {
31
- node.interfaces.forEach(findRelated);
32
- }
33
- }
34
- else if (node.kind === graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || node.kind === graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) {
35
- // Input
36
- markAsUsed(node.name.value);
37
- if (node.fields) {
38
- node.fields.forEach(findRelated);
39
- }
40
- }
41
- else if (node.kind === graphql.Kind.INTERFACE_TYPE_DEFINITION || node.kind === graphql.Kind.INTERFACE_TYPE_EXTENSION) {
42
- // Interface
43
- markAsUsed(node.name.value);
44
- if (node.fields) {
45
- node.fields.forEach(findRelated);
46
- }
47
- if (node.interfaces) {
48
- node.interfaces.forEach(findRelated);
49
- }
50
- }
51
- else if (node.kind === graphql.Kind.UNION_TYPE_DEFINITION || node.kind === graphql.Kind.UNION_TYPE_EXTENSION) {
52
- // Union
53
- markAsUsed(node.name.value);
54
- if (node.types) {
55
- node.types.forEach(findRelated);
56
- }
57
- }
58
- else if (node.kind === graphql.Kind.ENUM_TYPE_DEFINITION || node.kind === graphql.Kind.ENUM_TYPE_EXTENSION) {
59
- // Enum
60
- markAsUsed(node.name.value);
61
- }
62
- else if (node.kind === graphql.Kind.SCALAR_TYPE_DEFINITION || node.kind === graphql.Kind.SCALAR_TYPE_EXTENSION) {
63
- // Scalar
64
- if (!isGraphQLPrimitive(node.name.value)) {
65
- markAsUsed(node.name.value);
66
- }
67
- }
68
- else if (node.kind === graphql.Kind.INPUT_VALUE_DEFINITION) {
69
- // Argument
70
- findRelated(resolveTypeNode(node.type));
71
- }
72
- else if (node.kind === graphql.Kind.FIELD_DEFINITION) {
73
- // Field
74
- findRelated(resolveTypeNode(node.type));
75
- if (node.arguments) {
76
- node.arguments.forEach(findRelated);
77
- }
78
- }
79
- else if (node.kind === graphql.Kind.NAMED_TYPE &&
80
- // Named type
81
- !isGraphQLPrimitive(node.name.value)) {
82
- markAsUsed(node.name.value);
83
- }
84
- }
85
- return used;
86
- }
87
- function resolveTypeNode(node) {
88
- if (node.kind === graphql.Kind.LIST_TYPE) {
89
- return resolveTypeNode(node.type);
90
- }
91
- if (node.kind === graphql.Kind.NON_NULL_TYPE) {
92
- return resolveTypeNode(node.type);
93
- }
94
- return node;
95
- }
96
- function isGraphQLPrimitive(name) {
97
- return ['String', 'Boolean', 'ID', 'Float', 'Int'].includes(name);
98
- }
99
- function unique(val, i, all) {
100
- return i === all.indexOf(val);
101
- }
102
- function withQuotes(val) {
103
- return `'${val}'`;
104
- }
105
- function indent(size) {
106
- const space = new Array(size).fill(' ').join('');
107
- function indentInner(val) {
108
- return val
109
- .split('\n')
110
- .map(line => `${space}${line}`)
111
- .join('\n');
112
- }
113
- return indentInner;
114
- }
115
- function buildBlock({ name, lines }) {
116
- if (!lines.length) {
117
- return '';
118
- }
119
- return [`${name} {`, ...lines.map(indent(2)), '};'].join('\n');
120
- }
121
- const getRelativePath = function (filepath, basePath) {
122
- const normalizedFilepath = normalize(filepath);
123
- const normalizedBasePath = ensureStartsWithSeparator(normalize(ensureEndsWithSeparator(basePath)));
124
- const [, relativePath] = normalizedFilepath.split(normalizedBasePath);
125
- return relativePath;
126
- };
127
- function groupSourcesByModule(sources, basePath) {
128
- const grouped = {};
129
- sources.forEach(source => {
130
- const relativePath = getRelativePath(source.location, basePath);
131
- if (relativePath) {
132
- // PERF: we could guess the module by matching source.location with a list of already resolved paths
133
- const mod = extractModuleDirectory(source.location, basePath);
134
- if (!grouped[mod]) {
135
- grouped[mod] = [];
136
- }
137
- grouped[mod].push(source);
138
- }
139
- });
140
- return grouped;
141
- }
142
- function extractModuleDirectory(filepath, basePath) {
143
- const relativePath = getRelativePath(filepath, basePath);
144
- const [moduleDirectory] = relativePath.split(sep);
145
- return moduleDirectory;
146
- }
147
- function stripFilename(path) {
148
- const parsedPath = parse(path);
149
- return normalize(parsedPath.dir);
150
- }
151
- function normalize(path) {
152
- return path.replace(/\\/g, '/');
153
- }
154
- function ensureEndsWithSeparator(path) {
155
- return path.endsWith(sep) ? path : path + sep;
156
- }
157
- function ensureStartsWithSeparator(path) {
158
- return path.startsWith('.') ? path.replace(/^(..\/)|(.\/)/, '/') : path.startsWith('/') ? path : '/' + path;
159
- }
160
- /**
161
- * Pushes an item to a list only if the list doesn't include the item
162
- */
163
- function pushUnique(list, item) {
164
- if (!list.includes(item)) {
165
- list.push(item);
166
- }
167
- }
168
- function concatByKey(left, right, key) {
169
- // Remove duplicate, if an element is in right & left, it will be only once in the returned array.
170
- return [...new Set([...left[key], ...right[key]])];
171
- }
172
- function uniqueByKey(left, right, key) {
173
- return left[key].filter(item => !right[key].includes(item));
174
- }
175
- function createObject(keys, valueFn) {
176
- const obj = {};
177
- keys.forEach(key => {
178
- obj[key] = valueFn(key);
179
- });
180
- return obj;
181
- }
182
-
183
- const registryKeys = ['objects', 'inputs', 'interfaces', 'scalars', 'unions', 'enums'];
184
- const resolverKeys = ['scalars', 'objects', 'enums'];
185
- function buildModule(name, doc, { importNamespace, importPath, encapsulate, shouldDeclare, rootTypes, schema, baseVisitor, useGraphQLModules, }) {
186
- const picks = createObject(registryKeys, () => ({}));
187
- const defined = createObject(registryKeys, () => []);
188
- const extended = createObject(registryKeys, () => []);
189
- // List of types used in objects, fields, arguments etc
190
- const usedTypes = collectUsedTypes(doc);
191
- graphql.visit(doc, {
192
- ObjectTypeDefinition(node) {
193
- collectTypeDefinition(node);
194
- },
195
- ObjectTypeExtension(node) {
196
- collectTypeExtension(node);
197
- },
198
- InputObjectTypeDefinition(node) {
199
- collectTypeDefinition(node);
200
- },
201
- InputObjectTypeExtension(node) {
202
- collectTypeExtension(node);
203
- },
204
- InterfaceTypeDefinition(node) {
205
- collectTypeDefinition(node);
206
- },
207
- InterfaceTypeExtension(node) {
208
- collectTypeExtension(node);
209
- },
210
- ScalarTypeDefinition(node) {
211
- collectTypeDefinition(node);
212
- },
213
- UnionTypeDefinition(node) {
214
- collectTypeDefinition(node);
215
- },
216
- UnionTypeExtension(node) {
217
- collectTypeExtension(node);
218
- },
219
- EnumTypeDefinition(node) {
220
- collectTypeDefinition(node);
221
- },
222
- EnumTypeExtension(node) {
223
- collectTypeExtension(node);
224
- },
225
- });
226
- // Defined and Extended types
227
- const visited = createObject(registryKeys, key => concatByKey(defined, extended, key));
228
- // Types that are not defined or extended in a module, they come from other modules
229
- const external = createObject(registryKeys, key => uniqueByKey(extended, defined, key));
230
- //
231
- //
232
- //
233
- // Prints
234
- //
235
- //
236
- //
237
- // An actual output
238
- const imports = [`import * as ${importNamespace} from "${importPath}";`];
239
- if (useGraphQLModules) {
240
- imports.push(`import * as gm from "graphql-modules";`);
241
- }
242
- let content = [
243
- printDefinedFields(),
244
- printDefinedEnumValues(),
245
- printDefinedInputFields(),
246
- printSchemaTypes(usedTypes),
247
- printScalars(visited),
248
- printResolveSignaturesPerType(visited),
249
- printResolversType(visited),
250
- useGraphQLModules ? printResolveMiddlewareMap() : undefined,
251
- ]
252
- .filter(Boolean)
253
- .join('\n\n');
254
- if (encapsulate === 'namespace') {
255
- content =
256
- `${shouldDeclare ? 'declare' : 'export'} namespace ${baseVisitor.convertName(name, {
257
- suffix: 'Module',
258
- useTypesPrefix: false,
259
- useTypesSuffix: false,
260
- })} {\n` +
261
- (shouldDeclare ? `${indent(2)(imports.join('\n'))}\n` : '') +
262
- indent(2)(content) +
263
- '\n}';
264
- }
265
- return [...(!shouldDeclare ? imports : []), content].filter(Boolean).join('\n');
266
- /**
267
- * A dictionary of fields to pick from an object
268
- */
269
- function printDefinedFields() {
270
- return buildBlock({
271
- name: `interface DefinedFields`,
272
- lines: [...visited.objects, ...visited.interfaces].map(typeName => `${typeName}: ${printPicks(typeName, {
273
- ...picks.objects,
274
- ...picks.interfaces,
275
- })};`),
276
- });
277
- }
278
- /**
279
- * A dictionary of values to pick from an enum
280
- */
281
- function printDefinedEnumValues() {
282
- return buildBlock({
283
- name: `interface DefinedEnumValues`,
284
- lines: visited.enums.map(typeName => `${typeName}: ${printPicks(typeName, picks.enums)};`),
285
- });
286
- }
287
- function encapsulateTypeName(typeName) {
288
- if (encapsulate === 'prefix') {
289
- return `${changeCaseAll.pascalCase(name)}_${typeName}`;
290
- }
291
- return typeName;
292
- }
293
- /**
294
- * A dictionary of fields to pick from an input
295
- */
296
- function printDefinedInputFields() {
297
- return buildBlock({
298
- name: `interface DefinedInputFields`,
299
- lines: visited.inputs.map(typeName => `${typeName}: ${printPicks(typeName, picks.inputs)};`),
300
- });
301
- }
302
- /**
303
- * Prints signatures of schema types with picks
304
- */
305
- function printSchemaTypes(types) {
306
- return types
307
- .filter(type => !visited.scalars.includes(type))
308
- .map(printExportType)
309
- .join('\n');
310
- }
311
- function printResolveSignaturesPerType(registry) {
312
- return [
313
- [...registry.objects, ...registry.interfaces]
314
- .map(name => printResolverType(name, 'DefinedFields', !rootTypes.includes(name) && defined.objects.includes(name) ? ` | '__isTypeOf'` : ''))
315
- .join('\n'),
316
- ].join('\n');
317
- }
318
- function printScalars(registry) {
319
- if (!registry.scalars.length) {
320
- return '';
321
- }
322
- return [
323
- `export type ${encapsulateTypeName('Scalars')} = Pick<${importNamespace}.Scalars, ${registry.scalars
324
- .map(withQuotes)
325
- .join(' | ')}>;`,
326
- ...registry.scalars.map(scalar => {
327
- const convertedName = baseVisitor.convertName(scalar, {
328
- suffix: 'ScalarConfig',
329
- });
330
- return `export type ${encapsulateTypeName(convertedName)} = ${importNamespace}.${convertedName};`;
331
- }),
332
- ].join('\n');
333
- }
334
- /**
335
- * Aggregation of type resolver signatures
336
- */
337
- function printResolversType(registry) {
338
- const lines = [];
339
- for (const kind in registry) {
340
- const k = kind;
341
- if (registry.hasOwnProperty(k) && resolverKeys.includes(k)) {
342
- const types = registry[k];
343
- types.forEach(typeName => {
344
- if (k === 'enums') {
345
- return;
346
- }
347
- if (k === 'scalars') {
348
- lines.push(`${typeName}?: ${encapsulateTypeName(importNamespace)}.Resolvers['${typeName}'];`);
349
- }
350
- else {
351
- lines.push(`${typeName}?: ${encapsulateTypeName(typeName)}Resolvers;`);
352
- }
353
- });
354
- }
355
- }
356
- return buildBlock({
357
- name: `export interface ${encapsulateTypeName('Resolvers')}`,
358
- lines,
359
- });
360
- }
361
- /**
362
- * Signature for a map of resolve middlewares
363
- */
364
- function printResolveMiddlewareMap() {
365
- const wildcardField = printResolveMiddlewareRecord(withQuotes('*'));
366
- const blocks = [buildBlock({ name: `${withQuotes('*')}?:`, lines: [wildcardField] })];
367
- // Type.Field
368
- for (const typeName in picks.objects) {
369
- if (picks.objects.hasOwnProperty(typeName)) {
370
- const fields = picks.objects[typeName];
371
- const lines = [wildcardField].concat(fields.map(field => printResolveMiddlewareRecord(field)));
372
- blocks.push(buildBlock({
373
- name: `${typeName}?:`,
374
- lines,
375
- }));
376
- }
377
- }
378
- return buildBlock({
379
- name: `export interface ${encapsulateTypeName('MiddlewareMap')}`,
380
- lines: blocks,
381
- });
382
- }
383
- function printResolveMiddlewareRecord(path) {
384
- return `${path}?: gm.Middleware[];`;
385
- }
386
- function printResolverType(typeName, picksTypeName, extraKeys = '') {
387
- return `export type ${encapsulateTypeName(`${typeName}Resolvers`)} = Pick<${importNamespace}.${baseVisitor.convertName(typeName, {
388
- suffix: 'Resolvers',
389
- })}, ${picksTypeName}['${typeName}']${extraKeys}>;`;
390
- }
391
- function printPicks(typeName, records) {
392
- return records[typeName].filter(unique).map(withQuotes).join(' | ');
393
- }
394
- function printTypeBody(typeName) {
395
- const coreType = `${importNamespace}.${baseVisitor.convertName(typeName, {
396
- useTypesSuffix: true,
397
- useTypesPrefix: true,
398
- })}`;
399
- if (external.enums.includes(typeName) || external.objects.includes(typeName)) {
400
- if (schema && graphql.isScalarType(schema.getType(typeName))) {
401
- return `${importNamespace}.Scalars['${typeName}']`;
402
- }
403
- return coreType;
404
- }
405
- if (defined.enums.includes(typeName) && picks.enums[typeName]) {
406
- return `DefinedEnumValues['${typeName}']`;
407
- }
408
- if (defined.objects.includes(typeName) && picks.objects[typeName]) {
409
- return `Pick<${coreType}, DefinedFields['${typeName}']>`;
410
- }
411
- if (defined.interfaces.includes(typeName) && picks.interfaces[typeName]) {
412
- return `Pick<${coreType}, DefinedFields['${typeName}']>`;
413
- }
414
- if (defined.inputs.includes(typeName) && picks.inputs[typeName]) {
415
- return `Pick<${coreType}, DefinedInputFields['${typeName}']>`;
416
- }
417
- return coreType;
418
- }
419
- function printExportType(typeName) {
420
- return `export type ${encapsulateTypeName(typeName)} = ${printTypeBody(typeName)};`;
421
- }
422
- //
423
- //
424
- //
425
- // Utils
426
- //
427
- //
428
- //
429
- function collectFields(node, picksObj) {
430
- const name = node.name.value;
431
- if (node.fields) {
432
- if (!picksObj[name]) {
433
- picksObj[name] = [];
434
- }
435
- node.fields.forEach(field => {
436
- picksObj[name].push(field.name.value);
437
- });
438
- }
439
- }
440
- function collectValuesFromEnum(node) {
441
- const name = node.name.value;
442
- if (node.values) {
443
- if (!picks.enums[name]) {
444
- picks.enums[name] = [];
445
- }
446
- node.values.forEach(field => {
447
- picks.enums[name].push(field.name.value);
448
- });
449
- }
450
- }
451
- function collectTypeDefinition(node) {
452
- const name = node.name.value;
453
- switch (node.kind) {
454
- case graphql.Kind.OBJECT_TYPE_DEFINITION: {
455
- defined.objects.push(name);
456
- collectFields(node, picks.objects);
457
- break;
458
- }
459
- case graphql.Kind.ENUM_TYPE_DEFINITION: {
460
- defined.enums.push(name);
461
- collectValuesFromEnum(node);
462
- break;
463
- }
464
- case graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION: {
465
- defined.inputs.push(name);
466
- collectFields(node, picks.inputs);
467
- break;
468
- }
469
- case graphql.Kind.SCALAR_TYPE_DEFINITION: {
470
- defined.scalars.push(name);
471
- break;
472
- }
473
- case graphql.Kind.INTERFACE_TYPE_DEFINITION: {
474
- defined.interfaces.push(name);
475
- collectFields(node, picks.interfaces);
476
- break;
477
- }
478
- case graphql.Kind.UNION_TYPE_DEFINITION: {
479
- defined.unions.push(name);
480
- break;
481
- }
482
- }
483
- }
484
- function collectTypeExtension(node) {
485
- const name = node.name.value;
486
- switch (node.kind) {
487
- case graphql.Kind.OBJECT_TYPE_EXTENSION: {
488
- collectFields(node, picks.objects);
489
- // Do not include root types as extensions
490
- // so we can use them in DefinedFields
491
- if (rootTypes.includes(name)) {
492
- pushUnique(defined.objects, name);
493
- return;
494
- }
495
- pushUnique(extended.objects, name);
496
- break;
497
- }
498
- case graphql.Kind.ENUM_TYPE_EXTENSION: {
499
- collectValuesFromEnum(node);
500
- pushUnique(extended.enums, name);
501
- break;
502
- }
503
- case graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION: {
504
- collectFields(node, picks.inputs);
505
- pushUnique(extended.inputs, name);
506
- break;
507
- }
508
- case graphql.Kind.INTERFACE_TYPE_EXTENSION: {
509
- collectFields(node, picks.interfaces);
510
- pushUnique(extended.interfaces, name);
511
- break;
512
- }
513
- case graphql.Kind.UNION_TYPE_EXTENSION: {
514
- pushUnique(extended.unions, name);
515
- break;
516
- }
517
- }
518
- }
519
- }
520
-
521
- const preset = {
522
- buildGeneratesSection: options => {
523
- const useGraphQLModules = visitorPluginCommon.getConfigValue(options === null || options === void 0 ? void 0 : options.presetConfig.useGraphQLModules, true);
524
- const { baseOutputDir } = options;
525
- const { baseTypesPath, encapsulateModuleTypes } = options.presetConfig;
526
- const cwd = path.resolve(options.presetConfig.cwd || process.cwd());
527
- const importTypesNamespace = options.presetConfig.importTypesNamespace || 'Types';
528
- if (!baseTypesPath) {
529
- throw new Error(`Preset "graphql-modules" requires you to specify "baseTypesPath" configuration and point it to your base types file (generated by "typescript" plugin)!`);
530
- }
531
- if (!options.schemaAst || !options.schemaAst.extensions.sources) {
532
- throw new Error(`Preset "graphql-modules" requires to use GraphQL SDL`);
533
- }
534
- const extensions = options.schemaAst.extensions;
535
- const sourcesByModuleMap = groupSourcesByModule(extensions.extendedSources, baseOutputDir);
536
- const modules = Object.keys(sourcesByModuleMap);
537
- const baseVisitor = new visitorPluginCommon.BaseVisitor(options.config, {});
538
- // One file with an output from all plugins
539
- const baseOutput = {
540
- filename: path.resolve(cwd, baseOutputDir, baseTypesPath),
541
- schema: options.schema,
542
- documents: options.documents,
543
- plugins: [
544
- ...options.plugins,
545
- {
546
- 'modules-exported-scalars': {},
547
- },
548
- ],
549
- pluginMap: {
550
- ...options.pluginMap,
551
- 'modules-exported-scalars': {
552
- plugin: schema => {
553
- const typeMap = schema.getTypeMap();
554
- return Object.keys(typeMap)
555
- .map(t => {
556
- if (t && typeMap[t] && graphql.isScalarType(typeMap[t]) && !isGraphQLPrimitive(t)) {
557
- const convertedName = baseVisitor.convertName(t);
558
- return `export type ${convertedName} = Scalars["${t}"];`;
559
- }
560
- return null;
561
- })
562
- .filter(Boolean)
563
- .join('\n');
564
- },
565
- },
566
- },
567
- config: {
568
- ...options.config,
569
- enumsAsTypes: true,
570
- },
571
- schemaAst: options.schemaAst,
572
- };
573
- const baseTypesFilename = baseTypesPath.replace(/\.(js|ts|d.ts)$/, '');
574
- const baseTypesDir = stripFilename(baseOutput.filename);
575
- // One file per each module
576
- const outputs = modules.map(moduleName => {
577
- const filename = path.resolve(cwd, baseOutputDir, moduleName, options.presetConfig.filename);
578
- const dirpath = stripFilename(filename);
579
- const relativePath = path.relative(dirpath, baseTypesDir);
580
- const importPath = options.presetConfig.importBaseTypesFrom || normalize(path.join(relativePath, baseTypesFilename));
581
- const sources = sourcesByModuleMap[moduleName];
582
- const moduleDocument = graphql.concatAST(sources.map(source => source.document));
583
- const shouldDeclare = filename.endsWith('.d.ts');
584
- return {
585
- filename,
586
- schema: options.schema,
587
- documents: [],
588
- plugins: [
589
- ...options.plugins.filter(p => typeof p === 'object' && !!p.add),
590
- {
591
- 'graphql-modules-plugin': {},
592
- },
593
- ],
594
- pluginMap: {
595
- ...options.pluginMap,
596
- 'graphql-modules-plugin': {
597
- plugin: schema => {
598
- var _a, _b, _c;
599
- return buildModule(moduleName, moduleDocument, {
600
- importNamespace: importTypesNamespace,
601
- importPath,
602
- encapsulate: encapsulateModuleTypes || 'namespace',
603
- shouldDeclare,
604
- schema,
605
- baseVisitor,
606
- useGraphQLModules,
607
- rootTypes: [
608
- (_a = schema.getQueryType()) === null || _a === void 0 ? void 0 : _a.name,
609
- (_b = schema.getMutationType()) === null || _b === void 0 ? void 0 : _b.name,
610
- (_c = schema.getSubscriptionType()) === null || _c === void 0 ? void 0 : _c.name,
611
- ].filter(Boolean),
612
- });
613
- },
614
- },
615
- },
616
- config: options.config,
617
- schemaAst: options.schemaAst,
618
- };
619
- });
620
- return [baseOutput].concat(outputs);
621
- },
622
- };
623
-
624
- exports.default = preset;
625
- exports.preset = preset;