@graphql-tools/graphql-file-loader 6.2.7-alpha-523f2cce.0 → 6.2.7

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.esm.js CHANGED
@@ -1,734 +1,9 @@
1
- import { printSchemaWithDirectives, createSchemaDefinition, compareNodes, isNotEqual, isValidPath, parseGraphQLSDL } from '@graphql-tools/utils';
1
+ import { isValidPath, parseGraphQLSDL } from '@graphql-tools/utils';
2
2
  import { isAbsolute, resolve } from 'path';
3
3
  import { accessSync, readFileSync, promises } from 'fs';
4
4
  import { cwd } from 'process';
5
- import { Kind, visit, isSchema, parse, Source, getDescription, print, isExecutableDefinitionNode } from 'graphql';
6
5
  import { processImport } from '@graphql-tools/import';
7
6
 
8
- function mergeArguments(args1, args2, config) {
9
- const result = deduplicateArguments([].concat(args2, args1).filter(a => a));
10
- if (config && config.sort) {
11
- result.sort(compareNodes);
12
- }
13
- return result;
14
- }
15
- function deduplicateArguments(args) {
16
- return args.reduce((acc, current) => {
17
- const dup = acc.find(arg => arg.name.value === current.name.value);
18
- if (!dup) {
19
- return acc.concat([current]);
20
- }
21
- return acc;
22
- }, []);
23
- }
24
-
25
- let commentsRegistry = {};
26
- function resetComments() {
27
- commentsRegistry = {};
28
- }
29
- function collectComment(node) {
30
- const entityName = node.name.value;
31
- pushComment(node, entityName);
32
- switch (node.kind) {
33
- case 'EnumTypeDefinition':
34
- node.values.forEach(value => {
35
- pushComment(value, entityName, value.name.value);
36
- });
37
- break;
38
- case 'ObjectTypeDefinition':
39
- case 'InputObjectTypeDefinition':
40
- case 'InterfaceTypeDefinition':
41
- if (node.fields) {
42
- node.fields.forEach((field) => {
43
- pushComment(field, entityName, field.name.value);
44
- if (isFieldDefinitionNode(field) && field.arguments) {
45
- field.arguments.forEach(arg => {
46
- pushComment(arg, entityName, field.name.value, arg.name.value);
47
- });
48
- }
49
- });
50
- }
51
- break;
52
- }
53
- }
54
- function pushComment(node, entity, field, argument) {
55
- const comment = getDescription(node, { commentDescriptions: true });
56
- if (typeof comment !== 'string' || comment.length === 0) {
57
- return;
58
- }
59
- const keys = [entity];
60
- if (field) {
61
- keys.push(field);
62
- if (argument) {
63
- keys.push(argument);
64
- }
65
- }
66
- const path = keys.join('.');
67
- if (!commentsRegistry[path]) {
68
- commentsRegistry[path] = [];
69
- }
70
- commentsRegistry[path].push(comment);
71
- }
72
- function printComment(comment) {
73
- return '\n# ' + comment.replace(/\n/g, '\n# ');
74
- }
75
- /**
76
- * Copyright (c) 2015-present, Facebook, Inc.
77
- *
78
- * This source code is licensed under the MIT license found in the
79
- * LICENSE file in the root directory of this source tree.
80
- */
81
- /**
82
- * NOTE: ==> This file has been modified just to add comments to the printed AST
83
- * This is a temp measure, we will move to using the original non modified printer.js ASAP.
84
- */
85
- // import { visit, VisitFn } from 'graphql/language/visitor';
86
- /**
87
- * Given maybeArray, print an empty string if it is null or empty, otherwise
88
- * print all items together separated by separator if provided
89
- */
90
- function join(maybeArray, separator) {
91
- return maybeArray ? maybeArray.filter(x => x).join(separator || '') : '';
92
- }
93
- function addDescription(cb) {
94
- return (node, _key, _parent, path, ancestors) => {
95
- const keys = [];
96
- const parent = path.reduce((prev, key) => {
97
- if (['fields', 'arguments', 'values'].includes(key)) {
98
- keys.push(prev.name.value);
99
- }
100
- return prev[key];
101
- }, ancestors[0]);
102
- const key = [...keys, parent.name.value].join('.');
103
- const items = [];
104
- if (commentsRegistry[key]) {
105
- items.push(...commentsRegistry[key]);
106
- }
107
- return join([...items.map(printComment), node.description, cb(node)], '\n');
108
- };
109
- }
110
- function indent(maybeString) {
111
- return maybeString && ` ${maybeString.replace(/\n/g, '\n ')}`;
112
- }
113
- /**
114
- * Given array, print each item on its own line, wrapped in an
115
- * indented "{ }" block.
116
- */
117
- function block(array) {
118
- return array && array.length !== 0 ? `{\n${indent(join(array, '\n'))}\n}` : '';
119
- }
120
- /**
121
- * If maybeString is not null or empty, then wrap with start and end, otherwise
122
- * print an empty string.
123
- */
124
- function wrap(start, maybeString, end) {
125
- return maybeString ? start + maybeString + (end || '') : '';
126
- }
127
- /**
128
- * Print a block string in the indented block form by adding a leading and
129
- * trailing blank line. However, if a block string starts with whitespace and is
130
- * a single-line, adding a leading blank line would strip that whitespace.
131
- */
132
- function printBlockString(value, isDescription) {
133
- const escaped = value.replace(/"""/g, '\\"""');
134
- return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1
135
- ? `"""${escaped.replace(/"$/, '"\n')}"""`
136
- : `"""\n${isDescription ? escaped : indent(escaped)}\n"""`;
137
- }
138
- /**
139
- * Converts an AST into a string, using one set of reasonable
140
- * formatting rules.
141
- */
142
- function printWithComments(ast) {
143
- return visit(ast, {
144
- leave: {
145
- Name: node => node.value,
146
- Variable: node => `$${node.name}`,
147
- // Document
148
- Document: node => `${node.definitions
149
- .map(defNode => `${defNode}\n${defNode[0] === '#' ? '' : '\n'}`)
150
- .join('')
151
- .trim()}\n`,
152
- OperationTypeDefinition: node => `${node.operation}: ${node.type}`,
153
- VariableDefinition: ({ variable, type, defaultValue }) => `${variable}: ${type}${wrap(' = ', defaultValue)}`,
154
- SelectionSet: ({ selections }) => block(selections),
155
- Field: ({ alias, name, arguments: args, directives, selectionSet }) => join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' '),
156
- Argument: addDescription(({ name, value }) => `${name}: ${value}`),
157
- // Value
158
- IntValue: ({ value }) => value,
159
- FloatValue: ({ value }) => value,
160
- StringValue: ({ value, block: isBlockString }, key) => isBlockString ? printBlockString(value, key === 'description') : JSON.stringify(value),
161
- BooleanValue: ({ value }) => (value ? 'true' : 'false'),
162
- NullValue: () => 'null',
163
- EnumValue: ({ value }) => value,
164
- ListValue: ({ values }) => `[${join(values, ', ')}]`,
165
- ObjectValue: ({ fields }) => `{${join(fields, ', ')}}`,
166
- ObjectField: ({ name, value }) => `${name}: ${value}`,
167
- // Directive
168
- Directive: ({ name, arguments: args }) => `@${name}${wrap('(', join(args, ', '), ')')}`,
169
- // Type
170
- NamedType: ({ name }) => name,
171
- ListType: ({ type }) => `[${type}]`,
172
- NonNullType: ({ type }) => `${type}!`,
173
- // Type System Definitions
174
- SchemaDefinition: ({ directives, operationTypes }) => join(['schema', join(directives, ' '), block(operationTypes)], ' '),
175
- ScalarTypeDefinition: addDescription(({ name, directives }) => join(['scalar', name, join(directives, ' ')], ' ')),
176
- ObjectTypeDefinition: addDescription(({ name, interfaces, directives, fields }) => join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ')),
177
- FieldDefinition: addDescription(({ name, arguments: args, type, directives }) => `${name + wrap('(', join(args, ', '), ')')}: ${type}${wrap(' ', join(directives, ' '))}`),
178
- InputValueDefinition: addDescription(({ name, type, defaultValue, directives }) => join([`${name}: ${type}`, wrap('= ', defaultValue), join(directives, ' ')], ' ')),
179
- InterfaceTypeDefinition: addDescription(({ name, directives, fields }) => join(['interface', name, join(directives, ' '), block(fields)], ' ')),
180
- UnionTypeDefinition: addDescription(({ name, directives, types }) => join(['union', name, join(directives, ' '), types && types.length !== 0 ? `= ${join(types, ' | ')}` : ''], ' ')),
181
- EnumTypeDefinition: addDescription(({ name, directives, values }) => join(['enum', name, join(directives, ' '), block(values)], ' ')),
182
- EnumValueDefinition: addDescription(({ name, directives }) => join([name, join(directives, ' ')], ' ')),
183
- InputObjectTypeDefinition: addDescription(({ name, directives, fields }) => join(['input', name, join(directives, ' '), block(fields)], ' ')),
184
- ScalarTypeExtension: ({ name, directives }) => join(['extend scalar', name, join(directives, ' ')], ' '),
185
- ObjectTypeExtension: ({ name, interfaces, directives, fields }) => join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '),
186
- InterfaceTypeExtension: ({ name, directives, fields }) => join(['extend interface', name, join(directives, ' '), block(fields)], ' '),
187
- UnionTypeExtension: ({ name, directives, types }) => join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? `= ${join(types, ' | ')}` : ''], ' '),
188
- EnumTypeExtension: ({ name, directives, values }) => join(['extend enum', name, join(directives, ' '), block(values)], ' '),
189
- InputObjectTypeExtension: ({ name, directives, fields }) => join(['extend input', name, join(directives, ' '), block(fields)], ' '),
190
- DirectiveDefinition: addDescription(({ name, arguments: args, locations }) => `directive @${name}${wrap('(', join(args, ', '), ')')} on ${join(locations, ' | ')}`),
191
- },
192
- });
193
- }
194
- function isFieldDefinitionNode(node) {
195
- return node.kind === 'FieldDefinition';
196
- }
197
-
198
- function directiveAlreadyExists(directivesArr, otherDirective) {
199
- return !!directivesArr.find(directive => directive.name.value === otherDirective.name.value);
200
- }
201
- function nameAlreadyExists(name, namesArr) {
202
- return namesArr.some(({ value }) => value === name.value);
203
- }
204
- function mergeArguments$1(a1, a2) {
205
- const result = [...a2];
206
- for (const argument of a1) {
207
- const existingIndex = result.findIndex(a => a.name.value === argument.name.value);
208
- if (existingIndex > -1) {
209
- const existingArg = result[existingIndex];
210
- if (existingArg.value.kind === 'ListValue') {
211
- const source = existingArg.value.values;
212
- const target = argument.value.values;
213
- // merge values of two lists
214
- existingArg.value.values = deduplicateLists(source, target, (targetVal, source) => {
215
- const value = targetVal.value;
216
- return !value || !source.some((sourceVal) => sourceVal.value === value);
217
- });
218
- }
219
- else {
220
- existingArg.value = argument.value;
221
- }
222
- }
223
- else {
224
- result.push(argument);
225
- }
226
- }
227
- return result;
228
- }
229
- function deduplicateDirectives(directives) {
230
- return directives
231
- .map((directive, i, all) => {
232
- const firstAt = all.findIndex(d => d.name.value === directive.name.value);
233
- if (firstAt !== i) {
234
- const dup = all[firstAt];
235
- directive.arguments = mergeArguments$1(directive.arguments, dup.arguments);
236
- return null;
237
- }
238
- return directive;
239
- })
240
- .filter(d => d);
241
- }
242
- function mergeDirectives(d1 = [], d2 = [], config) {
243
- const reverseOrder = config && config.reverseDirectives;
244
- const asNext = reverseOrder ? d1 : d2;
245
- const asFirst = reverseOrder ? d2 : d1;
246
- const result = deduplicateDirectives([...asNext]);
247
- for (const directive of asFirst) {
248
- if (directiveAlreadyExists(result, directive)) {
249
- const existingDirectiveIndex = result.findIndex(d => d.name.value === directive.name.value);
250
- const existingDirective = result[existingDirectiveIndex];
251
- result[existingDirectiveIndex].arguments = mergeArguments$1(directive.arguments || [], existingDirective.arguments || []);
252
- }
253
- else {
254
- result.push(directive);
255
- }
256
- }
257
- return result;
258
- }
259
- function validateInputs(node, existingNode) {
260
- const printedNode = print(node);
261
- const printedExistingNode = print(existingNode);
262
- // eslint-disable-next-line
263
- const leaveInputs = new RegExp('(directive @w*d*)|( on .*$)', 'g');
264
- const sameArguments = printedNode.replace(leaveInputs, '') === printedExistingNode.replace(leaveInputs, '');
265
- if (!sameArguments) {
266
- throw new Error(`Unable to merge GraphQL directive "${node.name.value}". \nExisting directive: \n\t${printedExistingNode} \nReceived directive: \n\t${printedNode}`);
267
- }
268
- }
269
- function mergeDirective(node, existingNode) {
270
- if (existingNode) {
271
- validateInputs(node, existingNode);
272
- return {
273
- ...node,
274
- locations: [
275
- ...existingNode.locations,
276
- ...node.locations.filter(name => !nameAlreadyExists(name, existingNode.locations)),
277
- ],
278
- };
279
- }
280
- return node;
281
- }
282
- function deduplicateLists(source, target, filterFn) {
283
- return source.concat(target.filter(val => filterFn(val, source)));
284
- }
285
-
286
- function mergeEnumValues(first, second, config) {
287
- const enumValueMap = new Map();
288
- for (const firstValue of first) {
289
- enumValueMap.set(firstValue.name.value, firstValue);
290
- }
291
- for (const secondValue of second) {
292
- const enumValue = secondValue.name.value;
293
- if (enumValueMap.has(enumValue)) {
294
- const firstValue = enumValueMap.get(enumValue);
295
- firstValue.description = secondValue.description || firstValue.description;
296
- firstValue.directives = mergeDirectives(secondValue.directives, firstValue.directives);
297
- }
298
- else {
299
- enumValueMap.set(enumValue, secondValue);
300
- }
301
- }
302
- const result = [...enumValueMap.values()];
303
- if (config && config.sort) {
304
- result.sort(compareNodes);
305
- }
306
- return result;
307
- }
308
-
309
- function mergeEnum(e1, e2, config) {
310
- if (e2) {
311
- return {
312
- name: e1.name,
313
- description: e1['description'] || e2['description'],
314
- kind: (config && config.convertExtensions) || e1.kind === 'EnumTypeDefinition' || e2.kind === 'EnumTypeDefinition'
315
- ? 'EnumTypeDefinition'
316
- : 'EnumTypeExtension',
317
- loc: e1.loc,
318
- directives: mergeDirectives(e1.directives, e2.directives, config),
319
- values: mergeEnumValues(e1.values, e2.values, config),
320
- };
321
- }
322
- return config && config.convertExtensions
323
- ? {
324
- ...e1,
325
- kind: 'EnumTypeDefinition',
326
- }
327
- : e1;
328
- }
329
-
330
- function isStringTypes(types) {
331
- return typeof types === 'string';
332
- }
333
- function isSourceTypes(types) {
334
- return types instanceof Source;
335
- }
336
- function isGraphQLType(definition) {
337
- return definition.kind === 'ObjectTypeDefinition';
338
- }
339
- function isGraphQLTypeExtension(definition) {
340
- return definition.kind === 'ObjectTypeExtension';
341
- }
342
- function isGraphQLEnum(definition) {
343
- return definition.kind === 'EnumTypeDefinition';
344
- }
345
- function isGraphQLEnumExtension(definition) {
346
- return definition.kind === 'EnumTypeExtension';
347
- }
348
- function isGraphQLUnion(definition) {
349
- return definition.kind === 'UnionTypeDefinition';
350
- }
351
- function isGraphQLUnionExtension(definition) {
352
- return definition.kind === 'UnionTypeExtension';
353
- }
354
- function isGraphQLScalar(definition) {
355
- return definition.kind === 'ScalarTypeDefinition';
356
- }
357
- function isGraphQLScalarExtension(definition) {
358
- return definition.kind === 'ScalarTypeExtension';
359
- }
360
- function isGraphQLInputType(definition) {
361
- return definition.kind === 'InputObjectTypeDefinition';
362
- }
363
- function isGraphQLInputTypeExtension(definition) {
364
- return definition.kind === 'InputObjectTypeExtension';
365
- }
366
- function isGraphQLInterface(definition) {
367
- return definition.kind === 'InterfaceTypeDefinition';
368
- }
369
- function isGraphQLInterfaceExtension(definition) {
370
- return definition.kind === 'InterfaceTypeExtension';
371
- }
372
- function isGraphQLDirective(definition) {
373
- return definition.kind === 'DirectiveDefinition';
374
- }
375
- function extractType(type) {
376
- let visitedType = type;
377
- while (visitedType.kind === 'ListType' || visitedType.kind === 'NonNullType') {
378
- visitedType = visitedType.type;
379
- }
380
- return visitedType;
381
- }
382
- function isSchemaDefinition(node) {
383
- return node.kind === 'SchemaDefinition';
384
- }
385
- function isWrappingTypeNode(type) {
386
- return type.kind !== Kind.NAMED_TYPE;
387
- }
388
- function isListTypeNode(type) {
389
- return type.kind === Kind.LIST_TYPE;
390
- }
391
- function isNonNullTypeNode(type) {
392
- return type.kind === Kind.NON_NULL_TYPE;
393
- }
394
- function printTypeNode(type) {
395
- if (isListTypeNode(type)) {
396
- return `[${printTypeNode(type.type)}]`;
397
- }
398
- if (isNonNullTypeNode(type)) {
399
- return `${printTypeNode(type.type)}!`;
400
- }
401
- return type.name.value;
402
- }
403
-
404
- function fieldAlreadyExists(fieldsArr, otherField) {
405
- const result = fieldsArr.find(field => field.name.value === otherField.name.value);
406
- if (result) {
407
- const t1 = extractType(result.type);
408
- const t2 = extractType(otherField.type);
409
- if (t1.name.value !== t2.name.value) {
410
- throw new Error(`Field "${otherField.name.value}" already defined with a different type. Declared as "${t1.name.value}", but you tried to override with "${t2.name.value}"`);
411
- }
412
- }
413
- return !!result;
414
- }
415
- function mergeFields(type, f1, f2, config) {
416
- const result = [...f2];
417
- for (const field of f1) {
418
- if (fieldAlreadyExists(result, field)) {
419
- const existing = result.find((f) => f.name.value === field.name.value);
420
- if (config && config.throwOnConflict) {
421
- preventConflicts(type, existing, field, false);
422
- }
423
- else {
424
- preventConflicts(type, existing, field, true);
425
- }
426
- if (isNonNullTypeNode(field.type) && !isNonNullTypeNode(existing.type)) {
427
- existing.type = field.type;
428
- }
429
- existing.arguments = mergeArguments(field['arguments'] || [], existing.arguments || [], config);
430
- existing.directives = mergeDirectives(field.directives, existing.directives, config);
431
- existing.description = field.description || existing.description;
432
- }
433
- else {
434
- result.push(field);
435
- }
436
- }
437
- if (config && config.sort) {
438
- result.sort(compareNodes);
439
- }
440
- if (config && config.exclusions) {
441
- return result.filter(field => !config.exclusions.includes(`${type.name.value}.${field.name.value}`));
442
- }
443
- return result;
444
- }
445
- function preventConflicts(type, a, b, ignoreNullability = false) {
446
- const aType = printTypeNode(a.type);
447
- const bType = printTypeNode(b.type);
448
- if (isNotEqual(aType, bType)) {
449
- if (safeChangeForFieldType(a.type, b.type, ignoreNullability) === false) {
450
- throw new Error(`Field '${type.name.value}.${a.name.value}' changed type from '${aType}' to '${bType}'`);
451
- }
452
- }
453
- }
454
- function safeChangeForFieldType(oldType, newType, ignoreNullability = false) {
455
- // both are named
456
- if (!isWrappingTypeNode(oldType) && !isWrappingTypeNode(newType)) {
457
- return oldType.toString() === newType.toString();
458
- }
459
- // new is non-null
460
- if (isNonNullTypeNode(newType)) {
461
- const ofType = isNonNullTypeNode(oldType) ? oldType.type : oldType;
462
- return safeChangeForFieldType(ofType, newType.type);
463
- }
464
- // old is non-null
465
- if (isNonNullTypeNode(oldType)) {
466
- return safeChangeForFieldType(newType, oldType, ignoreNullability);
467
- }
468
- // old is list
469
- if (isListTypeNode(oldType)) {
470
- return ((isListTypeNode(newType) && safeChangeForFieldType(oldType.type, newType.type)) ||
471
- (isNonNullTypeNode(newType) && safeChangeForFieldType(oldType, newType['type'])));
472
- }
473
- return false;
474
- }
475
-
476
- function mergeInputType(node, existingNode, config) {
477
- if (existingNode) {
478
- try {
479
- return {
480
- name: node.name,
481
- description: node['description'] || existingNode['description'],
482
- kind: (config && config.convertExtensions) ||
483
- node.kind === 'InputObjectTypeDefinition' ||
484
- existingNode.kind === 'InputObjectTypeDefinition'
485
- ? 'InputObjectTypeDefinition'
486
- : 'InputObjectTypeExtension',
487
- loc: node.loc,
488
- fields: mergeFields(node, node.fields, existingNode.fields, config),
489
- directives: mergeDirectives(node.directives, existingNode.directives, config),
490
- };
491
- }
492
- catch (e) {
493
- throw new Error(`Unable to merge GraphQL input type "${node.name.value}": ${e.message}`);
494
- }
495
- }
496
- return config && config.convertExtensions
497
- ? {
498
- ...node,
499
- kind: 'InputObjectTypeDefinition',
500
- }
501
- : node;
502
- }
503
-
504
- function mergeInterface(node, existingNode, config) {
505
- if (existingNode) {
506
- try {
507
- return {
508
- name: node.name,
509
- description: node['description'] || existingNode['description'],
510
- kind: (config && config.convertExtensions) ||
511
- node.kind === 'InterfaceTypeDefinition' ||
512
- existingNode.kind === 'InterfaceTypeDefinition'
513
- ? 'InterfaceTypeDefinition'
514
- : 'InterfaceTypeExtension',
515
- loc: node.loc,
516
- fields: mergeFields(node, node.fields, existingNode.fields, config),
517
- directives: mergeDirectives(node.directives, existingNode.directives, config),
518
- };
519
- }
520
- catch (e) {
521
- throw new Error(`Unable to merge GraphQL interface "${node.name.value}": ${e.message}`);
522
- }
523
- }
524
- return config && config.convertExtensions
525
- ? {
526
- ...node,
527
- kind: 'InterfaceTypeDefinition',
528
- }
529
- : node;
530
- }
531
-
532
- function alreadyExists(arr, other) {
533
- return !!arr.find(i => i.name.value === other.name.value);
534
- }
535
- function mergeNamedTypeArray(first, second, config) {
536
- const result = [...second, ...first.filter(d => !alreadyExists(second, d))];
537
- if (config && config.sort) {
538
- result.sort(compareNodes);
539
- }
540
- return result;
541
- }
542
-
543
- function mergeType(node, existingNode, config) {
544
- if (existingNode) {
545
- try {
546
- return {
547
- name: node.name,
548
- description: node['description'] || existingNode['description'],
549
- kind: (config && config.convertExtensions) ||
550
- node.kind === 'ObjectTypeDefinition' ||
551
- existingNode.kind === 'ObjectTypeDefinition'
552
- ? 'ObjectTypeDefinition'
553
- : 'ObjectTypeExtension',
554
- loc: node.loc,
555
- fields: mergeFields(node, node.fields, existingNode.fields, config),
556
- directives: mergeDirectives(node.directives, existingNode.directives, config),
557
- interfaces: mergeNamedTypeArray(node.interfaces, existingNode.interfaces, config),
558
- };
559
- }
560
- catch (e) {
561
- throw new Error(`Unable to merge GraphQL type "${node.name.value}": ${e.message}`);
562
- }
563
- }
564
- return config && config.convertExtensions
565
- ? {
566
- ...node,
567
- kind: 'ObjectTypeDefinition',
568
- }
569
- : node;
570
- }
571
-
572
- function mergeScalar(node, existingNode, config) {
573
- if (existingNode) {
574
- return {
575
- name: node.name,
576
- description: node['description'] || existingNode['description'],
577
- kind: (config && config.convertExtensions) ||
578
- node.kind === 'ScalarTypeDefinition' ||
579
- existingNode.kind === 'ScalarTypeDefinition'
580
- ? 'ScalarTypeDefinition'
581
- : 'ScalarTypeExtension',
582
- loc: node.loc,
583
- directives: mergeDirectives(node.directives, existingNode.directives, config),
584
- };
585
- }
586
- return config && config.convertExtensions
587
- ? {
588
- ...node,
589
- kind: 'ScalarTypeDefinition',
590
- }
591
- : node;
592
- }
593
-
594
- function mergeUnion(first, second, config) {
595
- if (second) {
596
- return {
597
- name: first.name,
598
- description: first['description'] || second['description'],
599
- directives: mergeDirectives(first.directives, second.directives, config),
600
- kind: (config && config.convertExtensions) ||
601
- first.kind === 'UnionTypeDefinition' ||
602
- second.kind === 'UnionTypeDefinition'
603
- ? 'UnionTypeDefinition'
604
- : 'UnionTypeExtension',
605
- loc: first.loc,
606
- types: mergeNamedTypeArray(first.types, second.types, config),
607
- };
608
- }
609
- return config && config.convertExtensions
610
- ? {
611
- ...first,
612
- kind: 'UnionTypeDefinition',
613
- }
614
- : first;
615
- }
616
-
617
- function mergeGraphQLNodes(nodes, config) {
618
- return nodes.reduce((prev, nodeDefinition) => {
619
- const node = nodeDefinition;
620
- if (node && node.name && node.name.value) {
621
- const name = node.name.value;
622
- if (config && config.commentDescriptions) {
623
- collectComment(node);
624
- }
625
- if (config &&
626
- config.exclusions &&
627
- (config.exclusions.includes(name + '.*') || config.exclusions.includes(name))) {
628
- delete prev[name];
629
- }
630
- else if (isGraphQLType(nodeDefinition) || isGraphQLTypeExtension(nodeDefinition)) {
631
- prev[name] = mergeType(nodeDefinition, prev[name], config);
632
- }
633
- else if (isGraphQLEnum(nodeDefinition) || isGraphQLEnumExtension(nodeDefinition)) {
634
- prev[name] = mergeEnum(nodeDefinition, prev[name], config);
635
- }
636
- else if (isGraphQLUnion(nodeDefinition) || isGraphQLUnionExtension(nodeDefinition)) {
637
- prev[name] = mergeUnion(nodeDefinition, prev[name], config);
638
- }
639
- else if (isGraphQLScalar(nodeDefinition) || isGraphQLScalarExtension(nodeDefinition)) {
640
- prev[name] = mergeScalar(nodeDefinition, prev[name], config);
641
- }
642
- else if (isGraphQLInputType(nodeDefinition) || isGraphQLInputTypeExtension(nodeDefinition)) {
643
- prev[name] = mergeInputType(nodeDefinition, prev[name], config);
644
- }
645
- else if (isGraphQLInterface(nodeDefinition) || isGraphQLInterfaceExtension(nodeDefinition)) {
646
- prev[name] = mergeInterface(nodeDefinition, prev[name], config);
647
- }
648
- else if (isGraphQLDirective(nodeDefinition)) {
649
- prev[name] = mergeDirective(nodeDefinition, prev[name]);
650
- }
651
- }
652
- return prev;
653
- }, {});
654
- }
655
-
656
- function mergeTypeDefs(types, config) {
657
- resetComments();
658
- const doc = {
659
- kind: Kind.DOCUMENT,
660
- definitions: mergeGraphQLTypes(types, {
661
- useSchemaDefinition: true,
662
- forceSchemaDefinition: false,
663
- throwOnConflict: false,
664
- commentDescriptions: false,
665
- ...config,
666
- }),
667
- };
668
- let result;
669
- if (config && config.commentDescriptions) {
670
- result = printWithComments(doc);
671
- }
672
- else {
673
- result = doc;
674
- }
675
- resetComments();
676
- return result;
677
- }
678
- function mergeGraphQLTypes(types, config) {
679
- resetComments();
680
- const allNodes = types
681
- .map(type => {
682
- if (Array.isArray(type)) {
683
- type = mergeTypeDefs(type);
684
- }
685
- if (isSchema(type)) {
686
- return parse(printSchemaWithDirectives(type));
687
- }
688
- else if (isStringTypes(type) || isSourceTypes(type)) {
689
- return parse(type);
690
- }
691
- return type;
692
- })
693
- .map(ast => ast.definitions)
694
- .reduce((defs, newDef = []) => [...defs, ...newDef], []);
695
- // XXX: right now we don't handle multiple schema definitions
696
- let schemaDef = allNodes.filter(isSchemaDefinition).reduce((def, node) => {
697
- node.operationTypes
698
- .filter(op => op.type.name.value)
699
- .forEach(op => {
700
- def[op.operation] = op.type.name.value;
701
- });
702
- return def;
703
- }, {
704
- query: null,
705
- mutation: null,
706
- subscription: null,
707
- });
708
- const mergedNodes = mergeGraphQLNodes(allNodes, config);
709
- const allTypes = Object.keys(mergedNodes);
710
- if (config && config.sort) {
711
- allTypes.sort(typeof config.sort === 'function' ? config.sort : undefined);
712
- }
713
- if (config && config.useSchemaDefinition) {
714
- const queryType = schemaDef.query ? schemaDef.query : allTypes.find(t => t === 'Query');
715
- const mutationType = schemaDef.mutation ? schemaDef.mutation : allTypes.find(t => t === 'Mutation');
716
- const subscriptionType = schemaDef.subscription ? schemaDef.subscription : allTypes.find(t => t === 'Subscription');
717
- schemaDef = {
718
- query: queryType,
719
- mutation: mutationType,
720
- subscription: subscriptionType,
721
- };
722
- }
723
- const schemaDefinition = createSchemaDefinition(schemaDef, {
724
- force: config.forceSchemaDefinition,
725
- });
726
- if (!schemaDefinition) {
727
- return Object.values(mergedNodes);
728
- }
729
- return [...Object.values(mergedNodes), parse(schemaDefinition).definitions[0]];
730
- }
731
-
732
7
  const { readFile, access } = promises;
733
8
  const FILE_EXTENSIONS = ['.gql', '.gqls', '.graphql', '.graphqls'];
734
9
  function isGraphQLImportFile(rawSDL) {
@@ -805,20 +80,9 @@ class GraphQLFileLoader {
805
80
  handleFileContent(rawSDL, pointer, options) {
806
81
  if (!options.skipGraphQLImport && isGraphQLImportFile(rawSDL)) {
807
82
  const document = processImport(pointer, options.cwd);
808
- const typeSystemDefinitions = document.definitions
809
- .filter(d => !isExecutableDefinitionNode(d))
810
- .map(definition => ({
811
- kind: Kind.DOCUMENT,
812
- definitions: [definition],
813
- }));
814
- const mergedTypeDefs = mergeTypeDefs(typeSystemDefinitions, { useSchemaDefinition: false });
815
- const executableDefinitions = document.definitions.filter(isExecutableDefinitionNode);
816
83
  return {
817
84
  location: pointer,
818
- document: {
819
- ...mergedTypeDefs,
820
- definitions: [...mergedTypeDefs.definitions, ...executableDefinitions],
821
- },
85
+ document,
822
86
  };
823
87
  }
824
88
  return parseGraphQLSDL(pointer, rawSDL, options);