-
Notifications
You must be signed in to change notification settings - Fork 251
/
operations.ts
4077 lines (3597 loc) · 163 KB
/
operations.ts
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
ArgumentNode,
ASTNode,
DefinitionNode,
DirectiveNode,
DocumentNode,
FieldNode,
FragmentDefinitionNode,
FragmentSpreadNode,
InlineFragmentNode,
Kind,
OperationDefinitionNode,
parse,
SelectionNode,
SelectionSetNode,
OperationTypeNode,
NameNode,
} from "graphql";
import {
baseType,
Directive,
DirectiveTargetElement,
FieldDefinition,
isCompositeType,
isInterfaceType,
isNullableType,
runtimeTypesIntersects,
Schema,
SchemaRootKind,
VariableCollector,
VariableDefinitions,
variableDefinitionsFromAST,
CompositeType,
typenameFieldName,
sameDirectiveApplications,
isConditionalDirective,
isDirectiveApplicationsSubset,
isAbstractType,
DeferDirectiveArgs,
Variable,
possibleRuntimeTypes,
Type,
sameDirectiveApplication,
isLeafType,
Variables,
isObjectType,
NamedType,
isUnionType,
directivesToString,
directivesToDirectiveNodes,
} from "./definitions";
import { federationMetadata, isFederationDirectiveDefinedInSchema, isInterfaceObjectType } from "./federation";
import { ERRORS } from "./error";
import { isSubtype, sameType, typesCanBeMerged } from "./types";
import { assert, mapKeys, mapValues, MapWithCachedArrays, MultiMap, SetMultiMap } from "./utils";
import { argumentsEquals, argumentsFromAST, isValidValue, valueToAST, valueToString } from "./values";
import { v1 as uuidv1 } from 'uuid';
export const DEFAULT_MIN_USAGES_TO_OPTIMIZE = 2;
function validate(condition: any, message: () => string, sourceAST?: ASTNode): asserts condition {
if (!condition) {
throw ERRORS.INVALID_GRAPHQL.err(message(), { nodes: sourceAST });
}
}
function haveSameDirectives<TElement extends OperationElement>(op1: TElement, op2: TElement): boolean {
return sameDirectiveApplications(op1.appliedDirectives, op2.appliedDirectives);
}
abstract class AbstractOperationElement<T extends AbstractOperationElement<T>> extends DirectiveTargetElement<T> {
private attachments?: Map<string, string>;
constructor(
schema: Schema,
directives?: readonly Directive<any>[],
) {
super(schema, directives);
}
collectVariables(collector: VariableCollector) {
this.collectVariablesInElement(collector);
this.collectVariablesInAppliedDirectives(collector);
}
abstract key(): string;
abstract asPathElement(): string | undefined;
abstract rebaseOn(args: { parentType: CompositeType, errorIfCannotRebase: boolean }): T | undefined;
rebaseOnOrError(parentType: CompositeType): T {
return this.rebaseOn({ parentType, errorIfCannotRebase: true })!;
}
abstract withUpdatedDirectives(newDirectives: readonly Directive<any>[]): T;
protected abstract collectVariablesInElement(collector: VariableCollector): void;
addAttachment(key: string, value: string) {
if (!this.attachments) {
this.attachments = new Map();
}
this.attachments.set(key, value);
}
getAttachment(key: string): string | undefined {
return this.attachments?.get(key);
}
protected copyAttachmentsTo(elt: AbstractOperationElement<any>) {
if (this.attachments) {
for (const [k, v] of this.attachments.entries()) {
elt.addAttachment(k, v);
}
}
}
protected keyForDirectives(): string {
return this.appliedDirectives.map((d) => keyForDirective(d)).join(' ');
}
}
export class Field<TArgs extends {[key: string]: any} = {[key: string]: any}> extends AbstractOperationElement<Field<TArgs>> {
readonly kind = 'Field' as const;
constructor(
readonly definition: FieldDefinition<CompositeType>,
readonly args?: TArgs,
directives?: readonly Directive<any>[],
readonly alias?: string,
) {
super(definition.schema(), directives);
}
protected collectVariablesInElement(collector: VariableCollector): void {
if (this.args) {
collector.collectInArguments(this.args);
}
}
get name(): string {
return this.definition.name;
}
argumentValue(name: string): any {
return this.args ? this.args[name] : undefined;
}
responseName(): string {
return this.alias ? this.alias : this.name;
}
key(): string {
return this.responseName() + this.keyForDirectives();
}
asPathElement(): string {
return this.responseName();
}
get parentType(): CompositeType {
return this.definition.parent;
}
isLeafField(): boolean {
return isLeafType(this.baseType());
}
baseType(): NamedType {
return baseType(this.definition.type!);
}
copy(): Field<TArgs> {
const newField = new Field<TArgs>(
this.definition,
this.args,
this.appliedDirectives,
this.alias,
);
this.copyAttachmentsTo(newField);
return newField;
}
withUpdatedArguments(newArgs: TArgs): Field<TArgs> {
const newField = new Field<TArgs>(
this.definition,
{ ...this.args, ...newArgs },
this.appliedDirectives,
this.alias,
);
this.copyAttachmentsTo(newField);
return newField;
}
withUpdatedDefinition(newDefinition: FieldDefinition<any>): Field<TArgs> {
const newField = new Field<TArgs>(
newDefinition,
this.args,
this.appliedDirectives,
this.alias,
);
this.copyAttachmentsTo(newField);
return newField;
}
withUpdatedAlias(newAlias: string | undefined): Field<TArgs> {
const newField = new Field<TArgs>(
this.definition,
this.args,
this.appliedDirectives,
newAlias,
);
this.copyAttachmentsTo(newField);
return newField;
}
withUpdatedDirectives(newDirectives: readonly Directive<any>[]): Field<TArgs> {
const newField = new Field<TArgs>(
this.definition,
this.args,
newDirectives,
this.alias,
);
this.copyAttachmentsTo(newField);
return newField;
}
argumentsToNodes(): ArgumentNode[] | undefined {
if (!this.args) {
return undefined;
}
const entries = Object.entries(this.args);
if (entries.length === 0) {
return undefined;
}
return entries.map(([n, v]) => {
return {
kind: Kind.ARGUMENT,
name: { kind: Kind.NAME, value: n },
value: valueToAST(v, this.definition.argument(n)!.type!)!,
};
});
}
selects(
definition: FieldDefinition<any>,
assumeValid: boolean = false,
variableDefinitions?: VariableDefinitions,
contextualArguments?: string[],
): boolean {
assert(assumeValid || variableDefinitions, 'Must provide variable definitions if validation is needed');
// We've already validated that the field selects the definition on which it was built.
if (definition === this.definition) {
return true;
}
// This code largely mirrors validate, so we could generalize that and return false on exception, but this
// method is called fairly often and that has been shown to impact performance quite a lot. So a little
// bit of code duplication is ok.
if (this.name !== definition.name) {
return false;
}
// We need to make sure the field has valid values for every non-optional argument.
for (const argDef of definition.arguments()) {
const appliedValue = this.argumentValue(argDef.name);
if (appliedValue === undefined) {
if (argDef.defaultValue === undefined && !isNullableType(argDef.type!) && (!contextualArguments || !contextualArguments?.includes(argDef.name))) {
return false;
}
} else {
if (!assumeValid && !isValidValue(appliedValue, argDef, variableDefinitions!)) {
return false;
}
}
}
// We also make sure the field application does not have non-null values for field that are not part of the definition.
if (!assumeValid && this.args) {
for (const [name, value] of Object.entries(this.args)) {
if (value !== null && definition.argument(name) === undefined) {
return false
}
}
}
return true;
}
validate(variableDefinitions: VariableDefinitions, validateContextualArgs: boolean) {
validate(this.name === this.definition.name, () => `Field name "${this.name}" cannot select field "${this.definition.coordinate}: name mismatch"`);
// We need to make sure the field has valid values for every non-optional argument.
for (const argDef of this.definition.arguments()) {
const appliedValue = this.argumentValue(argDef.name);
let isContextualArg = false;
const schema = this.definition.schema();
const fromContextDirective = federationMetadata(schema)?.fromContextDirective();
if (fromContextDirective && isFederationDirectiveDefinedInSchema(fromContextDirective)) {
isContextualArg = argDef.appliedDirectivesOf(fromContextDirective).length > 0;
}
if (appliedValue === undefined) {
validate(
(isContextualArg && !validateContextualArgs) || argDef.defaultValue !== undefined || isNullableType(argDef.type!),
() => `Missing mandatory value for argument "${argDef.name}" of field "${this.definition.coordinate}" in selection "${this}"`);
} else {
validate(
(isContextualArg && !validateContextualArgs) || isValidValue(appliedValue, argDef, variableDefinitions),
() => `Invalid value ${valueToString(appliedValue)} for argument "${argDef.coordinate}" of type ${argDef.type}`)
}
}
// We also make sure the field application does not have non-null values for field that are not part of the definition.
if (this.args) {
for (const [name, value] of Object.entries(this.args)) {
validate(
value === null || this.definition.argument(name) !== undefined,
() => `Unknown argument "${name}" in field application of "${this.name}"`);
}
}
}
rebaseOn({ parentType, errorIfCannotRebase }: { parentType: CompositeType, errorIfCannotRebase: boolean }): Field<TArgs> | undefined {
const fieldParent = this.definition.parent;
if (parentType === fieldParent) {
return this;
}
if (this.name === typenameFieldName) {
if (possibleRuntimeTypes(parentType).some((runtimeType) => isInterfaceObjectType(runtimeType))) {
validate(
!errorIfCannotRebase,
() => `Cannot add selection of field "${this.definition.coordinate}" to selection set of parent type "${parentType}" that is potentially an interface object type at runtime`
);
return undefined;
} else {
return this.withUpdatedDefinition(parentType.typenameField()!);
}
}
const fieldDef = parentType.field(this.name);
const canRebase = this.canRebaseOn(parentType) && fieldDef;
if (!canRebase) {
validate(
!errorIfCannotRebase,
() => `Cannot add selection of field "${this.definition.coordinate}" to selection set of parent type "${parentType}"`
);
return undefined;
}
return this.withUpdatedDefinition(fieldDef);
}
private canRebaseOn(parentType: CompositeType) {
const fieldParentType = this.definition.parent
// There is 2 valid cases we want to allow:
// 1. either `selectionParent` and `fieldParent` are the same underlying type (same name) but from different underlying schema. Typically,
// happens when we're building subgraph queries but using selections from the original query which is against the supergraph API schema.
// 2. or they are not the same underlying type, but the field parent type is from an interface (or an interface object, which is the same
// here), in which case we may be rebasing an interface field on one of the implementation type, which is ok. Note that we don't verify
// that `parentType` is indeed an implementation of `fieldParentType` because it's possible that this implementation relationship exists
// in the supergraph, but not in any of the subgraph schema involved here. So we just let it be. Not that `rebaseOn` will complain anyway
// if the field name simply does not exists in `parentType`.
return parentType.name === fieldParentType.name
|| isInterfaceType(fieldParentType)
|| isInterfaceObjectType(fieldParentType);
}
typeIfAddedTo(parentType: CompositeType): Type | undefined {
const fieldParentType = this.definition.parent;
if (parentType == fieldParentType) {
return this.definition.type;
}
if (this.name === typenameFieldName) {
return parentType.typenameField()?.type;
}
const returnType = this.canRebaseOn(parentType)
? parentType.field(this.name)?.type
: undefined;
// If the field has an argument with fromContextDirective on it. We should not rebase it.
const fromContextDirective = federationMetadata(parentType.schema())?.fromContextDirective();
if (fromContextDirective && isFederationDirectiveDefinedInSchema(fromContextDirective)) {
const fieldInParent = parentType.field(this.name);
if (fieldInParent && fieldInParent.arguments()
.some(arg => arg.appliedDirectivesOf(fromContextDirective).length > 0 && (!this.args || this.args[arg.name] === undefined))
) {
return undefined;
}
}
return returnType;
}
hasDefer(): boolean {
// @defer cannot be on field at the moment
return false;
}
deferDirectiveArgs(): undefined {
// @defer cannot be on field at the moment (but exists so we can call this method on any `OperationElement` conveniently)
return undefined;
}
withoutDefer(): Field<TArgs> {
// @defer cannot be on field at the moment
return this;
}
equals(that: OperationElement): boolean {
if (this === that) {
return true;
}
return that.kind === 'Field'
&& this.name === that.name
&& this.alias === that.alias
&& (this.args ? that.args && argumentsEquals(this.args, that.args) : !that.args)
&& haveSameDirectives(this, that);
}
toString(): string {
const alias = this.alias ? this.alias + ': ' : '';
const entries = this.args ? Object.entries(this.args) : [];
const args = entries.length === 0
? ''
: '(' + entries.map(([n, v]) => `${n}: ${valueToString(v, this.definition.argument(n)?.type)}`).join(', ') + ')';
return alias + this.name + args + this.appliedDirectivesToString();
}
}
/**
* Computes a string key representing a directive application, so that if 2 directive applications have the same key, then they
* represent the same application.
*
* Note that this is mostly just the `toString` representation of the directive, but for 2 subtlety:
* 1. for a handful of directives (really just `@defer` for now), we never want to consider directive applications the same, no
* matter that the arguments of the directive match, and this for the same reason as documented on the `sameDirectiveApplications`
* method in `definitions.ts`.
* 2. we sort the argument (by their name) before converting them to string, since argument order does not matter in graphQL.
*/
function keyForDirective(
directive: Directive<AbstractOperationElement<any>>,
directivesNeverEqualToThemselves: string[] = [ 'defer' ],
): string {
if (directivesNeverEqualToThemselves.includes(directive.name)) {
return uuidv1();
}
const entries = Object.entries(directive.arguments()).filter(([_, v]) => v !== undefined);
entries.sort(([n1], [n2]) => n1.localeCompare(n2));
const args = entries.length == 0 ? '' : '(' + entries.map(([n, v]) => `${n}: ${valueToString(v, directive.argumentType(n))}`).join(', ') + ')';
return `@${directive.name}${args}`;
}
export class FragmentElement extends AbstractOperationElement<FragmentElement> {
readonly kind = 'FragmentElement' as const;
readonly typeCondition?: CompositeType;
private computedKey: string | undefined;
constructor(
private readonly sourceType: CompositeType,
typeCondition?: string | CompositeType,
directives?: readonly Directive<any>[],
) {
// TODO: we should do some validation here (remove the ! with proper error, and ensure we have some intersection between
// the source type and the type condition)
super(sourceType.schema(), directives);
this.typeCondition = typeCondition !== undefined && typeof typeCondition === 'string'
? this.schema().type(typeCondition)! as CompositeType
: typeCondition;
}
protected collectVariablesInElement(_: VariableCollector): void {
// Cannot have variables in fragments
}
get parentType(): CompositeType {
return this.sourceType;
}
key(): string {
if (!this.computedKey) {
// The key is such that 2 fragments with the same key within a selection set gets merged together. So the type-condition
// is include, but so are the directives.
this.computedKey = '...' + (this.typeCondition ? ' on ' + this.typeCondition.name : '') + this.keyForDirectives();
}
return this.computedKey;
}
castedType(): CompositeType {
return this.typeCondition ? this.typeCondition : this.sourceType;
}
asPathElement(): string | undefined {
const condition = this.typeCondition;
return condition ? `... on ${condition}` : undefined;
}
withUpdatedSourceType(newSourceType: CompositeType): FragmentElement {
return this.withUpdatedTypes(newSourceType, this.typeCondition);
}
withUpdatedCondition(newCondition: CompositeType | undefined): FragmentElement {
return this.withUpdatedTypes(this.sourceType, newCondition);
}
withUpdatedTypes(newSourceType: CompositeType, newCondition: CompositeType | undefined): FragmentElement {
// Note that we pass the type-condition name instead of the type itself, to ensure that if `newSourceType` was from a different
// schema (typically, the supergraph) than `this.sourceType` (typically, a subgraph), then the new condition uses the
// definition of the proper schema (the supergraph in such cases, instead of the subgraph).
const newFragment = new FragmentElement(newSourceType, newCondition?.name, this.appliedDirectives);
this.copyAttachmentsTo(newFragment);
return newFragment;
}
withUpdatedDirectives(newDirectives: Directive<OperationElement>[]): FragmentElement {
const newFragment = new FragmentElement(this.sourceType, this.typeCondition, newDirectives);
this.copyAttachmentsTo(newFragment);
return newFragment;
}
rebaseOn({ parentType, errorIfCannotRebase }: { parentType: CompositeType, errorIfCannotRebase: boolean }): FragmentElement | undefined {
const fragmentParent = this.parentType;
const typeCondition = this.typeCondition;
if (parentType === fragmentParent) {
return this;
}
// This usually imply that the fragment is not from the same sugraph than then selection. So we need
// to update the source type of the fragment, but also "rebase" the condition to the selection set
// schema.
const { canRebase, rebasedCondition } = this.canRebaseOn(parentType);
if (!canRebase) {
validate(
!errorIfCannotRebase,
() => `Cannot add fragment of condition "${typeCondition}" (runtimes: [${possibleRuntimeTypes(typeCondition!)}]) to parent type "${parentType}" (runtimes: ${possibleRuntimeTypes(parentType)})`
);
return undefined;
}
return this.withUpdatedTypes(parentType, rebasedCondition);
}
private canRebaseOn(parentType: CompositeType): { canRebase: boolean, rebasedCondition?: CompositeType } {
if (!this.typeCondition) {
return { canRebase: true, rebasedCondition: undefined };
}
const rebasedCondition = parentType.schema().type(this.typeCondition.name);
if (!rebasedCondition || !isCompositeType(rebasedCondition) || !runtimeTypesIntersects(parentType, rebasedCondition)) {
return { canRebase: false };
}
return { canRebase: true, rebasedCondition };
}
castedTypeIfAddedTo(parentType: CompositeType): CompositeType | undefined {
if (parentType == this.parentType) {
return this.castedType();
}
const { canRebase, rebasedCondition } = this.canRebaseOn(parentType);
return canRebase ? (rebasedCondition ? rebasedCondition : parentType) : undefined;
}
hasDefer(): boolean {
return this.hasAppliedDirective('defer');
}
hasStream(): boolean {
return this.hasAppliedDirective('stream');
}
deferDirectiveArgs(): DeferDirectiveArgs | undefined {
// Note: @defer is not repeatable, so the return array below is either empty, or has a single value.
return this.appliedDirectivesOf(this.schema().deferDirective())[0]?.arguments();
}
/**
* Returns this fragment element but with any @defer directive on it removed.
*
* This method will return `undefined` if, upon removing @defer, the fragment has no conditions nor
* any remaining applied directives (meaning that it carries no information whatsoever and can be
* ignored).
*/
withoutDefer(): FragmentElement | undefined {
const deferName = this.schema().deferDirective().name;
const updatedDirectives = this.appliedDirectives.filter((d) => d.name !== deferName);
if (!this.typeCondition && updatedDirectives.length === 0) {
return undefined;
}
if (updatedDirectives.length === this.appliedDirectives.length) {
return this;
}
const updated = new FragmentElement(this.sourceType, this.typeCondition, updatedDirectives);
this.copyAttachmentsTo(updated);
return updated;
}
/**
* Returns this fragment element, but it is has a @defer directive, the element is returned with
* the @defer "normalized".
*
* See `Operation.withNormalizedDefer` for details on our so-called @defer normalization.
*/
withNormalizedDefer(normalizer: DeferNormalizer): FragmentElement | undefined {
const deferArgs = this.deferDirectiveArgs();
if (!deferArgs) {
return this;
}
let newDeferArgs: DeferDirectiveArgs | undefined = undefined;
let conditionVariable: Variable | undefined = undefined;
if (deferArgs.if !== undefined) {
if (typeof deferArgs.if === 'boolean') {
if (deferArgs.if) {
// Harcoded `if: true`, remove the `if`
newDeferArgs = {
...deferArgs,
if: undefined,
}
} else {
// Harcoded `if: false`, remove the @defer altogether
return this.withoutDefer();
}
} else {
// `if` on a variable
conditionVariable = deferArgs.if;
}
}
let label = deferArgs.label;
if (!label) {
label = normalizer.newLabel();
if (newDeferArgs) {
newDeferArgs.label = label;
} else {
newDeferArgs = {
...deferArgs,
label,
}
}
}
// Now that we are sure to have a label, if we had a (non-trivial) condition,
// associate it to that label.
if (conditionVariable) {
normalizer.registerCondition(label, conditionVariable);
}
if (!newDeferArgs) {
return this;
}
const deferDirective = this.schema().deferDirective();
const updatedDirectives = this.appliedDirectives
.filter((d) => d.name !== deferDirective.name)
.concat(new Directive<FragmentElement>(deferDirective.name, newDeferArgs));
const updated = new FragmentElement(this.sourceType, this.typeCondition, updatedDirectives);
this.copyAttachmentsTo(updated);
return updated;
}
equals(that: OperationElement): boolean {
if (this === that) {
return true;
}
return that.kind === 'FragmentElement'
&& this.typeCondition?.name === that.typeCondition?.name
&& haveSameDirectives(this, that);
}
toString(): string {
return '...' + (this.typeCondition ? ' on ' + this.typeCondition : '') + this.appliedDirectivesToString();
}
}
export type OperationElement = Field<any> | FragmentElement;
export type OperationPath = OperationElement[];
export function operationPathToStringPath(path: OperationPath): string[] {
return path
.filter((p) => !(p.kind === 'FragmentElement' && !p.typeCondition))
.map((p) => p.kind === 'Field' ? p.responseName() : `... on ${p.typeCondition?.coordinate}`);
}
export function sameOperationPaths(p1: OperationPath, p2: OperationPath): boolean {
if (p1 === p2) {
return true;
}
if (p1.length !== p2.length) {
return false;
}
for (let i = 0; i < p1.length; i++) {
if (!p1[i].equals(p2[i])) {
return false;
}
}
return true;
}
/**
* Returns all the "conditional" directive applications (`@skip` and `@include`) in the provided path.
*/
export function conditionalDirectivesInOperationPath(path: OperationPath): Directive<any, any>[] {
return path.map((e) => e.appliedDirectives).flat().filter((d) => isConditionalDirective(d));
}
export function concatOperationPaths(head: OperationPath, tail: OperationPath): OperationPath {
// While this is mainly a simple array concatenation, we optimize slightly by recognizing if the
// tail path starts by a fragment selection that is useless given the end of the head path.
if (head.length === 0) {
return tail;
}
if (tail.length === 0) {
return head;
}
const lastOfHead = head[head.length - 1];
const conditionals = conditionalDirectivesInOperationPath(head);
let firstOfTail = tail[0];
// Note that in practice, we may be able to eliminate a few elements at the beginning of the path
// due do conditionals ('@skip' and '@include'). Indeed, a (tail) path crossing multiple conditions
// may start with: [ ... on X @include(if: $c1), ... on X @ksip(if: $c2), (...)], but if `head`
// already ends on type `X` _and_ both the conditions on `$c1` and `$c2` are alredy found on `head`,
// then we can remove both fragments in `tail`.
while (firstOfTail && isUselessFollowupElement(lastOfHead, firstOfTail, conditionals)) {
tail = tail.slice(1);
firstOfTail = tail[0];
}
return head.concat(tail);
}
function isUselessFollowupElement(first: OperationElement, followup: OperationElement, conditionals: Directive<any, any>[]): boolean {
const typeOfFirst = first.kind === 'Field'
? first.baseType()
: first.typeCondition;
// The followup is useless if it's a fragment (with no directives we would want to preserve) whose type
// is already that of the first element (or a supertype).
return !!typeOfFirst
&& followup.kind === 'FragmentElement'
&& !!followup.typeCondition
&& (followup.appliedDirectives.length === 0 || isDirectiveApplicationsSubset(conditionals, followup.appliedDirectives))
&& isSubtype(followup.typeCondition, typeOfFirst);
}
export type RootOperationPath = {
rootKind: SchemaRootKind,
path: OperationPath
}
// Computes for every fragment, which other fragments use it (so the reverse of it's dependencies, the other fragment it uses).
function computeFragmentsDependents(fragments: NamedFragments): SetMultiMap<string, string> {
const reverseDeps = new SetMultiMap<string, string>();
for (const fragment of fragments.definitions()) {
for (const dependency of fragment.fragmentUsages().keys()) {
reverseDeps.add(dependency, fragment.name);
}
}
return reverseDeps;
}
function clearKeptFragments(
usages: Map<string, number>,
fragments: NamedFragments,
minUsagesToOptimize: number
) {
// `toCheck` will contain only fragments that we know we want to keep (but haven't handled/removed from `usages` yet).
let toCheck = Array.from(usages.entries()).filter(([_, count]) => count >= minUsagesToOptimize).map(([name, _]) => name);
while (toCheck.length > 0) {
const newToCheck = [];
for (const name of toCheck) {
// We "keep" that fragment so clear it.
usages.delete(name);
// But as it is used, bump the usage for every fragment it uses.
const ownUsages = fragments.get(name)!.fragmentUsages();
for (const [otherName, otherCount] of ownUsages.entries()) {
const prevCount = usages.get(otherName);
// We're interested in fragment not in `usages` anymore.
if (prevCount !== undefined) {
const newCount = prevCount + otherCount;
usages.set(otherName, newCount);
if (prevCount < minUsagesToOptimize && newCount >= minUsagesToOptimize) {
newToCheck.push(otherName);
}
}
}
}
toCheck = newToCheck;
}
}
// Checks, in `selectionSet`, which fragments (of `fragments`) are used at least `minUsagesToOptimize` times.
// Returns the updated set of fragments containing only the fragment definitions with usage above our threshold,
// and `undefined` or `null` if no such fragment meets said threshold. When this method returns `null`, it
// additionally means that no fragments are use at all in `selectionSet` (and so `undefined` means that
// "some" fragments are used in `selectionSet`, but just none of them is used at least `minUsagesToOptimize`
// times).
function computeFragmentsToKeep(
selectionSet: SelectionSet,
fragments: NamedFragments,
minUsagesToOptimize: number
): NamedFragments | undefined | null {
// We start by collecting the usages within the selection set.
const usages = new Map<string, number>();
selectionSet.collectUsedFragmentNames(usages);
// If we have no fragment in the selection set, then it's simple, we just don't keep any fragments.
if (usages.size === 0) {
return null;
}
// We're going to remove fragments from usages as we categorize them as kept or expanded, so we
// first ensure that it has entries for every fragment, default to 0.
for (const fragment of fragments.definitions()) {
if (usages.get(fragment.name) === undefined) {
usages.set(fragment.name, 0);
}
}
// At this point, `usages` contains the usages of fragments "in the selection". From that, we want
// to decide which fragment to "keep", and which to re-expand. But there is 2 subtlety:
// 1. when we decide to keep some fragment F, then we should could it's own usages of other fragments. That
// is, if a fragment G is use once in the selection, but also use once in a fragment F that we
// keep, then the usages for G is really 2 (but if F is unused, then we don't want to count
// it's usage of G for instance).
// 2. when we decide to expand a fragment, then this also impact the usages of other fragments it
// uses, as those gets "inlined" into the selection. But that also mean we have to be careful
// of the order in which we pick fragments to expand. Say we have:
// ```graphql
// query {
// ...F1
// }
//
// fragment F1 {
// a { ...F2 }
// b { ...F2 }
// }
//
// fragment F2 {
// // something
// }
// ```
// then at this point where we've only counted usages in the query selection, `usages` will be
// `{ F1: 1, F2: 0 }`. But we do not want to expand _both_ F1 and F2. Instead, we want to expand
// F1 first, and then realize that this increases F2 usages to 2, which means we stop there and keep F2.
// Generalizing this, it means we want to first pick up fragments to expand that are _not_ used by any
// other fragments that may be expanded.
const reverseDependencies = computeFragmentsDependents(fragments);
// We'll add to `toExpand` fragment we will definitively expand.
const toExpand = new Set<string>;
let shouldContinue = true;
while (shouldContinue) {
// We'll do an iteration, but if we make no progress, we won't continue (we don't want to loop forever).
shouldContinue = false;
clearKeptFragments(usages, fragments, minUsagesToOptimize);
for (const name of mapKeys(usages)) {
// Note that we modify `usages` as we iterate it, so 1) we use `mapKeys` above which copy into a list and 2)
// we get the `count` manually instead of relying on (possibly outdated) entries.
const count = usages.get(name)!;
// A unused fragment is not technically expanded, it is just removed and we can ignore for now (it's count
// count increase later but ...).
if (count === 0) {
continue;
}
// If we find a fragment to keep, it means some fragment we expanded earlier in this iteration bump this
// one count. We unsure `shouldContinue` is set so `clearKeptFragments` is called again, but let that
// method deal with it otherwise.
if (count >= minUsagesToOptimize) {
shouldContinue = true;
break;
}
const fragmentsUsingName = reverseDependencies.get(name);
if (!fragmentsUsingName || [...fragmentsUsingName].every((fragName) => toExpand.has(fragName) || !usages.get(fragName))) {
// This fragment is not used enough, and is only used by fragments we keep, so we
// are guaranteed that expanding another fragment will not increase its usage. So
// we definitively expand it.
toExpand.add(name);
usages.delete(name);
// We've added to `toExpand`, so it's worth redoing another iteration
// after that to see if something changes.
shouldContinue = true;
// Now that we expand it, we should bump the usage for every fragment it uses.
const nameUsages = fragments.get(name)!.fragmentUsages();
for (const [otherName, otherCount] of nameUsages.entries()) {
const prev = usages.get(otherName);
// Note that if `otherName` is not part of usages, it means it's a fragment we
// already decided to keep/expand, so we just ignore it.
if (prev !== undefined) {
usages.set(otherName, prev + count * otherCount);
}
}
}
}
}
// Finally, we know that to expand, which is `toExpand` plus whatever remains in `usage` (typically
// genuinely unused fragments).
for (const name of usages.keys()) {
toExpand.add(name);
}
return toExpand.size === 0 ? fragments : fragments.filter((f) => !toExpand.has(f.name));
}
export class Operation extends DirectiveTargetElement<Operation> {
constructor(
schema: Schema,
readonly rootKind: SchemaRootKind,
readonly selectionSet: SelectionSet,
readonly variableDefinitions: VariableDefinitions,
readonly fragments?: NamedFragments,
readonly name?: string,
directives: readonly Directive<any>[] = []) {
super(schema, directives);
}
// Returns a copy of this operation with the provided updated selection set.
// Note that this method assumes that the existing `this.fragments` is still appropriate.
private withUpdatedSelectionSet(newSelectionSet: SelectionSet): Operation {
if (this.selectionSet === newSelectionSet) {
return this;
}
return new Operation(
this.schema(),
this.rootKind,
newSelectionSet,
this.variableDefinitions,
this.fragments,
this.name,
this.appliedDirectives,
);
}
private collectUndefinedVariablesFromFragments(fragments: NamedFragments): Variable[] {
const collector = new VariableCollector();
for (const namedFragment of fragments.definitions()) {
namedFragment.selectionSet.usedVariables().forEach(v => {
if (!this.variableDefinitions.definition(v)) {
collector.add(v);
}
});
}
return collector.variables();
}
// Returns a copy of this operation with the provided updated selection set and fragments.
private withUpdatedSelectionSetAndFragments(
newSelectionSet: SelectionSet,
newFragments: NamedFragments | undefined,
allAvailableVariables?: VariableDefinitions,
): Operation {
if (this.selectionSet === newSelectionSet && newFragments === this.fragments) {
return this;
}
let newVariableDefinitions = this.variableDefinitions;
if (allAvailableVariables && newFragments) {
const undefinedVariables = this.collectUndefinedVariablesFromFragments(newFragments);
if (undefinedVariables.length > 0) {
newVariableDefinitions = new VariableDefinitions();
newVariableDefinitions.addAll(this.variableDefinitions);
newVariableDefinitions.addAll(allAvailableVariables.filter(undefinedVariables));
}
}
return new Operation(
this.schema(),
this.rootKind,
newSelectionSet,
newVariableDefinitions,
newFragments,
this.name,
this.appliedDirectives,
);
}
optimize(
fragments?: NamedFragments,
minUsagesToOptimize: number = DEFAULT_MIN_USAGES_TO_OPTIMIZE,
allAvailableVariables?: VariableDefinitions,
): Operation {
assert(minUsagesToOptimize >= 1, `Expected 'minUsagesToOptimize' to be at least 1, but got ${minUsagesToOptimize}`)
if (!fragments || fragments.isEmpty()) {