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