-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathutils.ts
More file actions
799 lines (751 loc) · 26.4 KB
/
utils.ts
File metadata and controls
799 lines (751 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
import {
type BooleanValueNode,
type ConstDirectiveNode,
type ConstValueNode,
DEFAULT_DEPRECATION_REASON,
type DefinitionNode,
type DirectiveDefinitionNode,
type EnumValueDefinitionNode,
type EnumValueNode,
type FieldDefinitionNode,
type FloatValueNode,
type InputValueDefinitionNode,
type IntValueNode,
Kind,
type NullValueNode,
OperationTypeNode,
print,
type StringValueNode,
type TypeNode,
} from 'graphql';
import {
type AuthorizationData,
type ChildData,
type CompositeOutputData,
type ConditionalFieldData,
type DefinitionData,
ExtensionType,
type ExternalFieldData,
type FieldData,
type InputObjectDefinitionData,
type InputValueData,
type InterfaceDefinitionData,
type NodeData,
type ObjectDefinitionData,
type ParentDefinitionData,
type PersistedDirectiveDefinitionData,
type PersistedDirectivesData,
type SchemaData,
} from './types';
import { type MutableDefinitionNode, type MutableFieldNode, type MutableInputValueNode } from './ast';
import {
type InterfaceTypeNode,
type ObjectTypeNode,
type ParentTypeNode,
setToNameNodeArray,
stringToNameNode,
} from '../ast/utils';
import {
incompatibleInputValueDefaultValuesError,
invalidRepeatedFederatedDirectiveErrorMessage,
invalidRequiredInputValueError,
} from '../errors/errors';
import { type SubscriptionFilterValue } from '../router-configuration/types';
import {
ARGUMENT,
AUTHENTICATED,
BOOLEAN_SCALAR,
DEPRECATED,
DEPRECATED_DEFAULT_ARGUMENT_VALUE,
DIRECTIVE_DEFINITION,
EXTERNAL,
FLOAT_SCALAR,
INACCESSIBLE,
INPUT_FIELD,
INPUT_NODE_KINDS,
INT_SCALAR,
INTERFACE_NODE_KINDS,
MUTATION,
OUTPUT_NODE_KINDS,
PERSISTED_CLIENT_DIRECTIVES,
QUERY,
REASON,
REQUIRES_SCOPES,
ROOT_TYPE_NAMES,
SEMANTIC_NON_NULL,
SHAREABLE,
STRING_SCALAR,
SUBSCRIPTION,
} from '../utils/string-constants';
import {
generateRequiresScopesDirective,
generateSemanticNonNullDirective,
generateSimpleDirective,
getEntriesNotInHashSet,
getFirstEntry,
} from '../utils/utils';
import { type InputNodeKind, type InvalidRequiredInputValueData, type OutputNodeKind } from '../utils/types';
import { getDescriptionFromString } from '../v1/federation/utils';
import { type DirectiveName, type FieldName, type SubgraphName, type TypeName } from '../types/types';
import { type IsTypeValidImplementationParams } from './params';
export function newPersistedDirectivesData(): PersistedDirectivesData {
return {
deprecatedReason: '',
directivesByName: new Map<DirectiveName, Array<ConstDirectiveNode>>(),
isDeprecated: false,
tagDirectiveByName: new Map<string, ConstDirectiveNode>(),
};
}
type IsNodeExternalOrShareableResult = {
isExternal: boolean;
isShareable: boolean;
};
export function isNodeExternalOrShareable(
node: ObjectTypeNode | FieldDefinitionNode,
areAllFieldsShareable: boolean,
directivesByName: Map<DirectiveName, Array<ConstDirectiveNode>>,
): IsNodeExternalOrShareableResult {
const result: IsNodeExternalOrShareableResult = {
isExternal: directivesByName.has(EXTERNAL),
isShareable: areAllFieldsShareable || directivesByName.has(SHAREABLE),
};
if (!node.directives?.length) {
return result;
}
for (const directiveNode of node.directives) {
const directiveName = directiveNode.name.value;
if (directiveName === EXTERNAL) {
result.isExternal = true;
continue;
}
if (directiveName === SHAREABLE) {
result.isShareable = true;
}
}
return result;
}
export function isTypeRequired(node: TypeNode): boolean {
return node.kind === Kind.NON_NULL_TYPE;
}
export function isTypeNodeListType(node: TypeNode): boolean {
switch (node.kind) {
case Kind.LIST_TYPE:
return true;
case Kind.NON_NULL_TYPE:
return isTypeNodeListType(node.type);
default:
return false;
}
}
// TODO replace naïve comparison
export function areDefaultValuesCompatible(typeNode: TypeNode, incomingDefaultValue: ConstValueNode): boolean {
switch (typeNode.kind) {
case Kind.LIST_TYPE:
return incomingDefaultValue.kind === Kind.LIST || incomingDefaultValue.kind === Kind.NULL;
case Kind.NAMED_TYPE:
if (incomingDefaultValue.kind === Kind.NULL) {
return true;
}
switch (typeNode.name.value) {
case BOOLEAN_SCALAR:
return incomingDefaultValue.kind === Kind.BOOLEAN;
case FLOAT_SCALAR:
return incomingDefaultValue.kind === Kind.INT || incomingDefaultValue.kind === Kind.FLOAT;
case INT_SCALAR:
return incomingDefaultValue.kind === Kind.INT;
case STRING_SCALAR:
return incomingDefaultValue.kind === Kind.STRING;
default:
return true;
}
case Kind.NON_NULL_TYPE:
if (incomingDefaultValue.kind === Kind.NULL) {
return false;
}
return areDefaultValuesCompatible(typeNode.type, incomingDefaultValue);
}
}
export function compareAndValidateInputValueDefaultValues(
existingData: InputValueData,
incomingData: InputValueData,
errors: Error[],
) {
if (!existingData.defaultValue) {
// TODO warning if default value in incoming
return;
}
if (!incomingData.defaultValue) {
// TODO warning
existingData.includeDefaultValue = false;
return;
}
const existingDefaultValueString = print(existingData.defaultValue);
const incomingDefaultValueString = print(incomingData.defaultValue);
if (existingDefaultValueString !== incomingDefaultValueString) {
errors.push(
incompatibleInputValueDefaultValuesError(
`${existingData.isArgument ? ARGUMENT : INPUT_FIELD} "${existingData.name}"`,
existingData.originalCoords,
[...incomingData.subgraphNames],
existingDefaultValueString,
incomingDefaultValueString,
),
);
return;
}
}
export function setMutualExecutableLocations(
persistedDirectiveDefinitionData: PersistedDirectiveDefinitionData,
incomingExecutableLocations: Set<string>,
) {
const mutualExecutableLocations = new Set<string>();
for (const incomingExecutableLocation of incomingExecutableLocations) {
if (persistedDirectiveDefinitionData.executableLocations.has(incomingExecutableLocation)) {
mutualExecutableLocations.add(incomingExecutableLocation);
}
}
persistedDirectiveDefinitionData.executableLocations = mutualExecutableLocations;
}
export function isTypeNameRootType(typeName: string, operationByTypeName: Map<TypeName, OperationTypeNode>) {
return ROOT_TYPE_NAMES.has(typeName) || operationByTypeName.has(typeName);
}
export function getRenamedRootTypeName(
typeName: string,
operationByTypeName: Map<TypeName, OperationTypeNode>,
): string {
const operationTypeNode = operationByTypeName.get(typeName);
if (!operationTypeNode) {
return typeName;
}
switch (operationTypeNode) {
case OperationTypeNode.MUTATION:
return MUTATION;
case OperationTypeNode.SUBSCRIPTION:
return SUBSCRIPTION;
default:
return QUERY;
}
}
type ChildDefinitionNode = EnumValueDefinitionNode | FieldDefinitionNode | InputValueDefinitionNode;
function propagateFieldDataArguments(fieldData: FieldData) {
for (const argumentData of fieldData.argumentDataByName.values()) {
// First propagate the argument's directives
for (const directiveNodes of argumentData.directivesByName.values()) {
argumentData.node.directives.push(...directiveNodes);
}
fieldData.node.arguments.push(argumentData.node);
}
}
export function childMapToValueArray<T extends ChildData, U extends ChildDefinitionNode = T['node']>(
map: Map<string, T>,
): Array<U> {
const valueArray: Array<ChildDefinitionNode> = [];
for (const childData of map.values()) {
if (isFieldData(childData)) {
propagateFieldDataArguments(childData);
}
for (const [directiveName, directiveNodes] of childData.directivesByName) {
if (directiveName === DEPRECATED) {
// @deprecated is non-repeatable
const directiveNode = directiveNodes[0];
if (!directiveNode) {
continue;
}
if (directiveNode.arguments?.length) {
childData.node.directives.push(directiveNode);
continue;
}
childData.node.directives.push({
...directiveNode,
arguments: [
{
kind: Kind.ARGUMENT,
value: {
kind: Kind.STRING,
value: DEFAULT_DEPRECATION_REASON,
},
name: stringToNameNode(REASON),
},
],
});
continue;
}
childData.node.directives.push(...directiveNodes);
}
valueArray.push(childData.node);
}
return valueArray as Array<U>;
}
export function setLongestDescription(existingData: DefinitionData, incomingData: DefinitionData) {
if (!incomingData.description) {
return;
}
if ('configureDescriptionDataBySubgraphName' in incomingData) {
// There should be only be an incoming value for a single subgraph
for (const { propagate } of incomingData.configureDescriptionDataBySubgraphName.values()) {
if (!propagate) {
return;
}
}
}
if (!existingData.description || existingData.description.value.length < incomingData.description.value.length) {
existingData.description = { ...incomingData.description, block: true };
}
}
export function isParentDataRootType(parentData: ParentDefinitionData): boolean {
if (parentData.kind !== Kind.OBJECT_TYPE_DEFINITION) {
return false;
}
return parentData.isRootType;
}
export function isInterfaceDefinitionData(data: ParentDefinitionData): data is InterfaceDefinitionData {
return data.kind === Kind.INTERFACE_TYPE_DEFINITION;
}
export function setParentDataExtensionType(existingData: ParentDefinitionData, incomingData: ParentDefinitionData) {
if (existingData.extensionType === incomingData.extensionType || existingData.extensionType === ExtensionType.NONE) {
return;
}
if (incomingData.extensionType !== ExtensionType.NONE && !isParentDataRootType(incomingData)) {
return;
}
// Root types do not create errors even if all are instances are extensions.
existingData.extensionType = ExtensionType.NONE;
}
export function upsertDeprecatedDirective(
persistedDirectivesData: PersistedDirectivesData,
incomingDirectiveNode: ConstDirectiveNode,
) {
if (!incomingDirectiveNode.arguments?.length) {
return;
}
// The argument was already validated in the normalization factory, so it can be safely cast
const incomingReasonString = (incomingDirectiveNode.arguments[0].value as StringValueNode).value;
if (persistedDirectivesData.deprecatedReason.length < incomingReasonString.length) {
persistedDirectivesData.deprecatedReason = incomingReasonString;
}
}
export function upsertTagDirectives(
persistedDirectivesData: PersistedDirectivesData,
incomingDirectiveNodes: ConstDirectiveNode[],
) {
for (const incomingDirectiveNode of incomingDirectiveNodes) {
// The argument was already validated in the normalization factory, so it can be safely cast
const incomingNameString = (incomingDirectiveNode.arguments![0].value as StringValueNode).value;
persistedDirectivesData.tagDirectiveByName.set(incomingNameString, incomingDirectiveNode);
}
}
export function propagateAuthDirectives(parentData: ParentDefinitionData, authData?: AuthorizationData) {
if (!authData) {
return;
}
if (authData.requiresAuthentication) {
parentData.persistedDirectivesData.directivesByName.set(AUTHENTICATED, [generateSimpleDirective(AUTHENTICATED)]);
}
if (authData.requiredScopes.length > 0) {
parentData.persistedDirectivesData.directivesByName.set(REQUIRES_SCOPES, [
generateRequiresScopesDirective(authData.requiredScopes),
]);
}
}
export function propagateFieldAuthDirectives(fieldData: FieldData, authData?: AuthorizationData) {
if (!authData) {
return;
}
const fieldAuthData = authData.fieldAuthDataByFieldName.get(fieldData.name);
if (!fieldAuthData) {
return;
}
if (fieldAuthData.originalData.requiresAuthentication) {
fieldData.persistedDirectivesData.directivesByName.set(AUTHENTICATED, [generateSimpleDirective(AUTHENTICATED)]);
}
if (fieldAuthData.originalData.requiredScopes.length > 0) {
fieldData.persistedDirectivesData.directivesByName.set(REQUIRES_SCOPES, [
generateRequiresScopesDirective(fieldAuthData.originalData.requiredScopes),
]);
}
}
export function generateDeprecatedDirective(reason: string): ConstDirectiveNode {
return {
kind: Kind.DIRECTIVE,
name: stringToNameNode(DEPRECATED),
arguments: [
{
kind: Kind.ARGUMENT,
name: stringToNameNode(REASON),
value: {
kind: Kind.STRING,
value: reason || DEPRECATED_DEFAULT_ARGUMENT_VALUE, // use the default value if reason is empty
},
},
],
};
}
function getValidFlattenedPersistedDirectiveNodeArray(
directivesByName: Map<DirectiveName, Array<ConstDirectiveNode>>,
persistedDirectiveDefinitionByName: Map<DirectiveName, DirectiveDefinitionNode>,
directiveCoords: string,
errors: Error[],
): ConstDirectiveNode[] {
const persistedDirectiveNodes: Array<ConstDirectiveNode> = [];
for (const [directiveName, directiveNodes] of directivesByName) {
const persistedDirectiveDefinition = persistedDirectiveDefinitionByName.get(directiveName);
if (!persistedDirectiveDefinition) {
continue;
}
if (directiveNodes.length < 2) {
persistedDirectiveNodes.push(...directiveNodes);
continue;
}
if (!persistedDirectiveDefinition.repeatable) {
errors.push(invalidRepeatedFederatedDirectiveErrorMessage(directiveName, directiveCoords));
continue;
}
persistedDirectiveNodes.push(...directiveNodes);
}
return persistedDirectiveNodes;
}
function getRouterPersistedDirectiveNodes<T extends NodeData>(
nodeData: T,
persistedDirectiveDefinitionByName: Map<DirectiveName, DirectiveDefinitionNode>,
errors: Error[],
): ConstDirectiveNode[] {
const persistedDirectiveNodes = [...nodeData.persistedDirectivesData.tagDirectiveByName.values()];
if (nodeData.persistedDirectivesData.isDeprecated) {
persistedDirectiveNodes.push(generateDeprecatedDirective(nodeData.persistedDirectivesData.deprecatedReason));
}
persistedDirectiveNodes.push(
...getValidFlattenedPersistedDirectiveNodeArray(
nodeData.persistedDirectivesData.directivesByName,
persistedDirectiveDefinitionByName,
nodeData.name,
errors,
),
);
return persistedDirectiveNodes;
}
export function getClientPersistedDirectiveNodes<T extends NodeData>(nodeData: T): ConstDirectiveNode[] {
const persistedDirectiveNodes: Array<ConstDirectiveNode> = [];
if (nodeData.persistedDirectivesData.isDeprecated) {
persistedDirectiveNodes.push(generateDeprecatedDirective(nodeData.persistedDirectivesData.deprecatedReason));
}
for (const [directiveName, directiveNodes] of nodeData.persistedDirectivesData.directivesByName) {
if (directiveName === SEMANTIC_NON_NULL && isFieldData(nodeData)) {
persistedDirectiveNodes.push(
generateSemanticNonNullDirective(getFirstEntry(nodeData.nullLevelsBySubgraphName) ?? new Set<number>([0])),
);
continue;
}
// Only include @deprecated, @oneOf, and @semanticNonNull in the client schema.
if (!PERSISTED_CLIENT_DIRECTIVES.has(directiveName)) {
continue;
}
/* Persisted client-facing directives are all non-repeatable.
** The directive is validated against the definition when creating the router schema node, so it is not necessary
** to validate again. */
persistedDirectiveNodes.push(directiveNodes[0]);
}
return persistedDirectiveNodes;
}
export function getClientSchemaFieldNodeByFieldData(fieldData: FieldData): MutableFieldNode {
const directives = getClientPersistedDirectiveNodes(fieldData);
const argumentNodes: MutableInputValueNode[] = [];
for (const inputValueData of fieldData.argumentDataByName.values()) {
if (isNodeDataInaccessible(inputValueData)) {
continue;
}
argumentNodes.push({
...inputValueData.node,
directives: getClientPersistedDirectiveNodes(inputValueData),
});
}
return {
...fieldData.node,
directives,
arguments: argumentNodes,
};
}
export function getNodeWithPersistedDirectivesByInputValueData(
inputValueData: InputValueData,
persistedDirectiveDefinitionByDirectiveName: Map<DirectiveName, DirectiveDefinitionNode>,
errors: Error[],
): MutableInputValueNode {
inputValueData.node.name = stringToNameNode(inputValueData.name);
inputValueData.node.type = inputValueData.type;
inputValueData.node.description = inputValueData.description;
inputValueData.node.directives = getRouterPersistedDirectiveNodes(
inputValueData,
persistedDirectiveDefinitionByDirectiveName,
errors,
);
if (inputValueData.includeDefaultValue) {
inputValueData.node.defaultValue = inputValueData.defaultValue;
}
return inputValueData.node;
}
function addValidatedArgumentNodes(
argumentNodes: MutableInputValueNode[],
hostData: PersistedDirectiveDefinitionData,
persistedDirectiveDefinitionByDirectiveName: Map<DirectiveName, DirectiveDefinitionNode>,
errors: Error[],
argumentNamesForFieldConfiguration?: Set<string>,
): boolean {
const invalidRequiredArgumentErrors: InvalidRequiredInputValueData[] = [];
for (const [argumentName, argumentData] of hostData.argumentDataByName) {
const missingSubgraphs = getEntriesNotInHashSet(hostData.subgraphNames, argumentData.subgraphNames);
if (missingSubgraphs.length > 0) {
// Required arguments must be defined in all subgraphs that define the field
if (argumentData.requiredSubgraphNames.size > 0) {
invalidRequiredArgumentErrors.push({
inputValueName: argumentName,
missingSubgraphs,
requiredSubgraphs: [...argumentData.requiredSubgraphNames],
});
}
/* If the argument is always optional, but it's not defined in all subgraphs that define the field,
the argument should not be included in the federated graph */
continue;
}
argumentNodes.push(
getNodeWithPersistedDirectivesByInputValueData(argumentData, persistedDirectiveDefinitionByDirectiveName, errors),
);
if (argumentNamesForFieldConfiguration) {
argumentNamesForFieldConfiguration.add(argumentName);
}
}
if (invalidRequiredArgumentErrors.length > 0) {
errors.push(
invalidRequiredInputValueError(DIRECTIVE_DEFINITION, `@${hostData.name}`, invalidRequiredArgumentErrors),
);
return false;
}
return true;
}
export function addValidPersistedDirectiveDefinitionNodeByData(
definitions: (MutableDefinitionNode | DefinitionNode)[],
data: PersistedDirectiveDefinitionData,
persistedDirectiveDefinitionByDirectiveName: Map<DirectiveName, DirectiveDefinitionNode>,
errors: Error[],
) {
const argumentNodes: MutableInputValueNode[] = [];
if (!addValidatedArgumentNodes(argumentNodes, data, persistedDirectiveDefinitionByDirectiveName, errors)) {
return;
}
definitions.push({
arguments: argumentNodes,
kind: Kind.DIRECTIVE_DEFINITION,
locations: setToNameNodeArray(data.executableLocations),
name: stringToNameNode(data.name),
repeatable: data.repeatable,
description: data.description,
});
}
type InvalidFieldNames = {
byShareable: Set<string>;
subgraphNamesByExternalFieldName: Map<FieldName, Array<SubgraphName>>;
};
export function newInvalidFieldNames() {
return {
byShareable: new Set<string>(),
subgraphNamesByExternalFieldName: new Map<FieldName, Array<SubgraphName>>(),
};
}
export function validateExternalAndShareable(fieldData: FieldData, invalidFieldNames: InvalidFieldNames) {
// fieldData.subgraphNames.size is not used due to overridden fields
const instances = fieldData.isShareableBySubgraphName.size;
let externalFieldSubgraphNames = new Array<SubgraphName>();
let unshareableFields = 0;
for (const [subgraphName, isShareable] of fieldData.isShareableBySubgraphName) {
/*
* shareability is ignored if:
* 1. the field is external
* 2. the field is overridden by another subgraph (in which case it has not been upserted)
*/
const externalFieldData = fieldData.externalFieldDataBySubgraphName.get(subgraphName);
if (externalFieldData && !externalFieldData.isUnconditionallyProvided) {
externalFieldSubgraphNames.push(subgraphName);
continue;
}
if (isShareable) {
continue;
}
unshareableFields += 1;
}
switch (unshareableFields) {
case 0:
// At least one instance of a field must be non-external
if (instances === externalFieldSubgraphNames.length) {
invalidFieldNames.subgraphNamesByExternalFieldName.set(fieldData.name, externalFieldSubgraphNames);
}
return;
case 1:
// The field can be unshareable if it's the only one
if (instances === 1) {
return;
}
if (instances - externalFieldSubgraphNames.length !== 1) {
invalidFieldNames.byShareable.add(fieldData.name);
}
return;
default:
invalidFieldNames.byShareable.add(fieldData.name);
}
}
export enum MergeMethod {
UNION,
INTERSECTION,
CONSISTENT,
}
export function isTypeValidImplementation({
concreteTypeNamesByAbstractTypeName,
implementationType,
interfaceImplementationTypeNamesByInterfaceTypeName,
originalType,
}: IsTypeValidImplementationParams): boolean {
if (originalType.kind === Kind.NON_NULL_TYPE) {
if (implementationType.kind !== Kind.NON_NULL_TYPE) {
return false;
}
return isTypeValidImplementation({
concreteTypeNamesByAbstractTypeName,
implementationType: implementationType.type,
interfaceImplementationTypeNamesByInterfaceTypeName,
originalType: originalType.type,
});
}
if (implementationType.kind === Kind.NON_NULL_TYPE) {
return isTypeValidImplementation({
concreteTypeNamesByAbstractTypeName,
implementationType: implementationType.type,
interfaceImplementationTypeNamesByInterfaceTypeName,
originalType,
});
}
switch (originalType.kind) {
case Kind.NAMED_TYPE:
if (implementationType.kind === Kind.NAMED_TYPE) {
const originalTypeName = originalType.name.value;
const implementationTypeName = implementationType.name.value;
if (originalTypeName === implementationTypeName) {
return true;
}
const abstractTypes = interfaceImplementationTypeNamesByInterfaceTypeName.get(originalTypeName);
const concreteTypes = concreteTypeNamesByAbstractTypeName.get(originalTypeName);
return !!(concreteTypes?.has(implementationTypeName) || abstractTypes?.has(implementationTypeName));
}
return false;
default:
if (implementationType.kind === Kind.LIST_TYPE) {
return isTypeValidImplementation({
concreteTypeNamesByAbstractTypeName,
implementationType: implementationType.type,
interfaceImplementationTypeNamesByInterfaceTypeName,
originalType: originalType.type,
});
}
return false;
}
}
export function isNodeDataInaccessible(data: NodeData): boolean {
return data.persistedDirectivesData.directivesByName.has(INACCESSIBLE) || data.directivesByName.has(INACCESSIBLE);
}
export function isLeafKind(kind: Kind): boolean {
return kind === Kind.SCALAR_TYPE_DEFINITION || kind === Kind.ENUM_TYPE_DEFINITION;
}
export function getSubscriptionFilterValue(
valueNode: BooleanValueNode | EnumValueNode | FloatValueNode | IntValueNode | NullValueNode | StringValueNode,
): SubscriptionFilterValue {
switch (valueNode.kind) {
case Kind.BOOLEAN: {
return valueNode.value;
}
case Kind.ENUM:
// intentional fallthrough
case Kind.STRING: {
return valueNode.value;
}
case Kind.FLOAT:
// intentional fallthrough
case Kind.INT: {
// The incoming value should never not be a number but wrap in a catch just in case
try {
return parseFloat(valueNode.value);
} catch {
return 'NaN';
}
}
case Kind.NULL: {
return null;
}
}
}
export function getParentTypeName(parentData: CompositeOutputData): TypeName {
if (parentData.kind === Kind.OBJECT_TYPE_DEFINITION) {
return parentData.renamedTypeName || parentData.name;
}
return parentData.name;
}
export function newConditionalFieldData(): ConditionalFieldData {
return {
providedBy: [],
requiredBy: [],
};
}
export function getDefinitionDataCoords(data: NodeData, useFederatedCoords: boolean): string {
switch (data.kind) {
case Kind.ENUM_VALUE_DEFINITION: {
return `${data.parentTypeName}.${data.name}`;
}
case Kind.FIELD_DEFINITION: {
return `${useFederatedCoords ? data.renamedParentTypeName : data.originalParentTypeName}.${data.name}`;
}
case Kind.ARGUMENT:
// intentional fallthrough
case Kind.INPUT_VALUE_DEFINITION: {
return useFederatedCoords ? data.federatedCoords : data.originalCoords;
}
case Kind.OBJECT_TYPE_DEFINITION: {
return useFederatedCoords ? data.renamedTypeName : data.name;
}
default:
return data.name;
}
}
export function isParentDataCompositeOutputType(
data: ParentDefinitionData,
): data is ObjectDefinitionData | InterfaceDefinitionData {
return data.kind === Kind.OBJECT_TYPE_DEFINITION || data.kind === Kind.INTERFACE_TYPE_DEFINITION;
}
export function newExternalFieldData(isDefinedExternal: boolean): ExternalFieldData {
return {
isDefinedExternal,
isUnconditionallyProvided: !isDefinedExternal,
};
}
export function getInitialFederatedDescription(data: NodeData): StringValueNode | undefined {
const { value, done } = data.configureDescriptionDataBySubgraphName.values().next();
if (done) {
return data.description;
}
if (!value.propagate) {
return;
}
return getDescriptionFromString(value.description) || data.description;
}
export function areKindsEqual<T extends ParentDefinitionData>(a: T, b: ParentDefinitionData): b is T {
return a.kind === b.kind;
}
export function isFieldData(data: ChildData | NodeData | SchemaData): data is FieldData {
return data.kind === Kind.FIELD_DEFINITION;
}
export function isInputObjectDefinitionData(data: ParentDefinitionData): data is InputObjectDefinitionData {
return data.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION;
}
export function isInputNodeKind(kind: Kind): kind is InputNodeKind {
return INPUT_NODE_KINDS.has(kind);
}
export function isOutputNodeKind(kind: Kind): kind is OutputNodeKind {
return OUTPUT_NODE_KINDS.has(kind);
}
export function isInterfaceNode(node: ParentTypeNode): node is InterfaceTypeNode {
return INTERFACE_NODE_KINDS.has(node.kind);
}