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