@graphql-codegen/graphql-modules-preset 2.3.14 → 2.4.0-alpha-29eb1293b.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/cjs/builder.js ADDED
@@ -0,0 +1,344 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildModule = void 0;
4
+ const graphql_1 = require("graphql");
5
+ const change_case_all_1 = require("change-case-all");
6
+ const utils_js_1 = require("./utils.js");
7
+ const registryKeys = ['objects', 'inputs', 'interfaces', 'scalars', 'unions', 'enums'];
8
+ const resolverKeys = ['scalars', 'objects', 'enums'];
9
+ function buildModule(name, doc, { importNamespace, importPath, encapsulate, shouldDeclare, rootTypes, schema, baseVisitor, useGraphQLModules, }) {
10
+ const picks = (0, utils_js_1.createObject)(registryKeys, () => ({}));
11
+ const defined = (0, utils_js_1.createObject)(registryKeys, () => []);
12
+ const extended = (0, utils_js_1.createObject)(registryKeys, () => []);
13
+ // List of types used in objects, fields, arguments etc
14
+ const usedTypes = (0, utils_js_1.collectUsedTypes)(doc);
15
+ (0, graphql_1.visit)(doc, {
16
+ ObjectTypeDefinition(node) {
17
+ collectTypeDefinition(node);
18
+ },
19
+ ObjectTypeExtension(node) {
20
+ collectTypeExtension(node);
21
+ },
22
+ InputObjectTypeDefinition(node) {
23
+ collectTypeDefinition(node);
24
+ },
25
+ InputObjectTypeExtension(node) {
26
+ collectTypeExtension(node);
27
+ },
28
+ InterfaceTypeDefinition(node) {
29
+ collectTypeDefinition(node);
30
+ },
31
+ InterfaceTypeExtension(node) {
32
+ collectTypeExtension(node);
33
+ },
34
+ ScalarTypeDefinition(node) {
35
+ collectTypeDefinition(node);
36
+ },
37
+ UnionTypeDefinition(node) {
38
+ collectTypeDefinition(node);
39
+ },
40
+ UnionTypeExtension(node) {
41
+ collectTypeExtension(node);
42
+ },
43
+ EnumTypeDefinition(node) {
44
+ collectTypeDefinition(node);
45
+ },
46
+ EnumTypeExtension(node) {
47
+ collectTypeExtension(node);
48
+ },
49
+ });
50
+ // Defined and Extended types
51
+ const visited = (0, utils_js_1.createObject)(registryKeys, key => (0, utils_js_1.concatByKey)(defined, extended, key));
52
+ // Types that are not defined or extended in a module, they come from other modules
53
+ const external = (0, utils_js_1.createObject)(registryKeys, key => (0, utils_js_1.uniqueByKey)(extended, defined, key));
54
+ //
55
+ //
56
+ //
57
+ // Prints
58
+ //
59
+ //
60
+ //
61
+ // An actual output
62
+ const imports = [`import * as ${importNamespace} from "${importPath}";`];
63
+ if (useGraphQLModules) {
64
+ imports.push(`import * as gm from "graphql-modules";`);
65
+ }
66
+ let content = [
67
+ printDefinedFields(),
68
+ printDefinedEnumValues(),
69
+ printDefinedInputFields(),
70
+ printSchemaTypes(usedTypes),
71
+ printScalars(visited),
72
+ printResolveSignaturesPerType(visited),
73
+ printResolversType(visited),
74
+ useGraphQLModules ? printResolveMiddlewareMap() : undefined,
75
+ ]
76
+ .filter(Boolean)
77
+ .join('\n\n');
78
+ if (encapsulate === 'namespace') {
79
+ content =
80
+ `${shouldDeclare ? 'declare' : 'export'} namespace ${baseVisitor.convertName(name, {
81
+ suffix: 'Module',
82
+ useTypesPrefix: false,
83
+ useTypesSuffix: false,
84
+ })} {\n` +
85
+ (shouldDeclare ? `${(0, utils_js_1.indent)(2)(imports.join('\n'))}\n` : '') +
86
+ (0, utils_js_1.indent)(2)(content) +
87
+ '\n}';
88
+ }
89
+ return [...(!shouldDeclare ? imports : []), content].filter(Boolean).join('\n');
90
+ /**
91
+ * A dictionary of fields to pick from an object
92
+ */
93
+ function printDefinedFields() {
94
+ return (0, utils_js_1.buildBlock)({
95
+ name: `interface DefinedFields`,
96
+ lines: [...visited.objects, ...visited.interfaces].map(typeName => `${typeName}: ${printPicks(typeName, {
97
+ ...picks.objects,
98
+ ...picks.interfaces,
99
+ })};`),
100
+ });
101
+ }
102
+ /**
103
+ * A dictionary of values to pick from an enum
104
+ */
105
+ function printDefinedEnumValues() {
106
+ return (0, utils_js_1.buildBlock)({
107
+ name: `interface DefinedEnumValues`,
108
+ lines: visited.enums.map(typeName => `${typeName}: ${printPicks(typeName, picks.enums)};`),
109
+ });
110
+ }
111
+ function encapsulateTypeName(typeName) {
112
+ if (encapsulate === 'prefix') {
113
+ return `${(0, change_case_all_1.pascalCase)(name)}_${typeName}`;
114
+ }
115
+ return typeName;
116
+ }
117
+ /**
118
+ * A dictionary of fields to pick from an input
119
+ */
120
+ function printDefinedInputFields() {
121
+ return (0, utils_js_1.buildBlock)({
122
+ name: `interface DefinedInputFields`,
123
+ lines: visited.inputs.map(typeName => `${typeName}: ${printPicks(typeName, picks.inputs)};`),
124
+ });
125
+ }
126
+ /**
127
+ * Prints signatures of schema types with picks
128
+ */
129
+ function printSchemaTypes(types) {
130
+ return types
131
+ .filter(type => !visited.scalars.includes(type))
132
+ .map(printExportType)
133
+ .join('\n');
134
+ }
135
+ function printResolveSignaturesPerType(registry) {
136
+ return [
137
+ [...registry.objects, ...registry.interfaces]
138
+ .map(name => printResolverType(name, 'DefinedFields', !rootTypes.includes(name) && defined.objects.includes(name) ? ` | '__isTypeOf'` : ''))
139
+ .join('\n'),
140
+ ].join('\n');
141
+ }
142
+ function printScalars(registry) {
143
+ if (!registry.scalars.length) {
144
+ return '';
145
+ }
146
+ return [
147
+ `export type ${encapsulateTypeName('Scalars')} = Pick<${importNamespace}.Scalars, ${registry.scalars
148
+ .map(utils_js_1.withQuotes)
149
+ .join(' | ')}>;`,
150
+ ...registry.scalars.map(scalar => {
151
+ const convertedName = baseVisitor.convertName(scalar, {
152
+ suffix: 'ScalarConfig',
153
+ });
154
+ return `export type ${encapsulateTypeName(convertedName)} = ${importNamespace}.${convertedName};`;
155
+ }),
156
+ ].join('\n');
157
+ }
158
+ /**
159
+ * Aggregation of type resolver signatures
160
+ */
161
+ function printResolversType(registry) {
162
+ const lines = [];
163
+ for (const kind in registry) {
164
+ const k = kind;
165
+ if (registry.hasOwnProperty(k) && resolverKeys.includes(k)) {
166
+ const types = registry[k];
167
+ types.forEach(typeName => {
168
+ if (k === 'enums') {
169
+ return;
170
+ }
171
+ if (k === 'scalars') {
172
+ lines.push(`${typeName}?: ${encapsulateTypeName(importNamespace)}.Resolvers['${typeName}'];`);
173
+ }
174
+ else {
175
+ lines.push(`${typeName}?: ${encapsulateTypeName(typeName)}Resolvers;`);
176
+ }
177
+ });
178
+ }
179
+ }
180
+ return (0, utils_js_1.buildBlock)({
181
+ name: `export interface ${encapsulateTypeName('Resolvers')}`,
182
+ lines,
183
+ });
184
+ }
185
+ /**
186
+ * Signature for a map of resolve middlewares
187
+ */
188
+ function printResolveMiddlewareMap() {
189
+ const wildcardField = printResolveMiddlewareRecord((0, utils_js_1.withQuotes)('*'));
190
+ const blocks = [(0, utils_js_1.buildBlock)({ name: `${(0, utils_js_1.withQuotes)('*')}?:`, lines: [wildcardField] })];
191
+ // Type.Field
192
+ for (const typeName in picks.objects) {
193
+ if (picks.objects.hasOwnProperty(typeName)) {
194
+ const fields = picks.objects[typeName];
195
+ const lines = [wildcardField].concat(fields.map(field => printResolveMiddlewareRecord(field)));
196
+ blocks.push((0, utils_js_1.buildBlock)({
197
+ name: `${typeName}?:`,
198
+ lines,
199
+ }));
200
+ }
201
+ }
202
+ return (0, utils_js_1.buildBlock)({
203
+ name: `export interface ${encapsulateTypeName('MiddlewareMap')}`,
204
+ lines: blocks,
205
+ });
206
+ }
207
+ function printResolveMiddlewareRecord(path) {
208
+ return `${path}?: gm.Middleware[];`;
209
+ }
210
+ function printResolverType(typeName, picksTypeName, extraKeys = '') {
211
+ return `export type ${encapsulateTypeName(`${typeName}Resolvers`)} = Pick<${importNamespace}.${baseVisitor.convertName(typeName, {
212
+ suffix: 'Resolvers',
213
+ })}, ${picksTypeName}['${typeName}']${extraKeys}>;`;
214
+ }
215
+ function printPicks(typeName, records) {
216
+ return records[typeName].filter(utils_js_1.unique).map(utils_js_1.withQuotes).join(' | ');
217
+ }
218
+ function printTypeBody(typeName) {
219
+ const coreType = `${importNamespace}.${baseVisitor.convertName(typeName, {
220
+ useTypesSuffix: true,
221
+ useTypesPrefix: true,
222
+ })}`;
223
+ if (external.enums.includes(typeName) || external.objects.includes(typeName)) {
224
+ if (schema && (0, graphql_1.isScalarType)(schema.getType(typeName))) {
225
+ return `${importNamespace}.Scalars['${typeName}']`;
226
+ }
227
+ return coreType;
228
+ }
229
+ if (defined.enums.includes(typeName) && picks.enums[typeName]) {
230
+ return `DefinedEnumValues['${typeName}']`;
231
+ }
232
+ if (defined.objects.includes(typeName) && picks.objects[typeName]) {
233
+ return `Pick<${coreType}, DefinedFields['${typeName}']>`;
234
+ }
235
+ if (defined.interfaces.includes(typeName) && picks.interfaces[typeName]) {
236
+ return `Pick<${coreType}, DefinedFields['${typeName}']>`;
237
+ }
238
+ if (defined.inputs.includes(typeName) && picks.inputs[typeName]) {
239
+ return `Pick<${coreType}, DefinedInputFields['${typeName}']>`;
240
+ }
241
+ return coreType;
242
+ }
243
+ function printExportType(typeName) {
244
+ return `export type ${encapsulateTypeName(typeName)} = ${printTypeBody(typeName)};`;
245
+ }
246
+ //
247
+ //
248
+ //
249
+ // Utils
250
+ //
251
+ //
252
+ //
253
+ function collectFields(node, picksObj) {
254
+ const name = node.name.value;
255
+ if (node.fields) {
256
+ if (!picksObj[name]) {
257
+ picksObj[name] = [];
258
+ }
259
+ node.fields.forEach(field => {
260
+ picksObj[name].push(field.name.value);
261
+ });
262
+ }
263
+ }
264
+ function collectValuesFromEnum(node) {
265
+ const name = node.name.value;
266
+ if (node.values) {
267
+ if (!picks.enums[name]) {
268
+ picks.enums[name] = [];
269
+ }
270
+ node.values.forEach(field => {
271
+ picks.enums[name].push(field.name.value);
272
+ });
273
+ }
274
+ }
275
+ function collectTypeDefinition(node) {
276
+ const name = node.name.value;
277
+ switch (node.kind) {
278
+ case graphql_1.Kind.OBJECT_TYPE_DEFINITION: {
279
+ defined.objects.push(name);
280
+ collectFields(node, picks.objects);
281
+ break;
282
+ }
283
+ case graphql_1.Kind.ENUM_TYPE_DEFINITION: {
284
+ defined.enums.push(name);
285
+ collectValuesFromEnum(node);
286
+ break;
287
+ }
288
+ case graphql_1.Kind.INPUT_OBJECT_TYPE_DEFINITION: {
289
+ defined.inputs.push(name);
290
+ collectFields(node, picks.inputs);
291
+ break;
292
+ }
293
+ case graphql_1.Kind.SCALAR_TYPE_DEFINITION: {
294
+ defined.scalars.push(name);
295
+ break;
296
+ }
297
+ case graphql_1.Kind.INTERFACE_TYPE_DEFINITION: {
298
+ defined.interfaces.push(name);
299
+ collectFields(node, picks.interfaces);
300
+ break;
301
+ }
302
+ case graphql_1.Kind.UNION_TYPE_DEFINITION: {
303
+ defined.unions.push(name);
304
+ break;
305
+ }
306
+ }
307
+ }
308
+ function collectTypeExtension(node) {
309
+ const name = node.name.value;
310
+ switch (node.kind) {
311
+ case graphql_1.Kind.OBJECT_TYPE_EXTENSION: {
312
+ collectFields(node, picks.objects);
313
+ // Do not include root types as extensions
314
+ // so we can use them in DefinedFields
315
+ if (rootTypes.includes(name)) {
316
+ (0, utils_js_1.pushUnique)(defined.objects, name);
317
+ return;
318
+ }
319
+ (0, utils_js_1.pushUnique)(extended.objects, name);
320
+ break;
321
+ }
322
+ case graphql_1.Kind.ENUM_TYPE_EXTENSION: {
323
+ collectValuesFromEnum(node);
324
+ (0, utils_js_1.pushUnique)(extended.enums, name);
325
+ break;
326
+ }
327
+ case graphql_1.Kind.INPUT_OBJECT_TYPE_EXTENSION: {
328
+ collectFields(node, picks.inputs);
329
+ (0, utils_js_1.pushUnique)(extended.inputs, name);
330
+ break;
331
+ }
332
+ case graphql_1.Kind.INTERFACE_TYPE_EXTENSION: {
333
+ collectFields(node, picks.interfaces);
334
+ (0, utils_js_1.pushUnique)(extended.interfaces, name);
335
+ break;
336
+ }
337
+ case graphql_1.Kind.UNION_TYPE_EXTENSION: {
338
+ (0, utils_js_1.pushUnique)(extended.unions, name);
339
+ break;
340
+ }
341
+ }
342
+ }
343
+ }
344
+ exports.buildModule = buildModule;
package/cjs/config.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/cjs/index.js ADDED
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.preset = void 0;
4
+ const graphql_1 = require("graphql");
5
+ const path_1 = require("path");
6
+ const utils_js_1 = require("./utils.js");
7
+ const builder_js_1 = require("./builder.js");
8
+ const visitor_plugin_common_1 = require("@graphql-codegen/visitor-plugin-common");
9
+ exports.preset = {
10
+ buildGeneratesSection: options => {
11
+ const useGraphQLModules = (0, visitor_plugin_common_1.getConfigValue)(options === null || options === void 0 ? void 0 : options.presetConfig.useGraphQLModules, true);
12
+ const { baseOutputDir } = options;
13
+ const { baseTypesPath, encapsulateModuleTypes } = options.presetConfig;
14
+ const cwd = (0, path_1.resolve)(options.presetConfig.cwd || process.cwd());
15
+ const importTypesNamespace = options.presetConfig.importTypesNamespace || 'Types';
16
+ if (!baseTypesPath) {
17
+ throw new Error(`Preset "graphql-modules" requires you to specify "baseTypesPath" configuration and point it to your base types file (generated by "typescript" plugin)!`);
18
+ }
19
+ if (!options.schemaAst || !options.schemaAst.extensions.sources) {
20
+ throw new Error(`Preset "graphql-modules" requires to use GraphQL SDL`);
21
+ }
22
+ const extensions = options.schemaAst.extensions;
23
+ const sourcesByModuleMap = (0, utils_js_1.groupSourcesByModule)(extensions.extendedSources, baseOutputDir);
24
+ const modules = Object.keys(sourcesByModuleMap);
25
+ const baseVisitor = new visitor_plugin_common_1.BaseVisitor(options.config, {});
26
+ // One file with an output from all plugins
27
+ const baseOutput = {
28
+ filename: (0, path_1.resolve)(cwd, baseOutputDir, baseTypesPath),
29
+ schema: options.schema,
30
+ documents: options.documents,
31
+ plugins: [
32
+ ...options.plugins,
33
+ {
34
+ 'modules-exported-scalars': {},
35
+ },
36
+ ],
37
+ pluginMap: {
38
+ ...options.pluginMap,
39
+ 'modules-exported-scalars': {
40
+ plugin: schema => {
41
+ const typeMap = schema.getTypeMap();
42
+ return Object.keys(typeMap)
43
+ .map(t => {
44
+ if (t && typeMap[t] && (0, graphql_1.isScalarType)(typeMap[t]) && !(0, utils_js_1.isGraphQLPrimitive)(t)) {
45
+ const convertedName = baseVisitor.convertName(t);
46
+ return `export type ${convertedName} = Scalars["${t}"];`;
47
+ }
48
+ return null;
49
+ })
50
+ .filter(Boolean)
51
+ .join('\n');
52
+ },
53
+ },
54
+ },
55
+ config: {
56
+ ...options.config,
57
+ enumsAsTypes: true,
58
+ },
59
+ schemaAst: options.schemaAst,
60
+ };
61
+ const baseTypesFilename = baseTypesPath.replace(/\.(js|ts|d.ts)$/, '');
62
+ const baseTypesDir = (0, utils_js_1.stripFilename)(baseOutput.filename);
63
+ // One file per each module
64
+ const outputs = modules.map(moduleName => {
65
+ const filename = (0, path_1.resolve)(cwd, baseOutputDir, moduleName, options.presetConfig.filename);
66
+ const dirpath = (0, utils_js_1.stripFilename)(filename);
67
+ const relativePath = (0, path_1.relative)(dirpath, baseTypesDir);
68
+ const importPath = options.presetConfig.importBaseTypesFrom || (0, utils_js_1.normalize)((0, path_1.join)(relativePath, baseTypesFilename));
69
+ const sources = sourcesByModuleMap[moduleName];
70
+ const moduleDocument = (0, graphql_1.concatAST)(sources.map(source => source.document));
71
+ const shouldDeclare = filename.endsWith('.d.ts');
72
+ return {
73
+ filename,
74
+ schema: options.schema,
75
+ documents: [],
76
+ plugins: [
77
+ ...options.plugins.filter(p => typeof p === 'object' && !!p.add),
78
+ {
79
+ 'graphql-modules-plugin': {},
80
+ },
81
+ ],
82
+ pluginMap: {
83
+ ...options.pluginMap,
84
+ 'graphql-modules-plugin': {
85
+ plugin: schema => {
86
+ var _a, _b, _c;
87
+ return (0, builder_js_1.buildModule)(moduleName, moduleDocument, {
88
+ importNamespace: importTypesNamespace,
89
+ importPath,
90
+ encapsulate: encapsulateModuleTypes || 'namespace',
91
+ shouldDeclare,
92
+ schema,
93
+ baseVisitor,
94
+ useGraphQLModules,
95
+ rootTypes: [
96
+ (_a = schema.getQueryType()) === null || _a === void 0 ? void 0 : _a.name,
97
+ (_b = schema.getMutationType()) === null || _b === void 0 ? void 0 : _b.name,
98
+ (_c = schema.getSubscriptionType()) === null || _c === void 0 ? void 0 : _c.name,
99
+ ].filter(Boolean),
100
+ });
101
+ },
102
+ },
103
+ },
104
+ config: options.config,
105
+ schemaAst: options.schemaAst,
106
+ };
107
+ });
108
+ return [baseOutput].concat(outputs);
109
+ },
110
+ };
111
+ exports.default = exports.preset;
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
package/cjs/utils.js ADDED
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createObject = exports.uniqueByKey = exports.concatByKey = exports.pushUnique = exports.normalize = exports.stripFilename = exports.groupSourcesByModule = exports.buildBlock = exports.indent = exports.withQuotes = exports.unique = exports.isGraphQLPrimitive = exports.resolveTypeNode = exports.collectUsedTypes = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const graphql_1 = require("graphql");
6
+ const parse_filepath_1 = tslib_1.__importDefault(require("parse-filepath"));
7
+ const sep = '/';
8
+ /**
9
+ * Searches every node to collect used types
10
+ */
11
+ function collectUsedTypes(doc) {
12
+ const used = [];
13
+ doc.definitions.forEach(findRelated);
14
+ function markAsUsed(type) {
15
+ pushUnique(used, type);
16
+ }
17
+ function findRelated(node) {
18
+ if (node.kind === graphql_1.Kind.OBJECT_TYPE_DEFINITION || node.kind === graphql_1.Kind.OBJECT_TYPE_EXTENSION) {
19
+ // Object
20
+ markAsUsed(node.name.value);
21
+ if (node.fields) {
22
+ node.fields.forEach(findRelated);
23
+ }
24
+ if (node.interfaces) {
25
+ node.interfaces.forEach(findRelated);
26
+ }
27
+ }
28
+ else if (node.kind === graphql_1.Kind.INPUT_OBJECT_TYPE_DEFINITION || node.kind === graphql_1.Kind.INPUT_OBJECT_TYPE_EXTENSION) {
29
+ // Input
30
+ markAsUsed(node.name.value);
31
+ if (node.fields) {
32
+ node.fields.forEach(findRelated);
33
+ }
34
+ }
35
+ else if (node.kind === graphql_1.Kind.INTERFACE_TYPE_DEFINITION || node.kind === graphql_1.Kind.INTERFACE_TYPE_EXTENSION) {
36
+ // Interface
37
+ markAsUsed(node.name.value);
38
+ if (node.fields) {
39
+ node.fields.forEach(findRelated);
40
+ }
41
+ if (node.interfaces) {
42
+ node.interfaces.forEach(findRelated);
43
+ }
44
+ }
45
+ else if (node.kind === graphql_1.Kind.UNION_TYPE_DEFINITION || node.kind === graphql_1.Kind.UNION_TYPE_EXTENSION) {
46
+ // Union
47
+ markAsUsed(node.name.value);
48
+ if (node.types) {
49
+ node.types.forEach(findRelated);
50
+ }
51
+ }
52
+ else if (node.kind === graphql_1.Kind.ENUM_TYPE_DEFINITION || node.kind === graphql_1.Kind.ENUM_TYPE_EXTENSION) {
53
+ // Enum
54
+ markAsUsed(node.name.value);
55
+ }
56
+ else if (node.kind === graphql_1.Kind.SCALAR_TYPE_DEFINITION || node.kind === graphql_1.Kind.SCALAR_TYPE_EXTENSION) {
57
+ // Scalar
58
+ if (!isGraphQLPrimitive(node.name.value)) {
59
+ markAsUsed(node.name.value);
60
+ }
61
+ }
62
+ else if (node.kind === graphql_1.Kind.INPUT_VALUE_DEFINITION) {
63
+ // Argument
64
+ findRelated(resolveTypeNode(node.type));
65
+ }
66
+ else if (node.kind === graphql_1.Kind.FIELD_DEFINITION) {
67
+ // Field
68
+ findRelated(resolveTypeNode(node.type));
69
+ if (node.arguments) {
70
+ node.arguments.forEach(findRelated);
71
+ }
72
+ }
73
+ else if (node.kind === graphql_1.Kind.NAMED_TYPE &&
74
+ // Named type
75
+ !isGraphQLPrimitive(node.name.value)) {
76
+ markAsUsed(node.name.value);
77
+ }
78
+ }
79
+ return used;
80
+ }
81
+ exports.collectUsedTypes = collectUsedTypes;
82
+ function resolveTypeNode(node) {
83
+ if (node.kind === graphql_1.Kind.LIST_TYPE) {
84
+ return resolveTypeNode(node.type);
85
+ }
86
+ if (node.kind === graphql_1.Kind.NON_NULL_TYPE) {
87
+ return resolveTypeNode(node.type);
88
+ }
89
+ return node;
90
+ }
91
+ exports.resolveTypeNode = resolveTypeNode;
92
+ function isGraphQLPrimitive(name) {
93
+ return ['String', 'Boolean', 'ID', 'Float', 'Int'].includes(name);
94
+ }
95
+ exports.isGraphQLPrimitive = isGraphQLPrimitive;
96
+ function unique(val, i, all) {
97
+ return i === all.indexOf(val);
98
+ }
99
+ exports.unique = unique;
100
+ function withQuotes(val) {
101
+ return `'${val}'`;
102
+ }
103
+ exports.withQuotes = withQuotes;
104
+ function indent(size) {
105
+ const space = new Array(size).fill(' ').join('');
106
+ function indentInner(val) {
107
+ return val
108
+ .split('\n')
109
+ .map(line => `${space}${line}`)
110
+ .join('\n');
111
+ }
112
+ return indentInner;
113
+ }
114
+ exports.indent = indent;
115
+ function buildBlock({ name, lines }) {
116
+ if (!lines.length) {
117
+ return '';
118
+ }
119
+ return [`${name} {`, ...lines.map(indent(2)), '};'].join('\n');
120
+ }
121
+ exports.buildBlock = buildBlock;
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
+ exports.groupSourcesByModule = groupSourcesByModule;
144
+ function extractModuleDirectory(filepath, basePath) {
145
+ const relativePath = getRelativePath(filepath, basePath);
146
+ const [moduleDirectory] = relativePath.split(sep);
147
+ return moduleDirectory;
148
+ }
149
+ function stripFilename(path) {
150
+ const parsedPath = (0, parse_filepath_1.default)(path);
151
+ return normalize(parsedPath.dir);
152
+ }
153
+ exports.stripFilename = stripFilename;
154
+ function normalize(path) {
155
+ return path.replace(/\\/g, '/');
156
+ }
157
+ exports.normalize = normalize;
158
+ function ensureEndsWithSeparator(path) {
159
+ return path.endsWith(sep) ? path : path + sep;
160
+ }
161
+ function ensureStartsWithSeparator(path) {
162
+ return path.startsWith('.') ? path.replace(/^(..\/)|(.\/)/, '/') : path.startsWith('/') ? path : '/' + path;
163
+ }
164
+ /**
165
+ * Pushes an item to a list only if the list doesn't include the item
166
+ */
167
+ function pushUnique(list, item) {
168
+ if (!list.includes(item)) {
169
+ list.push(item);
170
+ }
171
+ }
172
+ exports.pushUnique = pushUnique;
173
+ function concatByKey(left, right, key) {
174
+ // Remove duplicate, if an element is in right & left, it will be only once in the returned array.
175
+ return [...new Set([...left[key], ...right[key]])];
176
+ }
177
+ exports.concatByKey = concatByKey;
178
+ function uniqueByKey(left, right, key) {
179
+ return left[key].filter(item => !right[key].includes(item));
180
+ }
181
+ exports.uniqueByKey = uniqueByKey;
182
+ function createObject(keys, valueFn) {
183
+ const obj = {};
184
+ keys.forEach(key => {
185
+ obj[key] = valueFn(key);
186
+ });
187
+ return obj;
188
+ }
189
+ exports.createObject = createObject;