@graphql-inspector/core 0.0.0-canary.58ffd99 → 0.0.0-canary.7db8980

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.
@@ -2,15 +2,40 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
+
7
+ const tslib = require('tslib');
5
8
  const graphql = require('graphql');
9
+ const inspect = _interopDefault(require('object-inspect'));
6
10
  const dependencyGraph = require('dependency-graph');
11
+ const parser = require('graphql/language/parser');
7
12
 
13
+ function keyMap(list, keyFn) {
14
+ return list.reduce((map, item) => {
15
+ map[keyFn(item)] = item;
16
+ return map;
17
+ }, Object.create(null));
18
+ }
8
19
  function isEqual(a, b) {
9
20
  if (Array.isArray(a) && Array.isArray(b)) {
10
21
  if (a.length !== b.length)
11
22
  return false;
12
23
  for (var index = 0; index < a.length; index++) {
13
- if (a[index] !== b[index]) {
24
+ if (!isEqual(a[index], b[index])) {
25
+ return false;
26
+ }
27
+ }
28
+ return true;
29
+ }
30
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
31
+ const aRecord = a;
32
+ const bRecord = b;
33
+ const aKeys = Object.keys(aRecord);
34
+ const bKeys = Object.keys(bRecord);
35
+ if (aKeys.length !== bKeys.length)
36
+ return false;
37
+ for (const key of aKeys) {
38
+ if (!isEqual(aRecord[key], bRecord[key])) {
14
39
  return false;
15
40
  }
16
41
  }
@@ -24,12 +49,62 @@ function isNotEqual(a, b) {
24
49
  function isVoid(a) {
25
50
  return typeof a === 'undefined' || a === null;
26
51
  }
27
-
28
52
  function diffArrays(a, b) {
29
- return a.filter((c) => !b.some((d) => d === c));
53
+ return a.filter(c => !b.some(d => isEqual(d, c)));
54
+ }
55
+ function compareLists(oldList, newList, callbacks) {
56
+ const oldMap = keyMap(oldList, ({ name }) => name);
57
+ const newMap = keyMap(newList, ({ name }) => name);
58
+ const added = [];
59
+ const removed = [];
60
+ const mutual = [];
61
+ for (const oldItem of oldList) {
62
+ const newItem = newMap[oldItem.name];
63
+ if (newItem === undefined) {
64
+ removed.push(oldItem);
65
+ }
66
+ else {
67
+ mutual.push({
68
+ newVersion: newItem,
69
+ oldVersion: oldItem,
70
+ });
71
+ }
72
+ }
73
+ for (const newItem of newList) {
74
+ if (oldMap[newItem.name] === undefined) {
75
+ added.push(newItem);
76
+ }
77
+ }
78
+ if (callbacks) {
79
+ if (callbacks.onAdded) {
80
+ added.forEach(callbacks.onAdded);
81
+ }
82
+ if (callbacks.onRemoved) {
83
+ removed.forEach(callbacks.onRemoved);
84
+ }
85
+ if (callbacks.onMutual) {
86
+ mutual.forEach(callbacks.onMutual);
87
+ }
88
+ }
89
+ return {
90
+ added,
91
+ removed,
92
+ mutual,
93
+ };
30
94
  }
31
- function unionArrays(a, b) {
32
- return a.filter((c) => b.some((d) => d === c));
95
+
96
+ function isDeprecated(fieldOrEnumValue) {
97
+ var _a, _b;
98
+ if ('isDeprecated' in fieldOrEnumValue) {
99
+ return fieldOrEnumValue['isDeprecated'];
100
+ }
101
+ if (fieldOrEnumValue.deprecationReason != null) {
102
+ return true;
103
+ }
104
+ if ((_b = (_a = fieldOrEnumValue.astNode) === null || _a === void 0 ? void 0 : _a.directives) === null || _b === void 0 ? void 0 : _b.some(directive => directive.name.value === 'deprecated')) {
105
+ return true;
106
+ }
107
+ return false;
33
108
  }
34
109
 
35
110
  function safeChangeForField(oldType, newType) {
@@ -41,8 +116,7 @@ function safeChangeForField(oldType, newType) {
41
116
  return safeChangeForField(ofType, newType.ofType);
42
117
  }
43
118
  if (graphql.isListType(oldType)) {
44
- return ((graphql.isListType(newType) &&
45
- safeChangeForField(oldType.ofType, newType.ofType)) ||
119
+ return ((graphql.isListType(newType) && safeChangeForField(oldType.ofType, newType.ofType)) ||
46
120
  (graphql.isNonNullType(newType) && safeChangeForField(oldType, newType.ofType)));
47
121
  }
48
122
  return false;
@@ -55,7 +129,7 @@ function safeChangeForInputValue(oldType, newType) {
55
129
  return safeChangeForInputValue(oldType.ofType, newType.ofType);
56
130
  }
57
131
  if (graphql.isNonNullType(oldType)) {
58
- const ofType = graphql.isNonNullType(newType) ? newType : newType;
132
+ const ofType = graphql.isNonNullType(newType) ? newType.ofType : newType;
59
133
  return safeChangeForInputValue(oldType.ofType, ofType);
60
134
  }
61
135
  return false;
@@ -74,10 +148,10 @@ function getTypePrefix(type) {
74
148
  [graphql.Kind.ENUM_TYPE_DEFINITION]: 'enum',
75
149
  [graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION]: 'input',
76
150
  };
77
- return kindsMap[kind];
151
+ return kindsMap[kind.toString()];
78
152
  }
79
153
  function isPrimitive(type) {
80
- return (['String', 'Int', 'Float', 'Boolean', 'ID'].indexOf(typeof type === 'string' ? type : type.name) !== -1);
154
+ return ['String', 'Int', 'Float', 'Boolean', 'ID'].indexOf(typeof type === 'string' ? type : type.name) !== -1;
81
155
  }
82
156
  function isForIntrospection(type) {
83
157
  return ([
@@ -95,9 +169,23 @@ function findDeprecatedUsages(schema, ast) {
95
169
  const errors = [];
96
170
  const typeInfo = new graphql.TypeInfo(schema);
97
171
  graphql.visit(ast, graphql.visitWithTypeInfo(typeInfo, {
172
+ Argument(node) {
173
+ const argument = typeInfo.getArgument();
174
+ if (argument) {
175
+ const reason = argument.deprecationReason;
176
+ if (reason) {
177
+ const fieldDef = typeInfo.getFieldDef();
178
+ if (fieldDef) {
179
+ errors.push(new graphql.GraphQLError(`The argument '${argument === null || argument === void 0 ? void 0 : argument.name}' of '${fieldDef.name}' is deprecated. ${reason}`, [
180
+ node,
181
+ ]));
182
+ }
183
+ }
184
+ }
185
+ },
98
186
  Field(node) {
99
187
  const fieldDef = typeInfo.getFieldDef();
100
- if (fieldDef && fieldDef.isDeprecated) {
188
+ if (fieldDef && isDeprecated(fieldDef)) {
101
189
  const parentType = typeInfo.getParentType();
102
190
  if (parentType) {
103
191
  const reason = fieldDef.deprecationReason;
@@ -107,7 +195,7 @@ function findDeprecatedUsages(schema, ast) {
107
195
  },
108
196
  EnumValue(node) {
109
197
  const enumVal = typeInfo.getEnumValue();
110
- if (enumVal && enumVal.isDeprecated) {
198
+ if (enumVal && isDeprecated(enumVal)) {
111
199
  const type = graphql.getNamedType(typeInfo.getInputType());
112
200
  if (type) {
113
201
  const reason = enumVal.deprecationReason;
@@ -120,7 +208,7 @@ function findDeprecatedUsages(schema, ast) {
120
208
  }
121
209
  function removeFieldIfDirectives(node, directiveNames) {
122
210
  if (node.directives) {
123
- if (node.directives.some((d) => directiveNames.indexOf(d.name.value) !== -1)) {
211
+ if (node.directives.some(d => directiveNames.indexOf(d.name.value) !== -1)) {
124
212
  return null;
125
213
  }
126
214
  }
@@ -128,10 +216,75 @@ function removeFieldIfDirectives(node, directiveNames) {
128
216
  }
129
217
  function removeDirectives(node, directiveNames) {
130
218
  if (node.directives) {
131
- return Object.assign(Object.assign({}, node), { directives: node.directives.filter((d) => directiveNames.indexOf(d.name.value) === -1) });
219
+ return Object.assign(Object.assign({}, node), { directives: node.directives.filter(d => directiveNames.indexOf(d.name.value) === -1) });
132
220
  }
133
221
  return node;
134
222
  }
223
+ function getReachableTypes(schema) {
224
+ const reachableTypes = new Set();
225
+ const collect = (type) => {
226
+ const typeName = type.name;
227
+ if (reachableTypes.has(typeName)) {
228
+ return;
229
+ }
230
+ reachableTypes.add(typeName);
231
+ if (graphql.isScalarType(type)) {
232
+ return;
233
+ }
234
+ else if (graphql.isInterfaceType(type) || graphql.isObjectType(type)) {
235
+ if (graphql.isInterfaceType(type)) {
236
+ const { objects, interfaces } = schema.getImplementations(type);
237
+ for (const child of objects) {
238
+ collect(child);
239
+ }
240
+ for (const child of interfaces) {
241
+ collect(child);
242
+ }
243
+ }
244
+ const fields = type.getFields();
245
+ for (const fieldName in fields) {
246
+ const field = fields[fieldName];
247
+ collect(resolveOutputType(field.type));
248
+ const args = field.args;
249
+ for (const argName in args) {
250
+ const arg = args[argName];
251
+ collect(resolveInputType(arg.type));
252
+ }
253
+ }
254
+ }
255
+ else if (graphql.isUnionType(type)) {
256
+ const types = type.getTypes();
257
+ for (const child of types) {
258
+ collect(child);
259
+ }
260
+ }
261
+ else if (graphql.isInputObjectType(type)) {
262
+ const fields = type.getFields();
263
+ for (const fieldName in fields) {
264
+ const field = fields[fieldName];
265
+ collect(resolveInputType(field.type));
266
+ }
267
+ }
268
+ };
269
+ for (const type of [schema.getQueryType(), schema.getMutationType(), schema.getSubscriptionType()]) {
270
+ if (type) {
271
+ collect(type);
272
+ }
273
+ }
274
+ return reachableTypes;
275
+ }
276
+ function resolveOutputType(output) {
277
+ if (graphql.isListType(output) || graphql.isNonNullType(output)) {
278
+ return resolveOutputType(output.ofType);
279
+ }
280
+ return output;
281
+ }
282
+ function resolveInputType(input) {
283
+ if (graphql.isListType(input) || graphql.isNonNullType(input)) {
284
+ return resolveInputType(input.ofType);
285
+ }
286
+ return input;
287
+ }
135
288
 
136
289
  (function (ChangeType) {
137
290
  // Argument
@@ -154,6 +307,8 @@ function removeDirectives(node, directiveNames) {
154
307
  ChangeType["EnumValueAdded"] = "ENUM_VALUE_ADDED";
155
308
  ChangeType["EnumValueDescriptionChanged"] = "ENUM_VALUE_DESCRIPTION_CHANGED";
156
309
  ChangeType["EnumValueDeprecationReasonChanged"] = "ENUM_VALUE_DEPRECATION_REASON_CHANGED";
310
+ ChangeType["EnumValueDeprecationReasonAdded"] = "ENUM_VALUE_DEPRECATION_REASON_ADDED";
311
+ ChangeType["EnumValueDeprecationReasonRemoved"] = "ENUM_VALUE_DEPRECATION_REASON_REMOVED";
157
312
  // Field
158
313
  ChangeType["FieldRemoved"] = "FIELD_REMOVED";
159
314
  ChangeType["FieldAdded"] = "FIELD_ADDED";
@@ -351,9 +506,7 @@ function directiveLocationRemoved(directive, location) {
351
506
  function directiveArgumentAdded(directive, arg) {
352
507
  return {
353
508
  criticality: {
354
- level: graphql.isNonNullType(arg.type)
355
- ? exports.CriticalityLevel.Breaking
356
- : exports.CriticalityLevel.NonBreaking,
509
+ level: graphql.isNonNullType(arg.type) ? exports.CriticalityLevel.Breaking : exports.CriticalityLevel.NonBreaking,
357
510
  },
358
511
  type: exports.ChangeType.DirectiveArgumentAdded,
359
512
  message: `Argument '${arg.name}' was added to directive '${directive.name}'`,
@@ -416,7 +569,7 @@ function enumValueRemoved(oldEnum, value) {
416
569
  reason: `Removing an enum value will cause existing queries that use this enum value to error.`,
417
570
  },
418
571
  type: exports.ChangeType.EnumValueRemoved,
419
- message: `Enum value '${value.name}' was removed from enum '${oldEnum.name}'`,
572
+ message: `Enum value '${value.name}' ${isDeprecated(value) ? '(deprecated) ' : ''}was removed from enum '${oldEnum.name}'`,
420
573
  path: [oldEnum.name, value.name].join('.'),
421
574
  };
422
575
  }
@@ -448,35 +601,59 @@ function enumValueDeprecationReasonChanged(newEnum, oldValue, newValue) {
448
601
  criticality: {
449
602
  level: exports.CriticalityLevel.NonBreaking,
450
603
  },
451
- type: exports.ChangeType.EnumValueDescriptionChanged,
452
- message: oldValue.deprecationReason
453
- ? `Enum value '${newEnum.name}.${newValue.name}' deprecation reason changed from '${oldValue.deprecationReason}' to '${newValue.deprecationReason}'`
454
- : `Enum value '${newEnum.name}.${newValue.name}' was deprecated with reason '${newValue.deprecationReason}'`,
604
+ type: exports.ChangeType.EnumValueDeprecationReasonChanged,
605
+ message: `Enum value '${newEnum.name}.${newValue.name}' deprecation reason changed from '${oldValue.deprecationReason}' to '${newValue.deprecationReason}'`,
606
+ path: [newEnum.name, oldValue.name].join('.'),
607
+ };
608
+ }
609
+ function enumValueDeprecationReasonAdded(newEnum, oldValue, newValue) {
610
+ return {
611
+ criticality: {
612
+ level: exports.CriticalityLevel.NonBreaking,
613
+ },
614
+ type: exports.ChangeType.EnumValueDeprecationReasonAdded,
615
+ message: `Enum value '${newEnum.name}.${newValue.name}' was deprecated with reason '${newValue.deprecationReason}'`,
616
+ path: [newEnum.name, oldValue.name].join('.'),
617
+ };
618
+ }
619
+ function enumValueDeprecationReasonRemoved(newEnum, oldValue, newValue) {
620
+ return {
621
+ criticality: {
622
+ level: exports.CriticalityLevel.NonBreaking,
623
+ },
624
+ type: exports.ChangeType.EnumValueDeprecationReasonRemoved,
625
+ message: `Deprecation reason was removed from enum value '${newEnum.name}.${newValue.name}'`,
455
626
  path: [newEnum.name, oldValue.name].join('.'),
456
627
  };
457
628
  }
458
629
 
459
- function changesInEnum(oldEnum, newEnum) {
460
- const changes = [];
461
- const oldNames = oldEnum.getValues().map((v) => v.name);
462
- const newNames = newEnum.getValues().map((v) => v.name);
463
- const added = diffArrays(newNames, oldNames).map((name) => newEnum.getValue(name));
464
- const removed = diffArrays(oldNames, newNames).map((name) => oldEnum.getValue(name));
465
- const common = unionArrays(oldNames, newNames).map((name) => ({
466
- oldValue: oldEnum.getValue(name),
467
- newValue: newEnum.getValue(name),
468
- }));
469
- changes.push(...added.map((v) => enumValueAdded(newEnum, v)));
470
- changes.push(...removed.map((v) => enumValueRemoved(oldEnum, v)));
471
- common.forEach(({ oldValue, newValue }) => {
472
- if (isNotEqual(oldValue.description, newValue.description)) {
473
- changes.push(enumValueDescriptionChanged(newEnum, oldValue, newValue));
474
- }
475
- if (isNotEqual(oldValue.deprecationReason, newValue.deprecationReason)) {
476
- changes.push(enumValueDeprecationReasonChanged(newEnum, oldValue, newValue));
477
- }
630
+ function changesInEnum(oldEnum, newEnum, addChange) {
631
+ compareLists(oldEnum.getValues(), newEnum.getValues(), {
632
+ onAdded(value) {
633
+ addChange(enumValueAdded(newEnum, value));
634
+ },
635
+ onRemoved(value) {
636
+ addChange(enumValueRemoved(oldEnum, value));
637
+ },
638
+ onMutual(value) {
639
+ const oldValue = value.oldVersion;
640
+ const newValue = value.newVersion;
641
+ if (isNotEqual(oldValue.description, newValue.description)) {
642
+ addChange(enumValueDescriptionChanged(newEnum, oldValue, newValue));
643
+ }
644
+ if (isNotEqual(oldValue.deprecationReason, newValue.deprecationReason)) {
645
+ if (isVoid(oldValue.deprecationReason)) {
646
+ addChange(enumValueDeprecationReasonAdded(newEnum, oldValue, newValue));
647
+ }
648
+ else if (isVoid(newValue.deprecationReason)) {
649
+ addChange(enumValueDeprecationReasonRemoved(newEnum, oldValue, newValue));
650
+ }
651
+ else {
652
+ addChange(enumValueDeprecationReasonChanged(newEnum, oldValue, newValue));
653
+ }
654
+ }
655
+ },
478
656
  });
479
- return changes;
480
657
  }
481
658
 
482
659
  function unionMemberRemoved(union, type) {
@@ -502,17 +679,81 @@ function unionMemberAdded(union, type) {
502
679
  };
503
680
  }
504
681
 
505
- function changesInUnion(oldUnion, newUnion) {
506
- const changes = [];
682
+ function changesInUnion(oldUnion, newUnion, addChange) {
507
683
  const oldTypes = oldUnion.getTypes();
508
684
  const newTypes = newUnion.getTypes();
509
- const oldTypenames = oldTypes.map((t) => t.name);
510
- const newTypenames = newTypes.map((t) => t.name);
511
- const added = diffArrays(newTypenames, oldTypenames).map((name) => newTypes.find((t) => t.name === name));
512
- const removed = diffArrays(oldTypenames, newTypenames).map((name) => oldTypes.find((t) => t.name === name));
513
- changes.push(...added.map((type) => unionMemberAdded(newUnion, type)));
514
- changes.push(...removed.map((type) => unionMemberRemoved(oldUnion, type)));
515
- return changes;
685
+ compareLists(oldTypes, newTypes, {
686
+ onAdded(t) {
687
+ addChange(unionMemberAdded(newUnion, t));
688
+ },
689
+ onRemoved(t) {
690
+ addChange(unionMemberRemoved(oldUnion, t));
691
+ },
692
+ });
693
+ }
694
+
695
+ function compareTwoStrings(str1, str2) {
696
+ if (!str1.length && !str2.length)
697
+ return 1;
698
+ if (!str1.length || !str2.length)
699
+ return 0;
700
+ if (str1.toUpperCase() === str2.toUpperCase())
701
+ return 1;
702
+ if (str1.length === 1 && str2.length === 1)
703
+ return 0;
704
+ const pairs1 = wordLetterPairs(str1);
705
+ const pairs2 = wordLetterPairs(str2);
706
+ const union = pairs1.length + pairs2.length;
707
+ let intersection = 0;
708
+ pairs1.forEach(pair1 => {
709
+ for (let i = 0, pair2; (pair2 = pairs2[i]); i++) {
710
+ if (pair1 !== pair2)
711
+ continue;
712
+ intersection++;
713
+ pairs2.splice(i, 1);
714
+ break;
715
+ }
716
+ });
717
+ return (intersection * 2) / union;
718
+ }
719
+ function findBestMatch(mainString, targetStrings) {
720
+ if (!areArgsValid(mainString, targetStrings))
721
+ throw new Error('Bad arguments: First argument should be a string, second should be an array of strings');
722
+ const ratings = targetStrings.map(target => ({
723
+ target,
724
+ rating: compareTwoStrings(mainString, target.value),
725
+ }));
726
+ const bestMatch = Array.from(ratings).sort((a, b) => b.rating - a.rating)[0];
727
+ return { ratings, bestMatch };
728
+ }
729
+ function flattenDeep(arr) {
730
+ return Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
731
+ }
732
+ function areArgsValid(mainString, targetStrings) {
733
+ if (typeof mainString !== 'string')
734
+ return false;
735
+ if (!Array.isArray(targetStrings))
736
+ return false;
737
+ if (!targetStrings.length)
738
+ return false;
739
+ if (targetStrings.find(s => typeof s.value !== 'string'))
740
+ return false;
741
+ return true;
742
+ }
743
+ function letterPairs(str) {
744
+ const pairs = [];
745
+ for (let i = 0, max = str.length - 1; i < max; i++)
746
+ pairs[i] = str.substring(i, i + 2);
747
+ return pairs;
748
+ }
749
+ function wordLetterPairs(str) {
750
+ const pairs = str.toUpperCase().split(' ').map(letterPairs);
751
+ return flattenDeep(pairs);
752
+ }
753
+ function safeString(obj) {
754
+ return inspect(obj)
755
+ .replace(/\[Object\: null prototype\] /g, '')
756
+ .replace(/(^')|('$)/g, '');
516
757
  }
517
758
 
518
759
  function inputFieldRemoved(input, field) {
@@ -522,7 +763,7 @@ function inputFieldRemoved(input, field) {
522
763
  reason: 'Removing an input field will cause existing queries that use this input field to error.',
523
764
  },
524
765
  type: exports.ChangeType.InputFieldRemoved,
525
- message: `Input field '${field.name}' was removed from input object type '${input.name}'`,
766
+ message: `Input field '${field.name}' ${isDeprecated(field) ? '(deprecated) ' : ''}was removed from input object type '${input.name}'`,
526
767
  path: [input.name, field.name].join('.'),
527
768
  };
528
769
  }
@@ -531,7 +772,7 @@ function inputFieldAdded(input, field) {
531
772
  criticality: graphql.isNonNullType(field.type)
532
773
  ? {
533
774
  level: exports.CriticalityLevel.Breaking,
534
- reason: 'Adding a possible type to Unions may break existing clients that were not programming defensively against a new possible type.',
775
+ reason: 'Adding a required input field to an existing input object type is a breaking change because it will cause existing uses of this input object type to error.',
535
776
  }
536
777
  : {
537
778
  level: exports.CriticalityLevel.Dangerous,
@@ -575,10 +816,10 @@ function inputFieldDefaultValueChanged(input, oldField, newField) {
575
816
  return {
576
817
  criticality: {
577
818
  level: exports.CriticalityLevel.Dangerous,
578
- reason: 'Changing the default value for an argument may change the runtime behaviour of a field if it was never provided.',
819
+ reason: 'Changing the default value for an argument may change the runtime behavior of a field if it was never provided.',
579
820
  },
580
821
  type: exports.ChangeType.InputFieldDefaultValueChanged,
581
- message: `Input field '${input.name}.${oldField.name}' default value changed from '${oldField.defaultValue}' to '${newField.defaultValue}'`,
822
+ message: `Input field '${input.name}.${oldField.name}' default value changed from '${safeString(oldField.defaultValue)}' to '${safeString(newField.defaultValue)}'`,
582
823
  path: [input.name, oldField.name].join('.'),
583
824
  };
584
825
  }
@@ -599,55 +840,46 @@ function inputFieldTypeChanged(input, oldField, newField) {
599
840
  };
600
841
  }
601
842
 
602
- function changesInInputObject(oldInput, newInput) {
603
- const changes = [];
843
+ function changesInInputObject(oldInput, newInput, addChange) {
604
844
  const oldFields = oldInput.getFields();
605
845
  const newFields = newInput.getFields();
606
- const oldNames = Object.keys(oldFields).map((name) => oldFields[name].name);
607
- const newNames = Object.keys(newFields).map((name) => newFields[name].name);
608
- const added = diffArrays(newNames, oldNames).map((name) => newFields[name]);
609
- const removed = diffArrays(oldNames, newNames).map((name) => oldFields[name]);
610
- const common = unionArrays(oldNames, newNames).map((name) => ({
611
- inOld: oldFields[name],
612
- inNew: newFields[name],
613
- }));
614
- common.forEach(({ inOld, inNew }) => {
615
- changes.push(...changesInInputField(oldInput, inOld, inNew));
846
+ compareLists(Object.values(oldFields), Object.values(newFields), {
847
+ onAdded(field) {
848
+ addChange(inputFieldAdded(newInput, field));
849
+ },
850
+ onRemoved(field) {
851
+ addChange(inputFieldRemoved(oldInput, field));
852
+ },
853
+ onMutual(field) {
854
+ changesInInputField(oldInput, field.oldVersion, field.newVersion, addChange);
855
+ },
616
856
  });
617
- changes.push(...added.map((field) => inputFieldAdded(newInput, field)));
618
- changes.push(...removed.map((field) => inputFieldRemoved(oldInput, field)));
619
- return changes;
620
857
  }
621
- function changesInInputField(input, oldField, newField) {
622
- const changes = [];
858
+ function changesInInputField(input, oldField, newField, addChange) {
623
859
  if (isNotEqual(oldField.description, newField.description)) {
624
860
  if (isVoid(oldField.description)) {
625
- changes.push(inputFieldDescriptionAdded(input, newField));
861
+ addChange(inputFieldDescriptionAdded(input, newField));
626
862
  }
627
863
  else if (isVoid(newField.description)) {
628
- changes.push(inputFieldDescriptionRemoved(input, oldField));
864
+ addChange(inputFieldDescriptionRemoved(input, oldField));
629
865
  }
630
866
  else {
631
- changes.push(inputFieldDescriptionChanged(input, oldField, newField));
867
+ addChange(inputFieldDescriptionChanged(input, oldField, newField));
632
868
  }
633
869
  }
634
870
  if (isNotEqual(oldField.defaultValue, newField.defaultValue)) {
635
- if (Array.isArray(oldField.defaultValue) &&
636
- Array.isArray(newField.defaultValue)) {
871
+ if (Array.isArray(oldField.defaultValue) && Array.isArray(newField.defaultValue)) {
637
872
  if (diffArrays(oldField.defaultValue, newField.defaultValue).length > 0) {
638
- changes.push(inputFieldDefaultValueChanged(input, oldField, newField));
873
+ addChange(inputFieldDefaultValueChanged(input, oldField, newField));
639
874
  }
640
875
  }
641
- else if (JSON.stringify(oldField.defaultValue) !==
642
- JSON.stringify(newField.defaultValue)) {
643
- changes.push(inputFieldDefaultValueChanged(input, oldField, newField));
876
+ else if (JSON.stringify(oldField.defaultValue) !== JSON.stringify(newField.defaultValue)) {
877
+ addChange(inputFieldDefaultValueChanged(input, oldField, newField));
644
878
  }
645
879
  }
646
880
  if (isNotEqual(oldField.type.toString(), newField.type.toString())) {
647
- changes.push(inputFieldTypeChanged(input, oldField, newField));
881
+ addChange(inputFieldTypeChanged(input, oldField, newField));
648
882
  }
649
- // TODO: diff directives
650
- return changes;
651
883
  }
652
884
 
653
885
  function objectTypeInterfaceAdded(iface, type) {
@@ -683,7 +915,7 @@ function fieldRemoved(type, field) {
683
915
  : `Removing a field is a breaking change. It is preferable to deprecate the field before removing it.`,
684
916
  },
685
917
  type: exports.ChangeType.FieldRemoved,
686
- message: `Field '${field.name}' ${field.isDeprecated ? '(deprecated) ' : ''}was removed from ${entity} '${type.name}'`,
918
+ message: `Field '${field.name}' ${isDeprecated(field) ? '(deprecated) ' : ''}was removed from ${entity} '${type.name}'`,
687
919
  path: [type.name, field.name].join('.'),
688
920
  };
689
921
  }
@@ -791,8 +1023,10 @@ function fieldTypeChanged(type, oldField, newField) {
791
1023
  };
792
1024
  }
793
1025
  function fieldArgumentAdded(type, field, arg) {
1026
+ const isBreaking = graphql.isNonNullType(arg.type) && typeof arg.defaultValue === 'undefined';
1027
+ const defaultValueMsg = typeof arg.defaultValue !== 'undefined' ? ' (with default value) ' : ' ';
794
1028
  return {
795
- criticality: graphql.isNonNullType(arg.type)
1029
+ criticality: isBreaking
796
1030
  ? {
797
1031
  level: exports.CriticalityLevel.Breaking,
798
1032
  reason: `Adding a required argument to an existing field is a breaking change because it will cause existing uses of this field to error.`,
@@ -802,7 +1036,7 @@ function fieldArgumentAdded(type, field, arg) {
802
1036
  reason: `Adding a new argument to an existing field may involve a change in resolve function logic that potentially may cause some side effects.`,
803
1037
  },
804
1038
  type: exports.ChangeType.FieldArgumentAdded,
805
- message: `Argument '${arg.name}: ${arg.type}' added to field '${type.name}.${field.name}'`,
1039
+ message: `Argument '${arg.name}: ${arg.type}'${defaultValueMsg}added to field '${type.name}.${field.name}'`,
806
1040
  path: [type.name, field.name, arg.name].join('.'),
807
1041
  };
808
1042
  }
@@ -836,8 +1070,8 @@ function fieldArgumentDefaultChanged(type, field, oldArg, newArg) {
836
1070
  },
837
1071
  type: exports.ChangeType.FieldArgumentDefaultChanged,
838
1072
  message: typeof oldArg.defaultValue === 'undefined'
839
- ? `Default value '${newArg.defaultValue}' was added to argument '${newArg.name}' on field '${type.name}.${field.name}'`
840
- : `Default value for argument '${newArg.name}' on field '${type.name}.${field.name}' changed from '${oldArg.defaultValue}' to '${newArg.defaultValue}'`,
1073
+ ? `Default value '${safeString(newArg.defaultValue)}' was added to argument '${newArg.name}' on field '${type.name}.${field.name}'`
1074
+ : `Default value for argument '${newArg.name}' on field '${type.name}.${field.name}' changed from '${safeString(oldArg.defaultValue)}' to '${safeString(newArg.defaultValue)}'`,
841
1075
  path: [type.name, field.name, oldArg.name].join('.'),
842
1076
  };
843
1077
  }
@@ -858,340 +1092,254 @@ function fieldArgumentTypeChanged(type, field, oldArg, newArg) {
858
1092
  };
859
1093
  }
860
1094
 
861
- function changesInArgument(type, field, oldArg, newArg) {
862
- const changes = [];
1095
+ function changesInArgument(type, field, oldArg, newArg, addChange) {
863
1096
  if (isNotEqual(oldArg.description, newArg.description)) {
864
- changes.push(fieldArgumentDescriptionChanged(type, field, oldArg, newArg));
1097
+ addChange(fieldArgumentDescriptionChanged(type, field, oldArg, newArg));
865
1098
  }
866
1099
  if (isNotEqual(oldArg.defaultValue, newArg.defaultValue)) {
867
- if (Array.isArray(oldArg.defaultValue) &&
868
- Array.isArray(newArg.defaultValue)) {
1100
+ if (Array.isArray(oldArg.defaultValue) && Array.isArray(newArg.defaultValue)) {
869
1101
  const diff = diffArrays(oldArg.defaultValue, newArg.defaultValue);
870
1102
  if (diff.length > 0) {
871
- changes.push(fieldArgumentDefaultChanged(type, field, oldArg, newArg));
1103
+ addChange(fieldArgumentDefaultChanged(type, field, oldArg, newArg));
872
1104
  }
873
1105
  }
874
- else if (JSON.stringify(oldArg.defaultValue) !==
875
- JSON.stringify(newArg.defaultValue)) {
876
- changes.push(fieldArgumentDefaultChanged(type, field, oldArg, newArg));
1106
+ else if (JSON.stringify(oldArg.defaultValue) !== JSON.stringify(newArg.defaultValue)) {
1107
+ addChange(fieldArgumentDefaultChanged(type, field, oldArg, newArg));
877
1108
  }
878
1109
  }
879
1110
  if (isNotEqual(oldArg.type.toString(), newArg.type.toString())) {
880
- changes.push(fieldArgumentTypeChanged(type, field, oldArg, newArg));
1111
+ addChange(fieldArgumentTypeChanged(type, field, oldArg, newArg));
881
1112
  }
882
- return changes;
883
1113
  }
884
1114
 
885
- function changesInField(type, oldField, newField) {
886
- const changes = [];
1115
+ function changesInField(type, oldField, newField, addChange) {
887
1116
  if (isNotEqual(oldField.description, newField.description)) {
888
1117
  if (isVoid(oldField.description)) {
889
- changes.push(fieldDescriptionAdded(type, newField));
1118
+ addChange(fieldDescriptionAdded(type, newField));
890
1119
  }
891
1120
  else if (isVoid(newField.description)) {
892
- changes.push(fieldDescriptionRemoved(type, oldField));
1121
+ addChange(fieldDescriptionRemoved(type, oldField));
893
1122
  }
894
1123
  else {
895
- changes.push(fieldDescriptionChanged(type, oldField, newField));
1124
+ addChange(fieldDescriptionChanged(type, oldField, newField));
896
1125
  }
897
1126
  }
898
- if (isNotEqual(oldField.isDeprecated, newField.isDeprecated)) {
899
- if (newField.isDeprecated) {
900
- changes.push(fieldDeprecationAdded(type, newField));
1127
+ if (isNotEqual(isDeprecated(oldField), isDeprecated(newField))) {
1128
+ if (isDeprecated(newField)) {
1129
+ addChange(fieldDeprecationAdded(type, newField));
901
1130
  }
902
1131
  else {
903
- changes.push(fieldDeprecationRemoved(type, oldField));
1132
+ addChange(fieldDeprecationRemoved(type, oldField));
904
1133
  }
905
1134
  }
906
1135
  if (isNotEqual(oldField.deprecationReason, newField.deprecationReason)) {
907
1136
  if (isVoid(oldField.deprecationReason)) {
908
- changes.push(fieldDeprecationReasonAdded(type, newField));
1137
+ addChange(fieldDeprecationReasonAdded(type, newField));
909
1138
  }
910
1139
  else if (isVoid(newField.deprecationReason)) {
911
- changes.push(fieldDeprecationReasonRemoved(type, oldField));
1140
+ addChange(fieldDeprecationReasonRemoved(type, oldField));
912
1141
  }
913
1142
  else {
914
- changes.push(fieldDeprecationReasonChanged(type, oldField, newField));
1143
+ addChange(fieldDeprecationReasonChanged(type, oldField, newField));
915
1144
  }
916
1145
  }
917
1146
  if (isNotEqual(oldField.type.toString(), newField.type.toString())) {
918
- changes.push(fieldTypeChanged(type, oldField, newField));
919
- }
920
- const oldArgs = oldField.args;
921
- const newArgs = newField.args;
922
- const oldNames = oldArgs.map((a) => a.name);
923
- const newNames = newArgs.map((a) => a.name);
924
- const added = diffArrays(newNames, oldNames).map((name) => newArgs.find((a) => a.name === name));
925
- const removed = diffArrays(oldNames, newNames).map((name) => oldArgs.find((a) => a.name === name));
926
- const common = unionArrays(oldNames, newNames).map((name) => ({
927
- inOld: oldArgs.find((a) => a.name === name),
928
- inNew: newArgs.find((a) => a.name === name),
929
- }));
930
- common.forEach(({ inOld, inNew }) => {
931
- changes.push(...changesInArgument(type, oldField, inOld, inNew));
1147
+ addChange(fieldTypeChanged(type, oldField, newField));
1148
+ }
1149
+ compareLists(oldField.args, newField.args, {
1150
+ onAdded(arg) {
1151
+ addChange(fieldArgumentAdded(type, newField, arg));
1152
+ },
1153
+ onRemoved(arg) {
1154
+ addChange(fieldArgumentRemoved(type, oldField, arg));
1155
+ },
1156
+ onMutual(arg) {
1157
+ changesInArgument(type, oldField, arg.oldVersion, arg.newVersion, addChange);
1158
+ },
932
1159
  });
933
- changes.push(...added.map((arg) => fieldArgumentAdded(type, newField, arg)));
934
- changes.push(...removed.map((arg) => fieldArgumentRemoved(type, oldField, arg)));
935
- return changes;
936
1160
  }
937
1161
 
938
- function changesInObject(oldType, newType) {
939
- const changes = [];
940
- // Interfaces
941
- changes.push(...addedInterfaces(oldType, newType));
942
- changes.push(...removedInterfaces(oldType, newType));
943
- // Fields
944
- changes.push(...addedFields(oldType, newType));
945
- changes.push(...removedFields(oldType, newType));
946
- changedFields(oldType, newType).forEach(({ inOld, inNew }) => {
947
- changes.push(...changesInField(oldType, inOld, inNew));
948
- });
949
- return changes;
950
- }
951
- function addedInterfaces(oldType, newType) {
952
- const oldInterfaces = oldType.getInterfaces();
953
- const newInterfaces = newType.getInterfaces();
954
- const oldNames = oldInterfaces.map((i) => i.name);
955
- const newNames = newInterfaces.map((i) => i.name);
956
- return diffArrays(newNames, oldNames)
957
- .map((name) => newInterfaces.find((i) => i.name === name))
958
- .map((i) => objectTypeInterfaceAdded(i, newType));
959
- }
960
- function removedInterfaces(oldType, newType) {
1162
+ function changesInObject(oldType, newType, addChange) {
961
1163
  const oldInterfaces = oldType.getInterfaces();
962
1164
  const newInterfaces = newType.getInterfaces();
963
- const oldNames = oldInterfaces.map((i) => i.name);
964
- const newNames = newInterfaces.map((i) => i.name);
965
- return diffArrays(oldNames, newNames)
966
- .map((name) => oldInterfaces.find((i) => i.name === name))
967
- .map((i) => objectTypeInterfaceRemoved(i, newType));
968
- }
969
- function addedFields(oldType, newType) {
970
- const oldFields = oldType.getFields();
971
- const newFields = newType.getFields();
972
- const oldNames = Object.keys(oldFields);
973
- const newNames = Object.keys(newFields);
974
- return diffArrays(newNames, oldNames)
975
- .map((name) => newFields[name])
976
- .map((f) => fieldAdded(newType, f));
977
- }
978
- function removedFields(oldType, newType) {
979
- const oldFields = oldType.getFields();
980
- const newFields = newType.getFields();
981
- const oldNames = Object.keys(oldFields);
982
- const newNames = Object.keys(newFields);
983
- return diffArrays(oldNames, newNames)
984
- .map((name) => oldFields[name])
985
- .map((f) => fieldRemoved(oldType, f));
986
- }
987
- function changedFields(oldType, newType) {
988
1165
  const oldFields = oldType.getFields();
989
1166
  const newFields = newType.getFields();
990
- const oldNames = Object.keys(oldFields);
991
- const newNames = Object.keys(newFields);
992
- return unionArrays(oldNames, newNames).map((name) => ({
993
- inOld: oldFields[name],
994
- inNew: newFields[name],
995
- }));
1167
+ compareLists(oldInterfaces, newInterfaces, {
1168
+ onAdded(i) {
1169
+ addChange(objectTypeInterfaceAdded(i, newType));
1170
+ },
1171
+ onRemoved(i) {
1172
+ addChange(objectTypeInterfaceRemoved(i, oldType));
1173
+ },
1174
+ });
1175
+ compareLists(Object.values(oldFields), Object.values(newFields), {
1176
+ onAdded(f) {
1177
+ addChange(fieldAdded(newType, f));
1178
+ },
1179
+ onRemoved(f) {
1180
+ addChange(fieldRemoved(oldType, f));
1181
+ },
1182
+ onMutual(f) {
1183
+ changesInField(oldType, f.oldVersion, f.newVersion, addChange);
1184
+ },
1185
+ });
996
1186
  }
997
1187
 
998
- function changesInInterface(oldInterface, newInterface) {
999
- const changes = [];
1000
- changes.push(...addedFields$1(oldInterface, newInterface));
1001
- changes.push(...removedFields$1(oldInterface, newInterface));
1002
- changedFields$1(oldInterface, newInterface).forEach(({ inOld, inNew }) => {
1003
- changes.push(...changesInField(oldInterface, inOld, inNew));
1188
+ function changesInInterface(oldInterface, newInterface, addChange) {
1189
+ compareLists(Object.values(oldInterface.getFields()), Object.values(newInterface.getFields()), {
1190
+ onAdded(field) {
1191
+ addChange(fieldAdded(newInterface, field));
1192
+ },
1193
+ onRemoved(field) {
1194
+ addChange(fieldRemoved(oldInterface, field));
1195
+ },
1196
+ onMutual(field) {
1197
+ changesInField(oldInterface, field.oldVersion, field.newVersion, addChange);
1198
+ },
1004
1199
  });
1005
- return changes;
1006
- }
1007
- function addedFields$1(oldInterface, newInterface) {
1008
- const oldFields = oldInterface.getFields();
1009
- const newFields = newInterface.getFields();
1010
- const oldNames = Object.keys(oldFields);
1011
- const newNames = Object.keys(newFields);
1012
- return diffArrays(newNames, oldNames)
1013
- .map((name) => newFields[name])
1014
- .map((f) => fieldAdded(newInterface, f));
1015
- }
1016
- function removedFields$1(oldInterface, newInterface) {
1017
- const oldFields = oldInterface.getFields();
1018
- const newFields = newInterface.getFields();
1019
- const oldNames = Object.keys(oldFields);
1020
- const newNames = Object.keys(newFields);
1021
- return diffArrays(oldNames, newNames)
1022
- .map((name) => oldFields[name])
1023
- .map((f) => fieldRemoved(oldInterface, f));
1024
- }
1025
- function changedFields$1(oldInterface, newInterface) {
1026
- const oldFields = oldInterface.getFields();
1027
- const newFields = newInterface.getFields();
1028
- const oldNames = Object.keys(oldFields);
1029
- const newNames = Object.keys(newFields);
1030
- return unionArrays(oldNames, newNames).map((name) => ({
1031
- inOld: oldFields[name],
1032
- inNew: newFields[name],
1033
- }));
1034
1200
  }
1035
1201
 
1036
- function changesInDirective(oldDirective, newDirective) {
1037
- const changes = [];
1202
+ function changesInDirective(oldDirective, newDirective, addChange) {
1038
1203
  if (isNotEqual(oldDirective.description, newDirective.description)) {
1039
- changes.push(directiveDescriptionChanged(oldDirective, newDirective));
1204
+ addChange(directiveDescriptionChanged(oldDirective, newDirective));
1040
1205
  }
1206
+ const locations = {
1207
+ added: diffArrays(newDirective.locations, oldDirective.locations),
1208
+ removed: diffArrays(oldDirective.locations, newDirective.locations),
1209
+ };
1041
1210
  // locations added
1042
- changes.push(...diffArrays(newDirective.locations, oldDirective.locations).map((location) => directiveLocationAdded(newDirective, location)));
1211
+ locations.added.forEach(location => addChange(directiveLocationAdded(newDirective, location)));
1043
1212
  // locations removed
1044
- changes.push(...diffArrays(oldDirective.locations, newDirective.locations).map((location) => directiveLocationRemoved(oldDirective, location)));
1045
- const oldNames = oldDirective.args.map((a) => a.name);
1046
- const newNames = newDirective.args.map((a) => a.name);
1047
- // arguments added
1048
- changes.push(...diffArrays(newNames, oldNames).map((name) => directiveArgumentAdded(newDirective, newDirective.args.find((a) => a.name === name))));
1049
- // arguments removed
1050
- changes.push(...diffArrays(oldNames, newNames).map((name) => directiveArgumentRemoved(oldDirective, oldDirective.args.find((a) => a.name === name))));
1051
- // common arguments
1052
- unionArrays(oldNames, newNames).forEach((name) => {
1053
- const oldArg = oldDirective.args.find((a) => a.name === name);
1054
- const newArg = newDirective.args.find((a) => a.name === name);
1055
- changes.push(...changesInDirectiveArgument(oldDirective, oldArg, newArg));
1213
+ locations.removed.forEach(location => addChange(directiveLocationRemoved(oldDirective, location)));
1214
+ compareLists(oldDirective.args, newDirective.args, {
1215
+ onAdded(arg) {
1216
+ addChange(directiveArgumentAdded(newDirective, arg));
1217
+ },
1218
+ onRemoved(arg) {
1219
+ addChange(directiveArgumentRemoved(oldDirective, arg));
1220
+ },
1221
+ onMutual(arg) {
1222
+ changesInDirectiveArgument(oldDirective, arg.oldVersion, arg.newVersion, addChange);
1223
+ },
1056
1224
  });
1057
- return changes;
1058
1225
  }
1059
- function changesInDirectiveArgument(directive, oldArg, newArg) {
1060
- const changes = [];
1226
+ function changesInDirectiveArgument(directive, oldArg, newArg, addChange) {
1061
1227
  if (isNotEqual(oldArg.description, newArg.description)) {
1062
- changes.push(directiveArgumentDescriptionChanged(directive, oldArg, newArg));
1228
+ addChange(directiveArgumentDescriptionChanged(directive, oldArg, newArg));
1063
1229
  }
1064
1230
  if (isNotEqual(oldArg.defaultValue, newArg.defaultValue)) {
1065
- changes.push(directiveArgumentDefaultValueChanged(directive, oldArg, newArg));
1231
+ addChange(directiveArgumentDefaultValueChanged(directive, oldArg, newArg));
1066
1232
  }
1067
1233
  if (isNotEqual(oldArg.type.toString(), newArg.type.toString())) {
1068
- changes.push(directiveArgumentTypeChanged(directive, oldArg, newArg));
1234
+ addChange(directiveArgumentTypeChanged(directive, oldArg, newArg));
1069
1235
  }
1070
- return changes;
1071
1236
  }
1072
1237
 
1073
1238
  function diffSchema(oldSchema, newSchema) {
1074
1239
  const changes = [];
1075
- const types = diffTypes(oldSchema, newSchema);
1076
- const directives = diffDirectives(oldSchema, newSchema);
1077
- // Added and removed types
1078
- changes.push(...types.added.map(typeAdded));
1079
- changes.push(...types.removed.map(typeRemoved));
1080
- // Added and removed directives
1081
- changes.push(...directives.added.map(directiveAdded));
1082
- changes.push(...directives.removed.map(directiveRemoved));
1083
- // Changes in Schema
1084
- changes.push(...changesInSchema(oldSchema, newSchema));
1085
- // Changes in Type
1086
- types.common.forEach(({ inOld, inNew }) => {
1087
- changes.push(...changesInType(inOld, inNew));
1240
+ function addChange(change) {
1241
+ changes.push(change);
1242
+ }
1243
+ changesInSchema(oldSchema, newSchema, addChange);
1244
+ compareLists(Object.values(oldSchema.getTypeMap()).filter(t => !isPrimitive(t)), Object.values(newSchema.getTypeMap()).filter(t => !isPrimitive(t)), {
1245
+ onAdded(type) {
1246
+ addChange(typeAdded(type));
1247
+ },
1248
+ onRemoved(type) {
1249
+ addChange(typeRemoved(type));
1250
+ },
1251
+ onMutual(type) {
1252
+ changesInType(type.oldVersion, type.newVersion, addChange);
1253
+ },
1088
1254
  });
1089
- // Changes in Directives
1090
- directives.common.forEach(({ inOld, inNew }) => {
1091
- changes.push(...changesInDirective(inOld, inNew));
1255
+ compareLists(oldSchema.getDirectives(), newSchema.getDirectives(), {
1256
+ onAdded(directive) {
1257
+ addChange(directiveAdded(directive));
1258
+ },
1259
+ onRemoved(directive) {
1260
+ addChange(directiveRemoved(directive));
1261
+ },
1262
+ onMutual(directive) {
1263
+ changesInDirective(directive.oldVersion, directive.newVersion, addChange);
1264
+ },
1092
1265
  });
1093
1266
  return changes;
1094
1267
  }
1095
- function diffTypes(oldSchema, newSchema) {
1096
- const oldTypeMap = oldSchema.getTypeMap();
1097
- const newTypeMap = newSchema.getTypeMap();
1098
- const oldTypenames = Object.keys(oldTypeMap).filter((name) => !isPrimitive(name));
1099
- const newTypenames = Object.keys(newTypeMap).filter((name) => !isPrimitive(name));
1100
- const added = diffArrays(newTypenames, oldTypenames).map((name) => newTypeMap[name]);
1101
- const removed = diffArrays(oldTypenames, newTypenames).map((name) => oldTypeMap[name]);
1102
- const common = unionArrays(oldTypenames, newTypenames).map((name) => ({
1103
- inOld: oldTypeMap[name],
1104
- inNew: newTypeMap[name],
1105
- }));
1106
- return {
1107
- added,
1108
- removed,
1109
- common,
1268
+ function changesInSchema(oldSchema, newSchema, addChange) {
1269
+ var _a, _b, _c, _d, _e, _f;
1270
+ const defaultNames = {
1271
+ query: 'Query',
1272
+ mutation: 'Mutation',
1273
+ subscription: 'Subscription',
1110
1274
  };
1111
- }
1112
- function diffDirectives(oldSchema, newSchema) {
1113
- const oldDirectives = oldSchema.getDirectives();
1114
- const newDirectives = newSchema.getDirectives();
1115
- const oldNames = oldDirectives.map((d) => d.name);
1116
- const newNames = newDirectives.map((d) => d.name);
1117
- const added = diffArrays(newNames, oldNames).map((name) => newDirectives.find((d) => d.name === name));
1118
- const removed = diffArrays(oldNames, newNames).map((name) => oldDirectives.find((d) => d.name === name));
1119
- const common = unionArrays(oldNames, newNames).map((name) => ({
1120
- inOld: oldDirectives.find((d) => d.name === name),
1121
- inNew: newDirectives.find((d) => d.name === name),
1122
- }));
1123
- return {
1124
- added,
1125
- removed,
1126
- common,
1127
- };
1128
- }
1129
- function changesInSchema(oldSchema, newSchema) {
1130
- const changes = [];
1131
1275
  const oldRoot = {
1132
- query: (oldSchema.getQueryType() || {}).name,
1133
- mutation: (oldSchema.getMutationType() || {}).name,
1134
- subscription: (oldSchema.getSubscriptionType() || {})
1135
- .name,
1276
+ query: (_a = (oldSchema.getQueryType() || {}).name) !== null && _a !== void 0 ? _a : defaultNames.query,
1277
+ mutation: (_b = (oldSchema.getMutationType() || {}).name) !== null && _b !== void 0 ? _b : defaultNames.mutation,
1278
+ subscription: (_c = (oldSchema.getSubscriptionType() || {}).name) !== null && _c !== void 0 ? _c : defaultNames.subscription,
1136
1279
  };
1137
1280
  const newRoot = {
1138
- query: (newSchema.getQueryType() || {}).name,
1139
- mutation: (newSchema.getMutationType() || {}).name,
1140
- subscription: (newSchema.getSubscriptionType() || {})
1141
- .name,
1281
+ query: (_d = (newSchema.getQueryType() || {}).name) !== null && _d !== void 0 ? _d : defaultNames.query,
1282
+ mutation: (_e = (newSchema.getMutationType() || {}).name) !== null && _e !== void 0 ? _e : defaultNames.mutation,
1283
+ subscription: (_f = (newSchema.getSubscriptionType() || {}).name) !== null && _f !== void 0 ? _f : defaultNames.subscription,
1142
1284
  };
1143
1285
  if (isNotEqual(oldRoot.query, newRoot.query)) {
1144
- changes.push(schemaQueryTypeChanged(oldSchema, newSchema));
1286
+ addChange(schemaQueryTypeChanged(oldSchema, newSchema));
1145
1287
  }
1146
1288
  if (isNotEqual(oldRoot.mutation, newRoot.mutation)) {
1147
- changes.push(schemaMutationTypeChanged(oldSchema, newSchema));
1289
+ addChange(schemaMutationTypeChanged(oldSchema, newSchema));
1148
1290
  }
1149
1291
  if (isNotEqual(oldRoot.subscription, newRoot.subscription)) {
1150
- changes.push(schemaSubscriptionTypeChanged(oldSchema, newSchema));
1292
+ addChange(schemaSubscriptionTypeChanged(oldSchema, newSchema));
1151
1293
  }
1152
- return changes;
1153
1294
  }
1154
- function changesInType(oldType, newType) {
1155
- let changes = [];
1295
+ function changesInType(oldType, newType, addChange) {
1156
1296
  if (graphql.isEnumType(oldType) && graphql.isEnumType(newType)) {
1157
- changes = changesInEnum(oldType, newType);
1297
+ changesInEnum(oldType, newType, addChange);
1158
1298
  }
1159
1299
  else if (graphql.isUnionType(oldType) && graphql.isUnionType(newType)) {
1160
- changes = changesInUnion(oldType, newType);
1300
+ changesInUnion(oldType, newType, addChange);
1161
1301
  }
1162
1302
  else if (graphql.isInputObjectType(oldType) && graphql.isInputObjectType(newType)) {
1163
- changes = changesInInputObject(oldType, newType);
1303
+ changesInInputObject(oldType, newType, addChange);
1164
1304
  }
1165
1305
  else if (graphql.isObjectType(oldType) && graphql.isObjectType(newType)) {
1166
- changes = changesInObject(oldType, newType);
1306
+ changesInObject(oldType, newType, addChange);
1167
1307
  }
1168
1308
  else if (graphql.isInterfaceType(oldType) && graphql.isInterfaceType(newType)) {
1169
- changes = changesInInterface(oldType, newType);
1309
+ changesInInterface(oldType, newType, addChange);
1170
1310
  }
1171
1311
  else if (graphql.isScalarType(oldType) && graphql.isScalarType(newType)) ;
1172
1312
  else {
1173
- changes = [typeKindChanged(oldType, newType)];
1313
+ addChange(typeKindChanged(oldType, newType));
1174
1314
  }
1175
1315
  if (isNotEqual(oldType.description, newType.description)) {
1176
1316
  if (isVoid(oldType.description)) {
1177
- changes.push(typeDescriptionAdded(newType));
1317
+ addChange(typeDescriptionAdded(newType));
1178
1318
  }
1179
1319
  else if (isVoid(newType.description)) {
1180
- changes.push(typeDescriptionRemoved(oldType));
1320
+ addChange(typeDescriptionRemoved(oldType));
1181
1321
  }
1182
1322
  else {
1183
- changes.push(typeDescriptionChanged(oldType, newType));
1323
+ addChange(typeDescriptionChanged(oldType, newType));
1184
1324
  }
1185
1325
  }
1186
- return changes;
1187
1326
  }
1188
1327
 
1328
+ const dangerousBreaking = ({ changes }) => {
1329
+ return changes.map(change => {
1330
+ if (change.criticality.level === exports.CriticalityLevel.Dangerous) {
1331
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Breaking }) });
1332
+ }
1333
+ return change;
1334
+ });
1335
+ };
1336
+
1189
1337
  function parsePath(path) {
1190
1338
  return path.split('.');
1191
1339
  }
1192
1340
 
1193
- const suppressRemovalOfDeprecatedField = ({ changes, oldSchema, }) => {
1194
- return changes.map((change) => {
1341
+ const suppressRemovalOfDeprecatedField = ({ changes, oldSchema }) => {
1342
+ return changes.map(change => {
1195
1343
  if (change.type === exports.ChangeType.FieldRemoved &&
1196
1344
  change.criticality.level === exports.CriticalityLevel.Breaking &&
1197
1345
  change.path) {
@@ -1199,7 +1347,31 @@ const suppressRemovalOfDeprecatedField = ({ changes, oldSchema, }) => {
1199
1347
  const type = oldSchema.getType(typeName);
1200
1348
  if (graphql.isObjectType(type) || graphql.isInterfaceType(type)) {
1201
1349
  const field = type.getFields()[fieldName];
1202
- if (field.isDeprecated) {
1350
+ if (isDeprecated(field)) {
1351
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }) });
1352
+ }
1353
+ }
1354
+ }
1355
+ if (change.type === exports.ChangeType.EnumValueRemoved &&
1356
+ change.criticality.level === exports.CriticalityLevel.Breaking &&
1357
+ change.path) {
1358
+ const [enumName, enumItem] = parsePath(change.path);
1359
+ const type = oldSchema.getType(enumName);
1360
+ if (graphql.isEnumType(type)) {
1361
+ const item = type.getValue(enumItem);
1362
+ if (item && isDeprecated(item)) {
1363
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }) });
1364
+ }
1365
+ }
1366
+ }
1367
+ if (change.type === exports.ChangeType.InputFieldRemoved &&
1368
+ change.criticality.level === exports.CriticalityLevel.Breaking &&
1369
+ change.path) {
1370
+ const [inputName, inputItem] = parsePath(change.path);
1371
+ const type = oldSchema.getType(inputName);
1372
+ if (graphql.isInputObjectType(type)) {
1373
+ const item = type.getFields()[inputItem];
1374
+ if (item && isDeprecated(item)) {
1203
1375
  return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }) });
1204
1376
  }
1205
1377
  }
@@ -1222,23 +1394,76 @@ const descriptionChangeTypes = [
1222
1394
  exports.ChangeType.TypeDescriptionChanged,
1223
1395
  ];
1224
1396
  const ignoreDescriptionChanges = ({ changes }) => {
1225
- return changes.filter((change) => descriptionChangeTypes.indexOf(change.type) === -1);
1397
+ return changes.filter(change => descriptionChangeTypes.indexOf(change.type) === -1);
1398
+ };
1399
+
1400
+ const considerUsage = ({ changes, config }) => tslib.__awaiter(void 0, void 0, void 0, function* () {
1401
+ if (!config) {
1402
+ throw new Error(`considerUsage rule is missing config`);
1403
+ }
1404
+ const collectedBreakingField = [];
1405
+ changes.forEach(change => {
1406
+ if (change.criticality.level === exports.CriticalityLevel.Breaking && change.path) {
1407
+ const [typeName, fieldName, argumentName] = parsePath(change.path);
1408
+ collectedBreakingField.push({
1409
+ type: typeName,
1410
+ field: fieldName,
1411
+ argument: argumentName,
1412
+ });
1413
+ }
1414
+ });
1415
+ // True if safe to break, false otherwise
1416
+ const usageList = yield config.checkUsage(collectedBreakingField);
1417
+ // turns an array of booleans into an array of `Type.Field` strings
1418
+ // includes only those that are safe to break the api
1419
+ const suppressedPaths = collectedBreakingField
1420
+ .filter((_, i) => usageList[i] === true)
1421
+ .map(({ type, field, argument }) => [type, field, argument].filter(Boolean).join('.'));
1422
+ return changes.map(change => {
1423
+ // Turns those "safe to break" changes into "dangerous"
1424
+ if (change.criticality.level === exports.CriticalityLevel.Breaking &&
1425
+ change.path &&
1426
+ suppressedPaths.some(p => change.path.startsWith(p))) {
1427
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }), message: `${change.message} (non-breaking based on usage)` });
1428
+ }
1429
+ return change;
1430
+ });
1431
+ });
1432
+
1433
+ const safeUnreachable = ({ changes, oldSchema }) => {
1434
+ const reachable = getReachableTypes(oldSchema);
1435
+ return changes.map(change => {
1436
+ if (change.criticality.level === exports.CriticalityLevel.Breaking && change.path) {
1437
+ const [typeName] = parsePath(change.path);
1438
+ if (!reachable.has(typeName)) {
1439
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.NonBreaking }), message: 'Unreachable from root' });
1440
+ }
1441
+ }
1442
+ return change;
1443
+ });
1226
1444
  };
1227
1445
 
1228
1446
  const rules = /*#__PURE__*/Object.freeze({
1229
1447
  __proto__: null,
1448
+ dangerousBreaking: dangerousBreaking,
1230
1449
  suppressRemovalOfDeprecatedField: suppressRemovalOfDeprecatedField,
1231
- ignoreDescriptionChanges: ignoreDescriptionChanges
1450
+ ignoreDescriptionChanges: ignoreDescriptionChanges,
1451
+ considerUsage: considerUsage,
1452
+ safeUnreachable: safeUnreachable
1232
1453
  });
1233
1454
 
1234
1455
  const DiffRule = rules;
1235
- function diff(oldSchema, newSchema, rules = []) {
1456
+ function diff(oldSchema, newSchema, rules = [], config) {
1236
1457
  const changes = diffSchema(oldSchema, newSchema);
1237
- return rules.reduce((prev, rule) => rule({
1238
- changes: prev,
1239
- oldSchema,
1240
- newSchema,
1241
- }), changes);
1458
+ return rules.reduce((prev, rule) => tslib.__awaiter(this, void 0, void 0, function* () {
1459
+ const prevChanges = yield prev;
1460
+ return rule({
1461
+ changes: prevChanges,
1462
+ oldSchema,
1463
+ newSchema,
1464
+ config,
1465
+ });
1466
+ }), Promise.resolve(changes));
1242
1467
  }
1243
1468
 
1244
1469
  function readDocument(source) {
@@ -1314,7 +1539,7 @@ function calculateDepth({ node, currentDepth, maxDepth, getFragment, }) {
1314
1539
  return 1 + maxInnerDepth;
1315
1540
  }
1316
1541
  case graphql.Kind.SELECTION_SET: {
1317
- return Math.max(...node.selections.map((selection) => {
1542
+ return Math.max(...node.selections.map(selection => {
1318
1543
  return calculateDepth({
1319
1544
  node: selection,
1320
1545
  currentDepth: currentDepth,
@@ -1324,7 +1549,7 @@ function calculateDepth({ node, currentDepth, maxDepth, getFragment, }) {
1324
1549
  }));
1325
1550
  }
1326
1551
  case graphql.Kind.DOCUMENT: {
1327
- return Math.max(...node.definitions.map((def) => {
1552
+ return Math.max(...node.definitions.map(def => {
1328
1553
  return calculateDepth({
1329
1554
  node: def,
1330
1555
  currentDepth: currentDepth,
@@ -1336,7 +1561,7 @@ function calculateDepth({ node, currentDepth, maxDepth, getFragment, }) {
1336
1561
  case graphql.Kind.OPERATION_DEFINITION:
1337
1562
  case graphql.Kind.INLINE_FRAGMENT:
1338
1563
  case graphql.Kind.FRAGMENT_DEFINITION: {
1339
- return Math.max(...node.selectionSet.selections.map((selection) => {
1564
+ return Math.max(...node.selectionSet.selections.map(selection => {
1340
1565
  return calculateDepth({
1341
1566
  node: selection,
1342
1567
  currentDepth,
@@ -1357,13 +1582,26 @@ function calculateDepth({ node, currentDepth, maxDepth, getFragment, }) {
1357
1582
  }
1358
1583
  }
1359
1584
  }
1585
+ function countDepth(node, parentDepth, getFragmentReference) {
1586
+ let depth = parentDepth;
1587
+ if ('selectionSet' in node && node.selectionSet) {
1588
+ for (let child of node.selectionSet.selections) {
1589
+ depth = Math.max(depth, countDepth(child, parentDepth + 1, getFragmentReference));
1590
+ }
1591
+ }
1592
+ if (node.kind == graphql.Kind.FRAGMENT_SPREAD) {
1593
+ const fragment = getFragmentReference(node.name.value);
1594
+ if (fragment) {
1595
+ depth = Math.max(depth, countDepth(fragment, parentDepth + 1, getFragmentReference));
1596
+ }
1597
+ }
1598
+ return depth;
1599
+ }
1360
1600
 
1361
1601
  function transformDocumentWithApollo(doc, { keepClientFields }) {
1362
1602
  return graphql.visit(doc, {
1363
1603
  Field(node) {
1364
- return keepClientFields
1365
- ? removeDirectives(node, ['client'])
1366
- : removeFieldIfDirectives(node, ['client']);
1604
+ return keepClientFields ? removeDirectives(node, ['client']) : removeFieldIfDirectives(node, ['client']);
1367
1605
  },
1368
1606
  });
1369
1607
  }
@@ -1373,6 +1611,116 @@ function transformSchemaWithApollo(schema) {
1373
1611
  `));
1374
1612
  }
1375
1613
 
1614
+ function validateAliasCount({ source, doc, maxAliasCount, fragmentGraph, }) {
1615
+ const getFragmentByFragmentName = (fragmentName) => fragmentGraph.getNodeData(fragmentName);
1616
+ for (const definition of doc.definitions) {
1617
+ if (definition.kind !== graphql.Kind.OPERATION_DEFINITION) {
1618
+ continue;
1619
+ }
1620
+ const aliasCount = countAliases(definition, getFragmentByFragmentName);
1621
+ if (aliasCount > maxAliasCount) {
1622
+ return new graphql.GraphQLError(`Too many aliases (${aliasCount}). Maximum allowed is ${maxAliasCount}`, [definition], source, definition.loc && definition.loc.start ? [definition.loc.start] : undefined);
1623
+ }
1624
+ }
1625
+ }
1626
+ function countAliases(node, getFragmentByName) {
1627
+ let aliases = 0;
1628
+ if ('alias' in node && node.alias) {
1629
+ ++aliases;
1630
+ }
1631
+ if ('selectionSet' in node && node.selectionSet) {
1632
+ for (let child of node.selectionSet.selections) {
1633
+ aliases += countAliases(child, getFragmentByName);
1634
+ }
1635
+ }
1636
+ else if (node.kind === graphql.Kind.FRAGMENT_SPREAD) {
1637
+ const fragmentNode = getFragmentByName(node.name.value);
1638
+ if (fragmentNode) {
1639
+ aliases += countAliases(fragmentNode, getFragmentByName);
1640
+ }
1641
+ }
1642
+ return aliases;
1643
+ }
1644
+
1645
+ function validateDirectiveCount({ source, doc, maxDirectiveCount, fragmentGraph, }) {
1646
+ const getFragmentByFragmentName = (fragmentName) => fragmentGraph.getNodeData(fragmentName);
1647
+ for (const definition of doc.definitions) {
1648
+ if (definition.kind !== graphql.Kind.OPERATION_DEFINITION) {
1649
+ continue;
1650
+ }
1651
+ const directiveCount = countDirectives(definition, getFragmentByFragmentName);
1652
+ if (directiveCount > maxDirectiveCount) {
1653
+ return new graphql.GraphQLError(`Too many directives (${directiveCount}). Maximum allowed is ${maxDirectiveCount}`, [definition], source, definition.loc && definition.loc.start ? [definition.loc.start] : undefined);
1654
+ }
1655
+ }
1656
+ }
1657
+ function countDirectives(node, getFragmentByName) {
1658
+ let directives = 0;
1659
+ if (node.directives) {
1660
+ directives += node.directives.length;
1661
+ }
1662
+ if ('selectionSet' in node && node.selectionSet) {
1663
+ for (let child of node.selectionSet.selections) {
1664
+ directives += countDirectives(child, getFragmentByName);
1665
+ }
1666
+ }
1667
+ if (node.kind == graphql.Kind.FRAGMENT_SPREAD) {
1668
+ const fragment = getFragmentByName(node.name.value);
1669
+ if (fragment) {
1670
+ directives += countDirectives(fragment, getFragmentByName);
1671
+ }
1672
+ }
1673
+ return directives;
1674
+ }
1675
+
1676
+ class ParserWithLexer extends parser.Parser {
1677
+ constructor(source, options) {
1678
+ super(source, options);
1679
+ this.__tokenCount = 0;
1680
+ const lexer = this._lexer;
1681
+ this._lexer = new Proxy(lexer, {
1682
+ get: (target, prop, receiver) => {
1683
+ if (prop === 'advance') {
1684
+ return () => {
1685
+ const token = target.advance();
1686
+ if (token.kind !== graphql.TokenKind.EOF) {
1687
+ this.__tokenCount++;
1688
+ }
1689
+ return token;
1690
+ };
1691
+ }
1692
+ return Reflect.get(target, prop, receiver);
1693
+ },
1694
+ });
1695
+ }
1696
+ get tokenCount() {
1697
+ return this.__tokenCount;
1698
+ }
1699
+ }
1700
+ function calculateTokenCount(args) {
1701
+ const parser = new ParserWithLexer(args.source);
1702
+ const document = parser.parseDocument();
1703
+ let { tokenCount } = parser;
1704
+ graphql.visit(document, {
1705
+ FragmentSpread(node) {
1706
+ const fragmentSource = args.getReferencedFragmentSource(node.name.value);
1707
+ if (fragmentSource) {
1708
+ tokenCount += calculateTokenCount({
1709
+ source: fragmentSource,
1710
+ getReferencedFragmentSource: args.getReferencedFragmentSource,
1711
+ });
1712
+ }
1713
+ },
1714
+ });
1715
+ return tokenCount;
1716
+ }
1717
+ function validateTokenCount(args) {
1718
+ const tokenCount = calculateTokenCount(args);
1719
+ if (tokenCount > args.maxTokenCount) {
1720
+ return new graphql.GraphQLError(`Query exceeds maximum token count of ${args.maxTokenCount} (actual: ${tokenCount})`, args.document, args.source, args.document.loc && args.document.loc.start ? [args.document.loc.start] : undefined);
1721
+ }
1722
+ }
1723
+
1376
1724
  function validate(schema, sources, options) {
1377
1725
  const config = Object.assign({ strictDeprecated: true, strictFragments: true, keepClientFields: false, apollo: false }, options);
1378
1726
  const invalidDocuments = [];
@@ -1382,43 +1730,41 @@ function validate(schema, sources, options) {
1382
1730
  const fragments = [];
1383
1731
  const fragmentNames = [];
1384
1732
  const graph = new dependencyGraph.DepGraph({ circular: true });
1385
- documents.forEach((doc) => {
1386
- doc.fragments.forEach((fragment) => {
1733
+ documents.forEach(doc => {
1734
+ doc.fragments.forEach(fragment => {
1387
1735
  fragmentNames.push(fragment.node.name.value);
1388
1736
  fragments.push(fragment);
1389
1737
  graph.addNode(fragment.node.name.value, fragment.node);
1390
1738
  });
1391
1739
  });
1392
- fragments.forEach((fragment) => {
1740
+ fragments.forEach(fragment => {
1393
1741
  const depends = extractFragments(graphql.print(fragment.node));
1394
1742
  if (depends) {
1395
- depends.forEach((name) => {
1743
+ depends.forEach(name => {
1396
1744
  graph.addDependency(fragment.node.name.value, name);
1397
1745
  });
1398
1746
  }
1399
1747
  });
1400
1748
  documents
1401
1749
  // since we include fragments, validate only operations
1402
- .filter((doc) => doc.hasOperations)
1403
- .forEach((doc) => {
1750
+ .filter(doc => doc.hasOperations)
1751
+ .forEach(doc => {
1404
1752
  const docWithOperations = {
1405
- kind: 'Document',
1406
- definitions: doc.operations.map((d) => d.node),
1753
+ kind: graphql.Kind.DOCUMENT,
1754
+ definitions: doc.operations.map(d => d.node),
1407
1755
  };
1408
1756
  const extractedFragments = (extractFragments(graphql.print(docWithOperations)) || [])
1409
1757
  // resolve all nested fragments
1410
- .map((fragmentName) => resolveFragment(graph.getNodeData(fragmentName), graph))
1758
+ .map(fragmentName => resolveFragment(graph.getNodeData(fragmentName), graph))
1411
1759
  // flatten arrays
1412
1760
  .reduce((list, current) => list.concat(current), [])
1413
1761
  // remove duplicates
1414
- .filter((def, i, all) => all.findIndex((item) => item.name.value === def.name.value) === i);
1762
+ .filter((def, i, all) => all.findIndex(item => item.name.value === def.name.value) === i);
1415
1763
  const merged = {
1416
- kind: 'Document',
1764
+ kind: graphql.Kind.DOCUMENT,
1417
1765
  definitions: [...docWithOperations.definitions, ...extractedFragments],
1418
1766
  };
1419
- const transformedSchema = config.apollo
1420
- ? transformSchemaWithApollo(schema)
1421
- : schema;
1767
+ let transformedSchema = config.apollo ? transformSchemaWithApollo(schema) : schema;
1422
1768
  const transformedDoc = config.apollo
1423
1769
  ? transformDocumentWithApollo(merged, {
1424
1770
  keepClientFields: config.keepClientFields,
@@ -1436,12 +1782,41 @@ function validate(schema, sources, options) {
1436
1782
  errors.push(depthError);
1437
1783
  }
1438
1784
  }
1439
- const deprecated = config.strictDeprecated
1440
- ? findDeprecatedUsages(transformedSchema, graphql.parse(doc.source.body))
1441
- : [];
1442
- const duplicatedFragments = config.strictFragments
1443
- ? findDuplicatedFragments(fragmentNames)
1444
- : [];
1785
+ if (config.maxAliasCount) {
1786
+ const aliasError = validateAliasCount({
1787
+ source: doc.source,
1788
+ doc: transformedDoc,
1789
+ maxAliasCount: config.maxAliasCount,
1790
+ fragmentGraph: graph,
1791
+ });
1792
+ if (aliasError) {
1793
+ errors.push(aliasError);
1794
+ }
1795
+ }
1796
+ if (config.maxDirectiveCount) {
1797
+ const directiveError = validateDirectiveCount({
1798
+ source: doc.source,
1799
+ doc: transformedDoc,
1800
+ maxDirectiveCount: config.maxDirectiveCount,
1801
+ fragmentGraph: graph,
1802
+ });
1803
+ if (directiveError) {
1804
+ errors.push(directiveError);
1805
+ }
1806
+ }
1807
+ if (config.maxTokenCount) {
1808
+ const tokenCountError = validateTokenCount({
1809
+ source: doc.source,
1810
+ document: transformedDoc,
1811
+ maxTokenCount: config.maxTokenCount,
1812
+ getReferencedFragmentSource: fragmentName => graphql.print(graph.getNodeData(fragmentName)),
1813
+ });
1814
+ if (tokenCountError) {
1815
+ errors.push(tokenCountError);
1816
+ }
1817
+ }
1818
+ const deprecated = config.strictDeprecated ? findDeprecatedUsages(transformedSchema, transformedDoc) : [];
1819
+ const duplicatedFragments = config.strictFragments ? findDuplicatedFragments(fragmentNames) : [];
1445
1820
  if (sumLengths(errors, duplicatedFragments, deprecated) > 0) {
1446
1821
  invalidDocuments.push({
1447
1822
  source: doc.source,
@@ -1455,7 +1830,7 @@ function validate(schema, sources, options) {
1455
1830
  function findDuplicatedFragments(fragmentNames) {
1456
1831
  return fragmentNames
1457
1832
  .filter((name, i, all) => all.indexOf(name) !== i)
1458
- .map((name) => new graphql.GraphQLError(`Name of '${name}' fragment is not unique`));
1833
+ .map(name => new graphql.GraphQLError(`Name of '${name}' fragment is not unique`));
1459
1834
  }
1460
1835
  //
1461
1836
  // PostInfo -> AuthorInfo
@@ -1464,96 +1839,31 @@ function findDuplicatedFragments(fragmentNames) {
1464
1839
  function resolveFragment(fragment, graph) {
1465
1840
  return graph
1466
1841
  .dependenciesOf(fragment.name.value)
1467
- .reduce((list, current) => [
1468
- ...list,
1469
- ...resolveFragment(graph.getNodeData(current), graph),
1470
- ], [fragment]);
1842
+ .reduce((list, current) => [...list, ...resolveFragment(graph.getNodeData(current), graph)], [fragment]);
1471
1843
  }
1472
1844
  function extractFragments(document) {
1473
- return (document.match(/[\.]{3}[a-z0-9\_]+\b/gi) || []).map((name) => name.replace('...', ''));
1845
+ return (document.match(/[\.]{3}[a-z0-9\_]+\b/gi) || []).map(name => name.replace('...', ''));
1474
1846
  }
1475
1847
  function sumLengths(...arrays) {
1476
1848
  return arrays.reduce((sum, { length }) => sum + length, 0);
1477
1849
  }
1478
1850
 
1479
- function compareTwoStrings(str1, str2) {
1480
- if (!str1.length && !str2.length)
1481
- return 1;
1482
- if (!str1.length || !str2.length)
1483
- return 0;
1484
- if (str1.toUpperCase() === str2.toUpperCase())
1485
- return 1;
1486
- if (str1.length === 1 && str2.length === 1)
1487
- return 0;
1488
- const pairs1 = wordLetterPairs(str1);
1489
- const pairs2 = wordLetterPairs(str2);
1490
- const union = pairs1.length + pairs2.length;
1491
- let intersection = 0;
1492
- pairs1.forEach((pair1) => {
1493
- for (let i = 0, pair2; (pair2 = pairs2[i]); i++) {
1494
- if (pair1 !== pair2)
1495
- continue;
1496
- intersection++;
1497
- pairs2.splice(i, 1);
1498
- break;
1499
- }
1500
- });
1501
- return (intersection * 2) / union;
1502
- }
1503
- function findBestMatch(mainString, targetStrings) {
1504
- if (!areArgsValid(mainString, targetStrings))
1505
- throw new Error('Bad arguments: First argument should be a string, second should be an array of strings');
1506
- const ratings = targetStrings.map((target) => ({
1507
- target,
1508
- rating: compareTwoStrings(mainString, target.value),
1509
- }));
1510
- const bestMatch = Array.from(ratings).sort((a, b) => b.rating - a.rating)[0];
1511
- return { ratings, bestMatch };
1512
- }
1513
- function flattenDeep(arr) {
1514
- return Array.isArray(arr)
1515
- ? arr.reduce((a, b) => a.concat(flattenDeep(b)), [])
1516
- : [arr];
1517
- }
1518
- function areArgsValid(mainString, targetStrings) {
1519
- if (typeof mainString !== 'string')
1520
- return false;
1521
- if (!Array.isArray(targetStrings))
1522
- return false;
1523
- if (!targetStrings.length)
1524
- return false;
1525
- if (targetStrings.find((s) => typeof s.value !== 'string'))
1526
- return false;
1527
- return true;
1528
- }
1529
- function letterPairs(str) {
1530
- const pairs = [];
1531
- for (let i = 0, max = str.length - 1; i < max; i++)
1532
- pairs[i] = str.substring(i, i + 2);
1533
- return pairs;
1534
- }
1535
- function wordLetterPairs(str) {
1536
- const pairs = str.toUpperCase().split(' ').map(letterPairs);
1537
- return flattenDeep(pairs);
1538
- }
1539
-
1540
1851
  function similar(schema, typeName, threshold = 0.4) {
1541
1852
  const typeMap = schema.getTypeMap();
1542
1853
  const targets = Object.keys(schema.getTypeMap())
1543
- .filter((name) => !isPrimitive(name) && !isForIntrospection(name))
1544
- .map((name) => ({
1854
+ .filter(name => !isPrimitive(name) && !isForIntrospection(name))
1855
+ .map(name => ({
1545
1856
  typeId: name,
1546
1857
  value: stripType(typeMap[name]),
1547
1858
  }));
1548
1859
  const results = {};
1549
- if (typeof typeName !== 'undefined' &&
1550
- !targets.some((t) => t.typeId === typeName)) {
1860
+ if (typeof typeName !== 'undefined' && !targets.some(t => t.typeId === typeName)) {
1551
1861
  throw new Error(`Type '${typeName}' doesn't exist`);
1552
1862
  }
1553
- (typeName ? [{ typeId: typeName, value: '' }] : targets).forEach((source) => {
1863
+ (typeName ? [{ typeId: typeName, value: '' }] : targets).forEach(source => {
1554
1864
  const sourceType = schema.getType(source.typeId);
1555
- const matchWith = targets.filter((target) => schema.getType(target.typeId).astNode.kind ===
1556
- sourceType.astNode.kind && target.typeId !== source.typeId);
1865
+ const matchWith = targets.filter(target => schema.getType(target.typeId).astNode.kind === sourceType.astNode.kind &&
1866
+ target.typeId !== source.typeId);
1557
1867
  if (matchWith.length > 0) {
1558
1868
  const found = similarTo(sourceType, matchWith, threshold);
1559
1869
  if (found) {
@@ -1564,7 +1874,7 @@ function similar(schema, typeName, threshold = 0.4) {
1564
1874
  return results;
1565
1875
  }
1566
1876
  function similarTo(type, targets, threshold) {
1567
- const types = targets.filter((target) => target.typeId !== type.name);
1877
+ const types = targets.filter(target => target.typeId !== type.name);
1568
1878
  const result = findBestMatch(stripType(type), types);
1569
1879
  if (result.bestMatch.rating < threshold) {
1570
1880
  return;
@@ -1572,7 +1882,7 @@ function similarTo(type, targets, threshold) {
1572
1882
  return {
1573
1883
  bestMatch: result.bestMatch,
1574
1884
  ratings: result.ratings
1575
- .filter((r) => r.rating >= threshold && r.target !== result.bestMatch.target)
1885
+ .filter(r => r.rating >= threshold && r.target !== result.bestMatch.target)
1576
1886
  .sort((a, b) => a.rating - b.rating)
1577
1887
  .reverse(),
1578
1888
  };
@@ -1584,7 +1894,7 @@ function stripType(type) {
1584
1894
  .replace(/\}$/g, '')
1585
1895
  .trim()
1586
1896
  .split('\n')
1587
- .map((s) => s.trim())
1897
+ .map(s => s.trim())
1588
1898
  .sort((a, b) => a.localeCompare(b))
1589
1899
  .join(' ');
1590
1900
  }
@@ -1596,7 +1906,7 @@ function coverage(schema, sources) {
1596
1906
  };
1597
1907
  const typeMap = schema.getTypeMap();
1598
1908
  const typeInfo = new graphql.TypeInfo(schema);
1599
- const visitor = (source) => ({
1909
+ const visitor = source => ({
1600
1910
  Field(node) {
1601
1911
  const fieldDef = typeInfo.getFieldDef();
1602
1912
  const parent = typeInfo.getParentType();
@@ -1607,10 +1917,24 @@ function coverage(schema, sources) {
1607
1917
  fieldDef.name &&
1608
1918
  fieldDef.name !== '__typename' &&
1609
1919
  fieldDef.name !== '__schema') {
1610
- const locations = coverage.types[parent.name].children[fieldDef.name].locations[source.name];
1611
- coverage.types[parent.name].hits++;
1612
- coverage.types[parent.name].children[fieldDef.name].locations[source.name] = [node.loc].concat(locations || []);
1613
- coverage.types[parent.name].children[fieldDef.name].hits++;
1920
+ const sourceName = source.name;
1921
+ const typeCoverage = coverage.types[parent.name];
1922
+ const fieldCoverage = typeCoverage.children[fieldDef.name];
1923
+ const locations = fieldCoverage.locations[sourceName];
1924
+ typeCoverage.hits++;
1925
+ fieldCoverage.hits++;
1926
+ if (node.loc) {
1927
+ fieldCoverage.locations[sourceName] = [node.loc, ...(locations || [])];
1928
+ }
1929
+ if (node.arguments) {
1930
+ for (const argNode of node.arguments) {
1931
+ const argCoverage = fieldCoverage.children[argNode.name.value];
1932
+ argCoverage.hits++;
1933
+ if (argNode.loc) {
1934
+ argCoverage.locations[sourceName] = [argNode.loc, ...(argCoverage.locations[sourceName] || [])];
1935
+ }
1936
+ }
1937
+ }
1614
1938
  }
1615
1939
  },
1616
1940
  });
@@ -1629,7 +1953,14 @@ function coverage(schema, sources) {
1629
1953
  typeCoverage.children[field.name] = {
1630
1954
  hits: 0,
1631
1955
  locations: {},
1956
+ children: {},
1632
1957
  };
1958
+ for (const arg of field.args) {
1959
+ typeCoverage.children[field.name].children[arg.name] = {
1960
+ hits: 0,
1961
+ locations: {},
1962
+ };
1963
+ }
1633
1964
  }
1634
1965
  coverage.types[type.name] = typeCoverage;
1635
1966
  }
@@ -1638,20 +1969,41 @@ function coverage(schema, sources) {
1638
1969
  const documents = coverage.sources.map(readDocument);
1639
1970
  documents.forEach((doc, i) => {
1640
1971
  const source = coverage.sources[i];
1641
- doc.operations.forEach((op) => {
1972
+ doc.operations.forEach(op => {
1642
1973
  graphql.visit(op.node, graphql.visitWithTypeInfo(typeInfo, visitor(source)));
1643
1974
  });
1644
- doc.fragments.forEach((fr) => {
1975
+ doc.fragments.forEach(fr => {
1645
1976
  graphql.visit(fr.node, graphql.visitWithTypeInfo(typeInfo, visitor(source)));
1646
1977
  });
1647
1978
  });
1648
1979
  return coverage;
1649
1980
  }
1650
1981
 
1982
+ function calculateOperationComplexity(node, config, getFragmentByName, depth = 0) {
1983
+ let cost = config.scalarCost;
1984
+ if ('selectionSet' in node && node.selectionSet) {
1985
+ cost = config.objectCost;
1986
+ for (let child of node.selectionSet.selections) {
1987
+ cost += config.depthCostFactor * calculateOperationComplexity(child, config, getFragmentByName, depth + 1);
1988
+ }
1989
+ }
1990
+ if (node.kind == graphql.Kind.FRAGMENT_SPREAD) {
1991
+ const fragment = getFragmentByName(node.name.value);
1992
+ if (fragment) {
1993
+ cost += config.depthCostFactor * calculateOperationComplexity(fragment, config, getFragmentByName, depth + 1);
1994
+ }
1995
+ }
1996
+ return cost;
1997
+ }
1998
+
1651
1999
  exports.DiffRule = DiffRule;
2000
+ exports.calculateOperationComplexity = calculateOperationComplexity;
2001
+ exports.calculateTokenCount = calculateTokenCount;
2002
+ exports.countAliases = countAliases;
2003
+ exports.countDepth = countDepth;
2004
+ exports.countDirectives = countDirectives;
1652
2005
  exports.coverage = coverage;
1653
2006
  exports.diff = diff;
1654
2007
  exports.getTypePrefix = getTypePrefix;
1655
2008
  exports.similar = similar;
1656
2009
  exports.validate = validate;
1657
- //# sourceMappingURL=index.cjs.js.map