@graphql-inspector/core 3.3.0 → 3.4.1-alpha-20230111095532-bd016dc8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -4,92 +4,46 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
6
 
7
- const tslib = require('tslib');
8
7
  const graphql = require('graphql');
8
+ const tslib = require('tslib');
9
9
  const inspect = _interopDefault(require('object-inspect'));
10
10
  const dependencyGraph = require('dependency-graph');
11
+ const parser = require('graphql/language/parser');
11
12
 
12
- function keyMap(list, keyFn) {
13
- return list.reduce((map, item) => {
14
- map[keyFn(item)] = item;
15
- return map;
16
- }, Object.create(null));
17
- }
18
- function isEqual(a, b) {
19
- if (Array.isArray(a) && Array.isArray(b)) {
20
- if (a.length !== b.length)
21
- return false;
22
- for (var index = 0; index < a.length; index++) {
23
- if (!isEqual(a[index], b[index])) {
24
- return false;
25
- }
13
+ function readDocument(source) {
14
+ const result = {
15
+ source,
16
+ fragments: [],
17
+ operations: [],
18
+ hasFragments: false,
19
+ hasOperations: false,
20
+ };
21
+ const documentNode = graphql.parse(source.body);
22
+ const filepath = source.name;
23
+ const definitions = documentNode.definitions || [];
24
+ definitions.forEach((node) => {
25
+ if (isOperation(node)) {
26
+ result.operations.push({
27
+ node,
28
+ source: filepath,
29
+ });
26
30
  }
27
- return true;
28
- }
29
- if (a && b && typeof a === 'object' && typeof b === 'object') {
30
- const aRecord = a;
31
- const bRecord = b;
32
- const aKeys = Object.keys(aRecord);
33
- const bKeys = Object.keys(bRecord);
34
- if (aKeys.length !== bKeys.length)
35
- return false;
36
- for (const key of aKeys) {
37
- if (!isEqual(aRecord[key], bRecord[key])) {
38
- return false;
39
- }
31
+ else if (isFragment(node)) {
32
+ result.fragments.push({
33
+ node,
34
+ source: filepath,
35
+ });
40
36
  }
41
- return true;
42
- }
43
- return a === b || (!a && !b);
44
- }
45
- function isNotEqual(a, b) {
46
- return !isEqual(a, b);
47
- }
48
- function isVoid(a) {
49
- return typeof a === 'undefined' || a === null;
37
+ });
38
+ result.hasFragments = result.fragments.length > 0;
39
+ result.hasOperations = result.operations.length > 0;
40
+ return result;
50
41
  }
51
- function diffArrays(a, b) {
52
- return a.filter((c) => !b.some((d) => isEqual(d, c)));
42
+ function isOperation(node) {
43
+ return node.kind === graphql.Kind.OPERATION_DEFINITION;
53
44
  }
54
- function compareLists(oldList, newList, callbacks) {
55
- const oldMap = keyMap(oldList, ({ name }) => name);
56
- const newMap = keyMap(newList, ({ name }) => name);
57
- const added = [];
58
- const removed = [];
59
- const mutual = [];
60
- for (const oldItem of oldList) {
61
- const newItem = newMap[oldItem.name];
62
- if (newItem === undefined) {
63
- removed.push(oldItem);
64
- }
65
- else {
66
- mutual.push({
67
- newVersion: newItem,
68
- oldVersion: oldItem,
69
- });
70
- }
71
- }
72
- for (const newItem of newList) {
73
- if (oldMap[newItem.name] === undefined) {
74
- added.push(newItem);
75
- }
76
- }
77
- if (callbacks) {
78
- if (callbacks.onAdded) {
79
- added.forEach(callbacks.onAdded);
80
- }
81
- if (callbacks.onRemoved) {
82
- removed.forEach(callbacks.onRemoved);
83
- }
84
- if (callbacks.onMutual) {
85
- mutual.forEach(callbacks.onMutual);
86
- }
87
- }
88
- return {
89
- added,
90
- removed,
91
- mutual,
92
- };
45
+ function isFragment(node) {
46
+ return node.kind === graphql.Kind.FRAGMENT_DEFINITION;
93
47
  }
94
48
 
95
49
  function isDeprecated(fieldOrEnumValue) {
@@ -100,7 +54,7 @@ function isDeprecated(fieldOrEnumValue) {
100
54
  if (fieldOrEnumValue.deprecationReason != null) {
101
55
  return true;
102
56
  }
103
- 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')) {
57
+ 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')) {
104
58
  return true;
105
59
  }
106
60
  return false;
@@ -115,8 +69,7 @@ function safeChangeForField(oldType, newType) {
115
69
  return safeChangeForField(ofType, newType.ofType);
116
70
  }
117
71
  if (graphql.isListType(oldType)) {
118
- return ((graphql.isListType(newType) &&
119
- safeChangeForField(oldType.ofType, newType.ofType)) ||
72
+ return ((graphql.isListType(newType) && safeChangeForField(oldType.ofType, newType.ofType)) ||
120
73
  (graphql.isNonNullType(newType) && safeChangeForField(oldType, newType.ofType)));
121
74
  }
122
75
  return false;
@@ -151,10 +104,10 @@ function getTypePrefix(type) {
151
104
  return kindsMap[kind.toString()];
152
105
  }
153
106
  function isPrimitive(type) {
154
- return (['String', 'Int', 'Float', 'Boolean', 'ID'].indexOf(typeof type === 'string' ? type : type.name) !== -1);
107
+ return ['String', 'Int', 'Float', 'Boolean', 'ID'].includes(typeof type === 'string' ? type : type.name);
155
108
  }
156
109
  function isForIntrospection(type) {
157
- return ([
110
+ return [
158
111
  '__Schema',
159
112
  '__Type',
160
113
  '__TypeKind',
@@ -163,7 +116,7 @@ function isForIntrospection(type) {
163
116
  '__EnumValue',
164
117
  '__Directive',
165
118
  '__DirectiveLocation',
166
- ].indexOf(typeof type === 'string' ? type : type.name) !== -1);
119
+ ].includes(typeof type === 'string' ? type : type.name);
167
120
  }
168
121
  function findDeprecatedUsages(schema, ast) {
169
122
  const errors = [];
@@ -205,16 +158,15 @@ function findDeprecatedUsages(schema, ast) {
205
158
  return errors;
206
159
  }
207
160
  function removeFieldIfDirectives(node, directiveNames) {
208
- if (node.directives) {
209
- if (node.directives.some((d) => directiveNames.indexOf(d.name.value) !== -1)) {
210
- return null;
211
- }
161
+ var _a;
162
+ if ((_a = node.directives) === null || _a === void 0 ? void 0 : _a.some(d => directiveNames.includes(d.name.value))) {
163
+ return null;
212
164
  }
213
165
  return node;
214
166
  }
215
167
  function removeDirectives(node, directiveNames) {
216
168
  if (node.directives) {
217
- return Object.assign(Object.assign({}, node), { directives: node.directives.filter((d) => directiveNames.indexOf(d.name.value) === -1) });
169
+ return Object.assign(Object.assign({}, node), { directives: node.directives.filter(d => !directiveNames.includes(d.name.value)) });
218
170
  }
219
171
  return node;
220
172
  }
@@ -229,7 +181,7 @@ function getReachableTypes(schema) {
229
181
  if (graphql.isScalarType(type)) {
230
182
  return;
231
183
  }
232
- else if (graphql.isInterfaceType(type) || graphql.isObjectType(type)) {
184
+ if (graphql.isInterfaceType(type) || graphql.isObjectType(type)) {
233
185
  if (graphql.isInterfaceType(type)) {
234
186
  const { objects, interfaces } = schema.getImplementations(type);
235
187
  for (const child of objects) {
@@ -288,6 +240,93 @@ function resolveInputType(input) {
288
240
  return input;
289
241
  }
290
242
 
243
+ function coverage(schema, sources) {
244
+ const coverage = {
245
+ sources,
246
+ types: {},
247
+ };
248
+ const typeMap = schema.getTypeMap();
249
+ const typeInfo = new graphql.TypeInfo(schema);
250
+ const visitor = source => ({
251
+ Field(node) {
252
+ const fieldDef = typeInfo.getFieldDef();
253
+ const parent = typeInfo.getParentType();
254
+ if (parent &&
255
+ parent.name &&
256
+ !isForIntrospection(parent.name) &&
257
+ fieldDef &&
258
+ fieldDef.name &&
259
+ fieldDef.name !== '__typename' &&
260
+ fieldDef.name !== '__schema') {
261
+ const sourceName = source.name;
262
+ const typeCoverage = coverage.types[parent.name];
263
+ const fieldCoverage = typeCoverage.children[fieldDef.name];
264
+ const locations = fieldCoverage.locations[sourceName];
265
+ typeCoverage.hits++;
266
+ fieldCoverage.hits++;
267
+ if (node.loc) {
268
+ fieldCoverage.locations[sourceName] = [node.loc, ...(locations || [])];
269
+ }
270
+ if (node.arguments) {
271
+ for (const argNode of node.arguments) {
272
+ const argCoverage = fieldCoverage.children[argNode.name.value];
273
+ argCoverage.hits++;
274
+ if (argNode.loc) {
275
+ argCoverage.locations[sourceName] = [
276
+ argNode.loc,
277
+ ...(argCoverage.locations[sourceName] || []),
278
+ ];
279
+ }
280
+ }
281
+ }
282
+ }
283
+ },
284
+ });
285
+ for (const typename in typeMap) {
286
+ if (!isForIntrospection(typename) && !isPrimitive(typename)) {
287
+ const type = typeMap[typename];
288
+ if (graphql.isObjectType(type) || graphql.isInterfaceType(type)) {
289
+ const typeCoverage = {
290
+ hits: 0,
291
+ type,
292
+ children: {},
293
+ };
294
+ const fieldMap = type.getFields();
295
+ for (const fieldname in fieldMap) {
296
+ const field = fieldMap[fieldname];
297
+ typeCoverage.children[field.name] = {
298
+ hits: 0,
299
+ locations: {},
300
+ children: {},
301
+ };
302
+ for (const arg of field.args) {
303
+ typeCoverage.children[field.name].children[arg.name] = {
304
+ hits: 0,
305
+ locations: {},
306
+ };
307
+ }
308
+ }
309
+ coverage.types[type.name] = typeCoverage;
310
+ }
311
+ }
312
+ }
313
+ const documents = coverage.sources.map(readDocument);
314
+ documents.forEach((doc, i) => {
315
+ const source = coverage.sources[i];
316
+ doc.operations.forEach(op => {
317
+ graphql.visit(op.node, graphql.visitWithTypeInfo(typeInfo, visitor(source)));
318
+ });
319
+ doc.fragments.forEach(fr => {
320
+ graphql.visit(fr.node, graphql.visitWithTypeInfo(typeInfo, visitor(source)));
321
+ });
322
+ });
323
+ return coverage;
324
+ }
325
+
326
+ function parsePath(path) {
327
+ return path.split('.');
328
+ }
329
+
291
330
  (function (ChangeType) {
292
331
  // Argument
293
332
  ChangeType["FieldArgumentDescriptionChanged"] = "FIELD_ARGUMENT_DESCRIPTION_CHANGED";
@@ -359,99 +398,209 @@ function resolveInputType(input) {
359
398
  CriticalityLevel["Dangerous"] = "DANGEROUS";
360
399
  })(exports.CriticalityLevel || (exports.CriticalityLevel = {}));
361
400
 
362
- function schemaQueryTypeChanged(oldSchema, newSchema) {
363
- const oldName = (oldSchema.getQueryType() || {}).name || 'unknown';
364
- const newName = (newSchema.getQueryType() || {}).name || 'unknown';
365
- return {
366
- criticality: {
367
- level: exports.CriticalityLevel.Breaking,
368
- },
369
- type: exports.ChangeType.SchemaQueryTypeChanged,
370
- message: `Schema query root has changed from '${oldName}' to '${newName}'`,
371
- };
372
- }
373
- function schemaMutationTypeChanged(oldSchema, newSchema) {
374
- const oldName = (oldSchema.getMutationType() || {}).name || 'unknown';
375
- const newName = (newSchema.getMutationType() || {}).name || 'unknown';
376
- return {
377
- criticality: {
378
- level: exports.CriticalityLevel.Breaking,
379
- },
380
- type: exports.ChangeType.SchemaMutationTypeChanged,
381
- message: `Schema mutation root has changed from '${oldName}' to '${newName}'`,
382
- };
383
- }
384
- function schemaSubscriptionTypeChanged(oldSchema, newSchema) {
385
- const oldName = (oldSchema.getSubscriptionType() || {}).name || 'unknown';
386
- const newName = (newSchema.getSubscriptionType() || {}).name || 'unknown';
387
- return {
388
- criticality: {
389
- level: exports.CriticalityLevel.Breaking,
390
- },
391
- type: exports.ChangeType.SchemaSubscriptionTypeChanged,
392
- message: `Schema subscription root has changed from '${oldName}' to '${newName}'`,
393
- };
394
- }
401
+ const considerUsage = ({ changes, config }) => tslib.__awaiter(void 0, void 0, void 0, function* () {
402
+ if (!config) {
403
+ throw new Error(`considerUsage rule is missing config`);
404
+ }
405
+ const collectedBreakingField = [];
406
+ changes.forEach(change => {
407
+ if (change.criticality.level === exports.CriticalityLevel.Breaking && change.path) {
408
+ const [typeName, fieldName, argumentName] = parsePath(change.path);
409
+ collectedBreakingField.push({
410
+ type: typeName,
411
+ field: fieldName,
412
+ argument: argumentName,
413
+ });
414
+ }
415
+ });
416
+ // True if safe to break, false otherwise
417
+ const usageList = yield config.checkUsage(collectedBreakingField);
418
+ // turns an array of booleans into an array of `Type.Field` strings
419
+ // includes only those that are safe to break the api
420
+ const suppressedPaths = collectedBreakingField
421
+ .filter((_, i) => usageList[i] === true)
422
+ .map(({ type, field, argument }) => [type, field, argument].filter(Boolean).join('.'));
423
+ return changes.map(change => {
424
+ // Turns those "safe to break" changes into "dangerous"
425
+ if (change.criticality.level === exports.CriticalityLevel.Breaking &&
426
+ change.path &&
427
+ suppressedPaths.some(p => change.path.startsWith(p))) {
428
+ 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)` });
429
+ }
430
+ return change;
431
+ });
432
+ });
395
433
 
396
- function typeRemoved(type) {
397
- return {
398
- criticality: {
399
- level: exports.CriticalityLevel.Breaking,
400
- },
401
- type: exports.ChangeType.TypeRemoved,
402
- message: `Type '${type.name}' was removed`,
403
- path: type.name,
404
- };
434
+ const dangerousBreaking = ({ changes }) => {
435
+ return changes.map(change => {
436
+ if (change.criticality.level === exports.CriticalityLevel.Dangerous) {
437
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Breaking }) });
438
+ }
439
+ return change;
440
+ });
441
+ };
442
+
443
+ const descriptionChangeTypes = [
444
+ exports.ChangeType.FieldArgumentDescriptionChanged,
445
+ exports.ChangeType.DirectiveDescriptionChanged,
446
+ exports.ChangeType.DirectiveArgumentDescriptionChanged,
447
+ exports.ChangeType.EnumValueDescriptionChanged,
448
+ exports.ChangeType.FieldDescriptionChanged,
449
+ exports.ChangeType.FieldDescriptionAdded,
450
+ exports.ChangeType.FieldDescriptionRemoved,
451
+ exports.ChangeType.InputFieldDescriptionAdded,
452
+ exports.ChangeType.InputFieldDescriptionRemoved,
453
+ exports.ChangeType.InputFieldDescriptionChanged,
454
+ exports.ChangeType.TypeDescriptionChanged,
455
+ ];
456
+ const ignoreDescriptionChanges = ({ changes }) => {
457
+ return changes.filter(change => !descriptionChangeTypes.includes(change.type));
458
+ };
459
+
460
+ const safeUnreachable = ({ changes, oldSchema }) => {
461
+ const reachable = getReachableTypes(oldSchema);
462
+ return changes.map(change => {
463
+ if (change.criticality.level === exports.CriticalityLevel.Breaking && change.path) {
464
+ const [typeName] = parsePath(change.path);
465
+ if (!reachable.has(typeName)) {
466
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.NonBreaking }), message: 'Unreachable from root' });
467
+ }
468
+ }
469
+ return change;
470
+ });
471
+ };
472
+
473
+ const suppressRemovalOfDeprecatedField = ({ changes, oldSchema }) => {
474
+ return changes.map(change => {
475
+ if (change.type === exports.ChangeType.FieldRemoved &&
476
+ change.criticality.level === exports.CriticalityLevel.Breaking &&
477
+ change.path) {
478
+ const [typeName, fieldName] = parsePath(change.path);
479
+ const type = oldSchema.getType(typeName);
480
+ if (graphql.isObjectType(type) || graphql.isInterfaceType(type)) {
481
+ const field = type.getFields()[fieldName];
482
+ if (isDeprecated(field)) {
483
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }) });
484
+ }
485
+ }
486
+ }
487
+ if (change.type === exports.ChangeType.EnumValueRemoved &&
488
+ change.criticality.level === exports.CriticalityLevel.Breaking &&
489
+ change.path) {
490
+ const [enumName, enumItem] = parsePath(change.path);
491
+ const type = oldSchema.getType(enumName);
492
+ if (graphql.isEnumType(type)) {
493
+ const item = type.getValue(enumItem);
494
+ if (item && isDeprecated(item)) {
495
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }) });
496
+ }
497
+ }
498
+ }
499
+ if (change.type === exports.ChangeType.InputFieldRemoved &&
500
+ change.criticality.level === exports.CriticalityLevel.Breaking &&
501
+ change.path) {
502
+ const [inputName, inputItem] = parsePath(change.path);
503
+ const type = oldSchema.getType(inputName);
504
+ if (graphql.isInputObjectType(type)) {
505
+ const item = type.getFields()[inputItem];
506
+ if (item && isDeprecated(item)) {
507
+ return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }) });
508
+ }
509
+ }
510
+ }
511
+ return change;
512
+ });
513
+ };
514
+
515
+ const rules = /*#__PURE__*/Object.freeze({
516
+ __proto__: null,
517
+ considerUsage: considerUsage,
518
+ dangerousBreaking: dangerousBreaking,
519
+ ignoreDescriptionChanges: ignoreDescriptionChanges,
520
+ safeUnreachable: safeUnreachable,
521
+ suppressRemovalOfDeprecatedField: suppressRemovalOfDeprecatedField
522
+ });
523
+
524
+ function keyMap(list, keyFn) {
525
+ return list.reduce((map, item) => {
526
+ map[keyFn(item)] = item;
527
+ return map;
528
+ }, Object.create(null));
405
529
  }
406
- function typeAdded(type) {
407
- return {
408
- criticality: {
409
- level: exports.CriticalityLevel.NonBreaking,
410
- },
411
- type: exports.ChangeType.TypeAdded,
412
- message: `Type '${type.name}' was added`,
413
- path: type.name,
414
- };
530
+ function isEqual(a, b) {
531
+ if (Array.isArray(a) && Array.isArray(b)) {
532
+ if (a.length !== b.length)
533
+ return false;
534
+ for (let index = 0; index < a.length; index++) {
535
+ if (!isEqual(a[index], b[index])) {
536
+ return false;
537
+ }
538
+ }
539
+ return true;
540
+ }
541
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
542
+ const aRecord = a;
543
+ const bRecord = b;
544
+ const aKeys = Object.keys(aRecord);
545
+ const bKeys = Object.keys(bRecord);
546
+ if (aKeys.length !== bKeys.length)
547
+ return false;
548
+ for (const key of aKeys) {
549
+ if (!isEqual(aRecord[key], bRecord[key])) {
550
+ return false;
551
+ }
552
+ }
553
+ return true;
554
+ }
555
+ return a === b || (!a && !b);
415
556
  }
416
- function typeKindChanged(oldType, newType) {
417
- return {
418
- criticality: {
419
- level: exports.CriticalityLevel.Breaking,
420
- reason: `Changing the kind of a type is a breaking change because it can cause existing queries to error. For example, turning an object type to a scalar type would break queries that define a selection set for this type.`,
421
- },
422
- type: exports.ChangeType.TypeKindChanged,
423
- message: `'${oldType.name}' kind changed from '${getKind(oldType)}' to '${getKind(newType)}'`,
424
- path: oldType.name,
425
- };
557
+ function isNotEqual(a, b) {
558
+ return !isEqual(a, b);
426
559
  }
427
- function typeDescriptionChanged(oldType, newType) {
428
- return {
429
- criticality: {
430
- level: exports.CriticalityLevel.NonBreaking,
431
- },
432
- type: exports.ChangeType.TypeDescriptionChanged,
433
- message: `Description '${oldType.description}' on type '${oldType.name}' has changed to '${newType.description}'`,
434
- path: oldType.name,
435
- };
560
+ function isVoid(a) {
561
+ return typeof a === 'undefined' || a === null;
436
562
  }
437
- function typeDescriptionRemoved(type) {
438
- return {
439
- criticality: {
440
- level: exports.CriticalityLevel.NonBreaking,
441
- },
442
- type: exports.ChangeType.TypeDescriptionRemoved,
443
- message: `Description '${type.description}' was removed from object type '${type.name}'`,
444
- path: type.name,
445
- };
563
+ function diffArrays(a, b) {
564
+ return a.filter(c => !b.some(d => isEqual(d, c)));
446
565
  }
447
- function typeDescriptionAdded(type) {
566
+ function compareLists(oldList, newList, callbacks) {
567
+ const oldMap = keyMap(oldList, ({ name }) => name);
568
+ const newMap = keyMap(newList, ({ name }) => name);
569
+ const added = [];
570
+ const removed = [];
571
+ const mutual = [];
572
+ for (const oldItem of oldList) {
573
+ const newItem = newMap[oldItem.name];
574
+ if (newItem === undefined) {
575
+ removed.push(oldItem);
576
+ }
577
+ else {
578
+ mutual.push({
579
+ newVersion: newItem,
580
+ oldVersion: oldItem,
581
+ });
582
+ }
583
+ }
584
+ for (const newItem of newList) {
585
+ if (oldMap[newItem.name] === undefined) {
586
+ added.push(newItem);
587
+ }
588
+ }
589
+ if (callbacks) {
590
+ if (callbacks.onAdded) {
591
+ added.forEach(callbacks.onAdded);
592
+ }
593
+ if (callbacks.onRemoved) {
594
+ removed.forEach(callbacks.onRemoved);
595
+ }
596
+ if (callbacks.onMutual) {
597
+ mutual.forEach(callbacks.onMutual);
598
+ }
599
+ }
448
600
  return {
449
- criticality: {
450
- level: exports.CriticalityLevel.NonBreaking,
451
- },
452
- type: exports.ChangeType.TypeDescriptionAdded,
453
- message: `Object type '${type.name}' has description '${type.description}'`,
454
- path: type.name,
601
+ added,
602
+ removed,
603
+ mutual,
455
604
  };
456
605
  }
457
606
 
@@ -508,9 +657,7 @@ function directiveLocationRemoved(directive, location) {
508
657
  function directiveArgumentAdded(directive, arg) {
509
658
  return {
510
659
  criticality: {
511
- level: graphql.isNonNullType(arg.type)
512
- ? exports.CriticalityLevel.Breaking
513
- : exports.CriticalityLevel.NonBreaking,
660
+ level: graphql.isNonNullType(arg.type) ? exports.CriticalityLevel.Breaking : exports.CriticalityLevel.NonBreaking,
514
661
  },
515
662
  type: exports.ChangeType.DirectiveArgumentAdded,
516
663
  message: `Argument '${arg.name}' was added to directive '${directive.name}'`,
@@ -566,6 +713,138 @@ function directiveArgumentTypeChanged(directive, oldArg, newArg) {
566
713
  };
567
714
  }
568
715
 
716
+ function schemaQueryTypeChanged(oldSchema, newSchema) {
717
+ const oldName = (oldSchema.getQueryType() || {}).name || 'unknown';
718
+ const newName = (newSchema.getQueryType() || {}).name || 'unknown';
719
+ return {
720
+ criticality: {
721
+ level: exports.CriticalityLevel.Breaking,
722
+ },
723
+ type: exports.ChangeType.SchemaQueryTypeChanged,
724
+ message: `Schema query root has changed from '${oldName}' to '${newName}'`,
725
+ };
726
+ }
727
+ function schemaMutationTypeChanged(oldSchema, newSchema) {
728
+ const oldName = (oldSchema.getMutationType() || {}).name || 'unknown';
729
+ const newName = (newSchema.getMutationType() || {}).name || 'unknown';
730
+ return {
731
+ criticality: {
732
+ level: exports.CriticalityLevel.Breaking,
733
+ },
734
+ type: exports.ChangeType.SchemaMutationTypeChanged,
735
+ message: `Schema mutation root has changed from '${oldName}' to '${newName}'`,
736
+ };
737
+ }
738
+ function schemaSubscriptionTypeChanged(oldSchema, newSchema) {
739
+ const oldName = (oldSchema.getSubscriptionType() || {}).name || 'unknown';
740
+ const newName = (newSchema.getSubscriptionType() || {}).name || 'unknown';
741
+ return {
742
+ criticality: {
743
+ level: exports.CriticalityLevel.Breaking,
744
+ },
745
+ type: exports.ChangeType.SchemaSubscriptionTypeChanged,
746
+ message: `Schema subscription root has changed from '${oldName}' to '${newName}'`,
747
+ };
748
+ }
749
+
750
+ function typeRemoved(type) {
751
+ return {
752
+ criticality: {
753
+ level: exports.CriticalityLevel.Breaking,
754
+ },
755
+ type: exports.ChangeType.TypeRemoved,
756
+ message: `Type '${type.name}' was removed`,
757
+ path: type.name,
758
+ };
759
+ }
760
+ function typeAdded(type) {
761
+ return {
762
+ criticality: {
763
+ level: exports.CriticalityLevel.NonBreaking,
764
+ },
765
+ type: exports.ChangeType.TypeAdded,
766
+ message: `Type '${type.name}' was added`,
767
+ path: type.name,
768
+ };
769
+ }
770
+ function typeKindChanged(oldType, newType) {
771
+ return {
772
+ criticality: {
773
+ level: exports.CriticalityLevel.Breaking,
774
+ reason: `Changing the kind of a type is a breaking change because it can cause existing queries to error. For example, turning an object type to a scalar type would break queries that define a selection set for this type.`,
775
+ },
776
+ type: exports.ChangeType.TypeKindChanged,
777
+ message: `'${oldType.name}' kind changed from '${getKind(oldType)}' to '${getKind(newType)}'`,
778
+ path: oldType.name,
779
+ };
780
+ }
781
+ function typeDescriptionChanged(oldType, newType) {
782
+ return {
783
+ criticality: {
784
+ level: exports.CriticalityLevel.NonBreaking,
785
+ },
786
+ type: exports.ChangeType.TypeDescriptionChanged,
787
+ message: `Description '${oldType.description}' on type '${oldType.name}' has changed to '${newType.description}'`,
788
+ path: oldType.name,
789
+ };
790
+ }
791
+ function typeDescriptionRemoved(type) {
792
+ return {
793
+ criticality: {
794
+ level: exports.CriticalityLevel.NonBreaking,
795
+ },
796
+ type: exports.ChangeType.TypeDescriptionRemoved,
797
+ message: `Description '${type.description}' was removed from object type '${type.name}'`,
798
+ path: type.name,
799
+ };
800
+ }
801
+ function typeDescriptionAdded(type) {
802
+ return {
803
+ criticality: {
804
+ level: exports.CriticalityLevel.NonBreaking,
805
+ },
806
+ type: exports.ChangeType.TypeDescriptionAdded,
807
+ message: `Object type '${type.name}' has description '${type.description}'`,
808
+ path: type.name,
809
+ };
810
+ }
811
+
812
+ function changesInDirective(oldDirective, newDirective, addChange) {
813
+ if (isNotEqual(oldDirective.description, newDirective.description)) {
814
+ addChange(directiveDescriptionChanged(oldDirective, newDirective));
815
+ }
816
+ const locations = {
817
+ added: diffArrays(newDirective.locations, oldDirective.locations),
818
+ removed: diffArrays(oldDirective.locations, newDirective.locations),
819
+ };
820
+ // locations added
821
+ locations.added.forEach(location => addChange(directiveLocationAdded(newDirective, location)));
822
+ // locations removed
823
+ locations.removed.forEach(location => addChange(directiveLocationRemoved(oldDirective, location)));
824
+ compareLists(oldDirective.args, newDirective.args, {
825
+ onAdded(arg) {
826
+ addChange(directiveArgumentAdded(newDirective, arg));
827
+ },
828
+ onRemoved(arg) {
829
+ addChange(directiveArgumentRemoved(oldDirective, arg));
830
+ },
831
+ onMutual(arg) {
832
+ changesInDirectiveArgument(oldDirective, arg.oldVersion, arg.newVersion, addChange);
833
+ },
834
+ });
835
+ }
836
+ function changesInDirectiveArgument(directive, oldArg, newArg, addChange) {
837
+ if (isNotEqual(oldArg.description, newArg.description)) {
838
+ addChange(directiveArgumentDescriptionChanged(directive, oldArg, newArg));
839
+ }
840
+ if (isNotEqual(oldArg.defaultValue, newArg.defaultValue)) {
841
+ addChange(directiveArgumentDefaultValueChanged(directive, oldArg, newArg));
842
+ }
843
+ if (isNotEqual(oldArg.type.toString(), newArg.type.toString())) {
844
+ addChange(directiveArgumentTypeChanged(directive, oldArg, newArg));
845
+ }
846
+ }
847
+
569
848
  function enumValueRemoved(oldEnum, value) {
570
849
  return {
571
850
  criticality: {
@@ -655,43 +934,7 @@ function changesInEnum(oldEnum, newEnum, addChange) {
655
934
  else {
656
935
  addChange(enumValueDeprecationReasonChanged(newEnum, oldValue, newValue));
657
936
  }
658
- }
659
- },
660
- });
661
- }
662
-
663
- function unionMemberRemoved(union, type) {
664
- return {
665
- criticality: {
666
- level: exports.CriticalityLevel.Breaking,
667
- reason: 'Removing a union member from a union can cause existing queries that use this union member in a fragment spread to error.',
668
- },
669
- type: exports.ChangeType.UnionMemberRemoved,
670
- message: `Member '${type.name}' was removed from Union type '${union.name}'`,
671
- path: union.name,
672
- };
673
- }
674
- function unionMemberAdded(union, type) {
675
- return {
676
- criticality: {
677
- level: exports.CriticalityLevel.Dangerous,
678
- reason: 'Adding a possible type to Unions may break existing clients that were not programming defensively against a new possible type.',
679
- },
680
- type: exports.ChangeType.UnionMemberAdded,
681
- message: `Member '${type.name}' was added to Union type '${union.name}'`,
682
- path: union.name,
683
- };
684
- }
685
-
686
- function changesInUnion(oldUnion, newUnion, addChange) {
687
- const oldTypes = oldUnion.getTypes();
688
- const newTypes = newUnion.getTypes();
689
- compareLists(oldTypes, newTypes, {
690
- onAdded(t) {
691
- addChange(unionMemberAdded(newUnion, t));
692
- },
693
- onRemoved(t) {
694
- addChange(unionMemberRemoved(oldUnion, t));
937
+ }
695
938
  },
696
939
  });
697
940
  }
@@ -709,7 +952,7 @@ function compareTwoStrings(str1, str2) {
709
952
  const pairs2 = wordLetterPairs(str2);
710
953
  const union = pairs1.length + pairs2.length;
711
954
  let intersection = 0;
712
- pairs1.forEach((pair1) => {
955
+ pairs1.forEach(pair1 => {
713
956
  for (let i = 0, pair2; (pair2 = pairs2[i]); i++) {
714
957
  if (pair1 !== pair2)
715
958
  continue;
@@ -723,7 +966,7 @@ function compareTwoStrings(str1, str2) {
723
966
  function findBestMatch(mainString, targetStrings) {
724
967
  if (!areArgsValid(mainString, targetStrings))
725
968
  throw new Error('Bad arguments: First argument should be a string, second should be an array of strings');
726
- const ratings = targetStrings.map((target) => ({
969
+ const ratings = targetStrings.map(target => ({
727
970
  target,
728
971
  rating: compareTwoStrings(mainString, target.value),
729
972
  }));
@@ -731,9 +974,7 @@ function findBestMatch(mainString, targetStrings) {
731
974
  return { ratings, bestMatch };
732
975
  }
733
976
  function flattenDeep(arr) {
734
- return Array.isArray(arr)
735
- ? arr.reduce((a, b) => a.concat(flattenDeep(b)), [])
736
- : [arr];
977
+ return Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
737
978
  }
738
979
  function areArgsValid(mainString, targetStrings) {
739
980
  if (typeof mainString !== 'string')
@@ -742,7 +983,7 @@ function areArgsValid(mainString, targetStrings) {
742
983
  return false;
743
984
  if (!targetStrings.length)
744
985
  return false;
745
- if (targetStrings.find((s) => typeof s.value !== 'string'))
986
+ if (targetStrings.find(s => typeof s.value !== 'string'))
746
987
  return false;
747
988
  return true;
748
989
  }
@@ -757,7 +998,9 @@ function wordLetterPairs(str) {
757
998
  return flattenDeep(pairs);
758
999
  }
759
1000
  function safeString(obj) {
760
- return inspect(obj).replace(/\[Object\: null prototype\] /g, '').replace(/(^')|('$)/g, '');
1001
+ return inspect(obj)
1002
+ .replace(/\[Object: null prototype\] /g, '')
1003
+ .replace(/(^')|('$)/g, '');
761
1004
  }
762
1005
 
763
1006
  function inputFieldRemoved(input, field) {
@@ -872,14 +1115,12 @@ function changesInInputField(input, oldField, newField, addChange) {
872
1115
  }
873
1116
  }
874
1117
  if (isNotEqual(oldField.defaultValue, newField.defaultValue)) {
875
- if (Array.isArray(oldField.defaultValue) &&
876
- Array.isArray(newField.defaultValue)) {
1118
+ if (Array.isArray(oldField.defaultValue) && Array.isArray(newField.defaultValue)) {
877
1119
  if (diffArrays(oldField.defaultValue, newField.defaultValue).length > 0) {
878
1120
  addChange(inputFieldDefaultValueChanged(input, oldField, newField));
879
1121
  }
880
1122
  }
881
- else if (JSON.stringify(oldField.defaultValue) !==
882
- JSON.stringify(newField.defaultValue)) {
1123
+ else if (JSON.stringify(oldField.defaultValue) !== JSON.stringify(newField.defaultValue)) {
883
1124
  addChange(inputFieldDefaultValueChanged(input, oldField, newField));
884
1125
  }
885
1126
  }
@@ -888,29 +1129,6 @@ function changesInInputField(input, oldField, newField, addChange) {
888
1129
  }
889
1130
  }
890
1131
 
891
- function objectTypeInterfaceAdded(iface, type) {
892
- return {
893
- criticality: {
894
- level: exports.CriticalityLevel.Dangerous,
895
- reason: 'Adding an interface to an object type may break existing clients that were not programming defensively against a new possible type.',
896
- },
897
- type: exports.ChangeType.ObjectTypeInterfaceAdded,
898
- message: `'${type.name}' object implements '${iface.name}' interface`,
899
- path: type.name,
900
- };
901
- }
902
- function objectTypeInterfaceRemoved(iface, type) {
903
- return {
904
- criticality: {
905
- level: exports.CriticalityLevel.Breaking,
906
- reason: 'Removing an interface from an object type can cause existing queries that use this in a fragment spread to error.',
907
- },
908
- type: exports.ChangeType.ObjectTypeInterfaceRemoved,
909
- message: `'${type.name}' object type no longer implements '${iface.name}' interface`,
910
- path: type.name,
911
- };
912
- }
913
-
914
1132
  function fieldRemoved(type, field) {
915
1133
  const entity = graphql.isInterfaceType(type) ? 'interface' : 'object type';
916
1134
  return {
@@ -1103,15 +1321,13 @@ function changesInArgument(type, field, oldArg, newArg, addChange) {
1103
1321
  addChange(fieldArgumentDescriptionChanged(type, field, oldArg, newArg));
1104
1322
  }
1105
1323
  if (isNotEqual(oldArg.defaultValue, newArg.defaultValue)) {
1106
- if (Array.isArray(oldArg.defaultValue) &&
1107
- Array.isArray(newArg.defaultValue)) {
1324
+ if (Array.isArray(oldArg.defaultValue) && Array.isArray(newArg.defaultValue)) {
1108
1325
  const diff = diffArrays(oldArg.defaultValue, newArg.defaultValue);
1109
1326
  if (diff.length > 0) {
1110
1327
  addChange(fieldArgumentDefaultChanged(type, field, oldArg, newArg));
1111
1328
  }
1112
1329
  }
1113
- else if (JSON.stringify(oldArg.defaultValue) !==
1114
- JSON.stringify(newArg.defaultValue)) {
1330
+ else if (JSON.stringify(oldArg.defaultValue) !== JSON.stringify(newArg.defaultValue)) {
1115
1331
  addChange(fieldArgumentDefaultChanged(type, field, oldArg, newArg));
1116
1332
  }
1117
1333
  }
@@ -1167,6 +1383,43 @@ function changesInField(type, oldField, newField, addChange) {
1167
1383
  });
1168
1384
  }
1169
1385
 
1386
+ function changesInInterface(oldInterface, newInterface, addChange) {
1387
+ compareLists(Object.values(oldInterface.getFields()), Object.values(newInterface.getFields()), {
1388
+ onAdded(field) {
1389
+ addChange(fieldAdded(newInterface, field));
1390
+ },
1391
+ onRemoved(field) {
1392
+ addChange(fieldRemoved(oldInterface, field));
1393
+ },
1394
+ onMutual(field) {
1395
+ changesInField(oldInterface, field.oldVersion, field.newVersion, addChange);
1396
+ },
1397
+ });
1398
+ }
1399
+
1400
+ function objectTypeInterfaceAdded(iface, type) {
1401
+ return {
1402
+ criticality: {
1403
+ level: exports.CriticalityLevel.Dangerous,
1404
+ reason: 'Adding an interface to an object type may break existing clients that were not programming defensively against a new possible type.',
1405
+ },
1406
+ type: exports.ChangeType.ObjectTypeInterfaceAdded,
1407
+ message: `'${type.name}' object implements '${iface.name}' interface`,
1408
+ path: type.name,
1409
+ };
1410
+ }
1411
+ function objectTypeInterfaceRemoved(iface, type) {
1412
+ return {
1413
+ criticality: {
1414
+ level: exports.CriticalityLevel.Breaking,
1415
+ reason: 'Removing an interface from an object type can cause existing queries that use this in a fragment spread to error.',
1416
+ },
1417
+ type: exports.ChangeType.ObjectTypeInterfaceRemoved,
1418
+ message: `'${type.name}' object type no longer implements '${iface.name}' interface`,
1419
+ path: type.name,
1420
+ };
1421
+ }
1422
+
1170
1423
  function changesInObject(oldType, newType, addChange) {
1171
1424
  const oldInterfaces = oldType.getInterfaces();
1172
1425
  const newInterfaces = newType.getInterfaces();
@@ -1193,55 +1446,41 @@ function changesInObject(oldType, newType, addChange) {
1193
1446
  });
1194
1447
  }
1195
1448
 
1196
- function changesInInterface(oldInterface, newInterface, addChange) {
1197
- compareLists(Object.values(oldInterface.getFields()), Object.values(newInterface.getFields()), {
1198
- onAdded(field) {
1199
- addChange(fieldAdded(newInterface, field));
1200
- },
1201
- onRemoved(field) {
1202
- addChange(fieldRemoved(oldInterface, field));
1449
+ function unionMemberRemoved(union, type) {
1450
+ return {
1451
+ criticality: {
1452
+ level: exports.CriticalityLevel.Breaking,
1453
+ reason: 'Removing a union member from a union can cause existing queries that use this union member in a fragment spread to error.',
1203
1454
  },
1204
- onMutual(field) {
1205
- changesInField(oldInterface, field.oldVersion, field.newVersion, addChange);
1455
+ type: exports.ChangeType.UnionMemberRemoved,
1456
+ message: `Member '${type.name}' was removed from Union type '${union.name}'`,
1457
+ path: union.name,
1458
+ };
1459
+ }
1460
+ function unionMemberAdded(union, type) {
1461
+ return {
1462
+ criticality: {
1463
+ level: exports.CriticalityLevel.Dangerous,
1464
+ reason: 'Adding a possible type to Unions may break existing clients that were not programming defensively against a new possible type.',
1206
1465
  },
1207
- });
1466
+ type: exports.ChangeType.UnionMemberAdded,
1467
+ message: `Member '${type.name}' was added to Union type '${union.name}'`,
1468
+ path: union.name,
1469
+ };
1208
1470
  }
1209
1471
 
1210
- function changesInDirective(oldDirective, newDirective, addChange) {
1211
- if (isNotEqual(oldDirective.description, newDirective.description)) {
1212
- addChange(directiveDescriptionChanged(oldDirective, newDirective));
1213
- }
1214
- const locations = {
1215
- added: diffArrays(newDirective.locations, oldDirective.locations),
1216
- removed: diffArrays(oldDirective.locations, newDirective.locations),
1217
- };
1218
- // locations added
1219
- locations.added.forEach((location) => addChange(directiveLocationAdded(newDirective, location)));
1220
- // locations removed
1221
- locations.removed.forEach((location) => addChange(directiveLocationRemoved(oldDirective, location)));
1222
- compareLists(oldDirective.args, newDirective.args, {
1223
- onAdded(arg) {
1224
- addChange(directiveArgumentAdded(newDirective, arg));
1225
- },
1226
- onRemoved(arg) {
1227
- addChange(directiveArgumentRemoved(oldDirective, arg));
1472
+ function changesInUnion(oldUnion, newUnion, addChange) {
1473
+ const oldTypes = oldUnion.getTypes();
1474
+ const newTypes = newUnion.getTypes();
1475
+ compareLists(oldTypes, newTypes, {
1476
+ onAdded(t) {
1477
+ addChange(unionMemberAdded(newUnion, t));
1228
1478
  },
1229
- onMutual(arg) {
1230
- changesInDirectiveArgument(oldDirective, arg.oldVersion, arg.newVersion, addChange);
1479
+ onRemoved(t) {
1480
+ addChange(unionMemberRemoved(oldUnion, t));
1231
1481
  },
1232
1482
  });
1233
1483
  }
1234
- function changesInDirectiveArgument(directive, oldArg, newArg, addChange) {
1235
- if (isNotEqual(oldArg.description, newArg.description)) {
1236
- addChange(directiveArgumentDescriptionChanged(directive, oldArg, newArg));
1237
- }
1238
- if (isNotEqual(oldArg.defaultValue, newArg.defaultValue)) {
1239
- addChange(directiveArgumentDefaultValueChanged(directive, oldArg, newArg));
1240
- }
1241
- if (isNotEqual(oldArg.type.toString(), newArg.type.toString())) {
1242
- addChange(directiveArgumentTypeChanged(directive, oldArg, newArg));
1243
- }
1244
- }
1245
1484
 
1246
1485
  function diffSchema(oldSchema, newSchema) {
1247
1486
  const changes = [];
@@ -1249,7 +1488,7 @@ function diffSchema(oldSchema, newSchema) {
1249
1488
  changes.push(change);
1250
1489
  }
1251
1490
  changesInSchema(oldSchema, newSchema, addChange);
1252
- compareLists(Object.values(oldSchema.getTypeMap()).filter((t) => !isPrimitive(t)), Object.values(newSchema.getTypeMap()).filter((t) => !isPrimitive(t)), {
1491
+ compareLists(Object.values(oldSchema.getTypeMap()).filter(t => !isPrimitive(t)), Object.values(newSchema.getTypeMap()).filter(t => !isPrimitive(t)), {
1253
1492
  onAdded(type) {
1254
1493
  addChange(typeAdded(type));
1255
1494
  },
@@ -1333,181 +1572,146 @@ function changesInType(oldType, newType, addChange) {
1333
1572
  }
1334
1573
  }
1335
1574
 
1336
- const dangerousBreaking = ({ changes }) => {
1337
- return changes.map((change) => {
1338
- if (change.criticality.level === exports.CriticalityLevel.Dangerous) {
1339
- return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Breaking }) });
1340
- }
1341
- return change;
1342
- });
1343
- };
1344
-
1345
- function parsePath(path) {
1346
- return path.split('.');
1575
+ const DiffRule = rules;
1576
+ function diff(oldSchema, newSchema, rules = [], config) {
1577
+ const changes = diffSchema(oldSchema, newSchema);
1578
+ return rules.reduce((prev, rule) => tslib.__awaiter(this, void 0, void 0, function* () {
1579
+ const prevChanges = yield prev;
1580
+ return rule({
1581
+ changes: prevChanges,
1582
+ oldSchema,
1583
+ newSchema,
1584
+ config,
1585
+ });
1586
+ }), Promise.resolve(changes));
1347
1587
  }
1348
1588
 
1349
- const suppressRemovalOfDeprecatedField = ({ changes, oldSchema, }) => {
1350
- return changes.map((change) => {
1351
- if (change.type === exports.ChangeType.FieldRemoved &&
1352
- change.criticality.level === exports.CriticalityLevel.Breaking &&
1353
- change.path) {
1354
- const [typeName, fieldName] = parsePath(change.path);
1355
- const type = oldSchema.getType(typeName);
1356
- if (graphql.isObjectType(type) || graphql.isInterfaceType(type)) {
1357
- const field = type.getFields()[fieldName];
1358
- if (isDeprecated(field)) {
1359
- return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }) });
1360
- }
1361
- }
1362
- }
1363
- if (change.type === exports.ChangeType.EnumValueRemoved &&
1364
- change.criticality.level === exports.CriticalityLevel.Breaking &&
1365
- change.path) {
1366
- const [enumName, enumItem] = parsePath(change.path);
1367
- const type = oldSchema.getType(enumName);
1368
- if (graphql.isEnumType(type)) {
1369
- const item = type.getValue(enumItem);
1370
- if (item && isDeprecated(item)) {
1371
- return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }) });
1372
- }
1373
- }
1374
- }
1375
- if (change.type === exports.ChangeType.InputFieldRemoved &&
1376
- change.criticality.level === exports.CriticalityLevel.Breaking &&
1377
- change.path) {
1378
- const [inputName, inputItem] = parsePath(change.path);
1379
- const type = oldSchema.getType(inputName);
1380
- if (graphql.isInputObjectType(type)) {
1381
- const item = type.getFields()[inputItem];
1382
- if (item && isDeprecated(item)) {
1383
- return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.Dangerous }) });
1384
- }
1589
+ function similar(schema, typeName, threshold = 0.4) {
1590
+ const typeMap = schema.getTypeMap();
1591
+ const targets = Object.keys(schema.getTypeMap())
1592
+ .filter(name => !isPrimitive(name) && !isForIntrospection(name))
1593
+ .map(name => ({
1594
+ typeId: name,
1595
+ value: stripType(typeMap[name]),
1596
+ }));
1597
+ const results = {};
1598
+ if (typeof typeName !== 'undefined' && !targets.some(t => t.typeId === typeName)) {
1599
+ throw new Error(`Type '${typeName}' doesn't exist`);
1600
+ }
1601
+ (typeName ? [{ typeId: typeName, value: '' }] : targets).forEach(source => {
1602
+ const sourceType = schema.getType(source.typeId);
1603
+ const matchWith = targets.filter(target => schema.getType(target.typeId).astNode.kind === sourceType.astNode.kind &&
1604
+ target.typeId !== source.typeId);
1605
+ if (matchWith.length > 0) {
1606
+ const found = similarTo(sourceType, matchWith, threshold);
1607
+ if (found) {
1608
+ results[source.typeId] = found;
1385
1609
  }
1386
1610
  }
1387
- return change;
1388
1611
  });
1389
- };
1390
-
1391
- const descriptionChangeTypes = [
1392
- exports.ChangeType.FieldArgumentDescriptionChanged,
1393
- exports.ChangeType.DirectiveDescriptionChanged,
1394
- exports.ChangeType.DirectiveArgumentDescriptionChanged,
1395
- exports.ChangeType.EnumValueDescriptionChanged,
1396
- exports.ChangeType.FieldDescriptionChanged,
1397
- exports.ChangeType.FieldDescriptionAdded,
1398
- exports.ChangeType.FieldDescriptionRemoved,
1399
- exports.ChangeType.InputFieldDescriptionAdded,
1400
- exports.ChangeType.InputFieldDescriptionRemoved,
1401
- exports.ChangeType.InputFieldDescriptionChanged,
1402
- exports.ChangeType.TypeDescriptionChanged,
1403
- ];
1404
- const ignoreDescriptionChanges = ({ changes }) => {
1405
- return changes.filter((change) => descriptionChangeTypes.indexOf(change.type) === -1);
1406
- };
1407
-
1408
- const considerUsage = ({ changes, config, }) => tslib.__awaiter(void 0, void 0, void 0, function* () {
1409
- if (!config) {
1410
- throw new Error(`considerUsage rule is missing config`);
1612
+ return results;
1613
+ }
1614
+ function similarTo(type, targets, threshold) {
1615
+ const types = targets.filter(target => target.typeId !== type.name);
1616
+ const result = findBestMatch(stripType(type), types);
1617
+ if (result.bestMatch.rating < threshold) {
1618
+ return;
1411
1619
  }
1412
- const collectedBreakingField = [];
1413
- changes.forEach((change) => {
1414
- if (change.criticality.level === exports.CriticalityLevel.Breaking && change.path) {
1415
- const [typeName, fieldName, argumentName] = parsePath(change.path);
1416
- collectedBreakingField.push({
1417
- type: typeName,
1418
- field: fieldName,
1419
- argument: argumentName,
1420
- });
1421
- }
1422
- });
1423
- // True if safe to break, false otherwise
1424
- const usageList = yield config.checkUsage(collectedBreakingField);
1425
- // turns an array of booleans into an array of `Type.Field` strings
1426
- // includes only those that are safe to break the api
1427
- const suppressedPaths = collectedBreakingField
1428
- .filter((_, i) => usageList[i] === true)
1429
- .map(({ type, field, argument }) => [type, field, argument].filter(Boolean).join('.'));
1430
- return changes.map((change) => {
1431
- // Turns those "safe to break" changes into "dangerous"
1432
- if (change.criticality.level === exports.CriticalityLevel.Breaking &&
1433
- change.path &&
1434
- suppressedPaths.some((p) => change.path.startsWith(p))) {
1435
- 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)` });
1436
- }
1437
- return change;
1438
- });
1439
- });
1620
+ return {
1621
+ bestMatch: result.bestMatch,
1622
+ ratings: result.ratings
1623
+ .filter(r => r.rating >= threshold && r.target !== result.bestMatch.target)
1624
+ .sort((a, b) => a.rating - b.rating)
1625
+ .reverse(),
1626
+ };
1627
+ }
1628
+ function stripType(type) {
1629
+ return graphql.printType(type)
1630
+ .trim()
1631
+ .replace(/^[a-z]+ [^{]+\{/g, '')
1632
+ .replace(/\}$/g, '')
1633
+ .trim()
1634
+ .split('\n')
1635
+ .map(s => s.trim())
1636
+ .sort((a, b) => a.localeCompare(b))
1637
+ .join(' ');
1638
+ }
1440
1639
 
1441
- const safeUnreachable = ({ changes, oldSchema }) => {
1442
- const reachable = getReachableTypes(oldSchema);
1443
- return changes.map((change) => {
1444
- if (change.criticality.level === exports.CriticalityLevel.Breaking && change.path) {
1445
- const [typeName] = parsePath(change.path);
1446
- if (!reachable.has(typeName)) {
1447
- return Object.assign(Object.assign({}, change), { criticality: Object.assign(Object.assign({}, change.criticality), { level: exports.CriticalityLevel.NonBreaking }), message: 'Unreachable from root' });
1448
- }
1449
- }
1450
- return change;
1640
+ function transformDocumentWithApollo(doc, { keepClientFields }) {
1641
+ return graphql.visit(doc, {
1642
+ Field(node) {
1643
+ return keepClientFields
1644
+ ? removeDirectives(node, ['client'])
1645
+ : removeFieldIfDirectives(node, ['client']);
1646
+ },
1451
1647
  });
1452
- };
1453
-
1454
- const rules = /*#__PURE__*/Object.freeze({
1455
- __proto__: null,
1456
- dangerousBreaking: dangerousBreaking,
1457
- suppressRemovalOfDeprecatedField: suppressRemovalOfDeprecatedField,
1458
- ignoreDescriptionChanges: ignoreDescriptionChanges,
1459
- considerUsage: considerUsage,
1460
- safeUnreachable: safeUnreachable
1461
- });
1462
-
1463
- const DiffRule = rules;
1464
- function diff(oldSchema, newSchema, rules = [], config) {
1465
- const changes = diffSchema(oldSchema, newSchema);
1466
- return rules.reduce((prev, rule) => tslib.__awaiter(this, void 0, void 0, function* () {
1467
- const prevChanges = yield prev;
1468
- return rule({
1469
- changes: prevChanges,
1470
- oldSchema,
1471
- newSchema,
1472
- config,
1473
- });
1474
- }), Promise.resolve(changes));
1648
+ }
1649
+ function transformSchemaWithApollo(schema) {
1650
+ return graphql.extendSchema(schema, graphql.parse(/* GraphQL */ `
1651
+ directive @connection(key: String!, filter: [String]) on FIELD
1652
+ `));
1475
1653
  }
1476
1654
 
1477
- function readDocument(source) {
1478
- const result = {
1479
- source,
1480
- fragments: [],
1481
- operations: [],
1482
- hasFragments: false,
1483
- hasOperations: false,
1484
- };
1485
- const documentNode = graphql.parse(source.body);
1486
- const filepath = source.name;
1487
- const definitions = documentNode.definitions || [];
1488
- definitions.forEach((node) => {
1489
- if (isOperation(node)) {
1490
- result.operations.push({
1491
- node,
1492
- source: filepath,
1493
- });
1655
+ function validateAliasCount({ source, doc, maxAliasCount, fragmentGraph, }) {
1656
+ const getFragmentByFragmentName = (fragmentName) => fragmentGraph.getNodeData(fragmentName);
1657
+ for (const definition of doc.definitions) {
1658
+ if (definition.kind !== graphql.Kind.OPERATION_DEFINITION) {
1659
+ continue;
1494
1660
  }
1495
- else if (isFragment(node)) {
1496
- result.fragments.push({
1497
- node,
1498
- source: filepath,
1499
- });
1661
+ const aliasCount = countAliases(definition, getFragmentByFragmentName);
1662
+ if (aliasCount > maxAliasCount) {
1663
+ return new graphql.GraphQLError(`Too many aliases (${aliasCount}). Maximum allowed is ${maxAliasCount}`, [definition], source, definition.loc && definition.loc.start ? [definition.loc.start] : undefined);
1500
1664
  }
1501
- });
1502
- result.hasFragments = result.fragments.length > 0;
1503
- result.hasOperations = result.operations.length > 0;
1504
- return result;
1665
+ }
1505
1666
  }
1506
- function isOperation(node) {
1507
- return node.kind === graphql.Kind.OPERATION_DEFINITION;
1667
+ function countAliases(node, getFragmentByName) {
1668
+ let aliases = 0;
1669
+ if ('alias' in node && node.alias) {
1670
+ ++aliases;
1671
+ }
1672
+ if ('selectionSet' in node && node.selectionSet) {
1673
+ for (const child of node.selectionSet.selections) {
1674
+ aliases += countAliases(child, getFragmentByName);
1675
+ }
1676
+ }
1677
+ else if (node.kind === graphql.Kind.FRAGMENT_SPREAD) {
1678
+ const fragmentNode = getFragmentByName(node.name.value);
1679
+ if (fragmentNode) {
1680
+ aliases += countAliases(fragmentNode, getFragmentByName);
1681
+ }
1682
+ }
1683
+ return aliases;
1508
1684
  }
1509
- function isFragment(node) {
1510
- return node.kind === graphql.Kind.FRAGMENT_DEFINITION;
1685
+
1686
+ function validateDirectiveCount({ source, doc, maxDirectiveCount, fragmentGraph, }) {
1687
+ const getFragmentByFragmentName = (fragmentName) => fragmentGraph.getNodeData(fragmentName);
1688
+ for (const definition of doc.definitions) {
1689
+ if (definition.kind !== graphql.Kind.OPERATION_DEFINITION) {
1690
+ continue;
1691
+ }
1692
+ const directiveCount = countDirectives(definition, getFragmentByFragmentName);
1693
+ if (directiveCount > maxDirectiveCount) {
1694
+ return new graphql.GraphQLError(`Too many directives (${directiveCount}). Maximum allowed is ${maxDirectiveCount}`, [definition], source, definition.loc && definition.loc.start ? [definition.loc.start] : undefined);
1695
+ }
1696
+ }
1697
+ }
1698
+ function countDirectives(node, getFragmentByName) {
1699
+ let directives = 0;
1700
+ if (node.directives) {
1701
+ directives += node.directives.length;
1702
+ }
1703
+ if ('selectionSet' in node && node.selectionSet) {
1704
+ for (const child of node.selectionSet.selections) {
1705
+ directives += countDirectives(child, getFragmentByName);
1706
+ }
1707
+ }
1708
+ if (node.kind == graphql.Kind.FRAGMENT_SPREAD) {
1709
+ const fragment = getFragmentByName(node.name.value);
1710
+ if (fragment) {
1711
+ directives += countDirectives(fragment, getFragmentByName);
1712
+ }
1713
+ }
1714
+ return directives;
1511
1715
  }
1512
1716
 
1513
1717
  function validateQueryDepth({ source, doc, maxDepth, fragmentGraph, }) {
@@ -1547,20 +1751,20 @@ function calculateDepth({ node, currentDepth, maxDepth, getFragment, }) {
1547
1751
  return 1 + maxInnerDepth;
1548
1752
  }
1549
1753
  case graphql.Kind.SELECTION_SET: {
1550
- return Math.max(...node.selections.map((selection) => {
1754
+ return Math.max(...node.selections.map(selection => {
1551
1755
  return calculateDepth({
1552
1756
  node: selection,
1553
- currentDepth: currentDepth,
1757
+ currentDepth,
1554
1758
  maxDepth,
1555
1759
  getFragment,
1556
1760
  });
1557
1761
  }));
1558
1762
  }
1559
1763
  case graphql.Kind.DOCUMENT: {
1560
- return Math.max(...node.definitions.map((def) => {
1764
+ return Math.max(...node.definitions.map(def => {
1561
1765
  return calculateDepth({
1562
1766
  node: def,
1563
- currentDepth: currentDepth,
1767
+ currentDepth,
1564
1768
  maxDepth,
1565
1769
  getFragment,
1566
1770
  });
@@ -1569,7 +1773,7 @@ function calculateDepth({ node, currentDepth, maxDepth, getFragment, }) {
1569
1773
  case graphql.Kind.OPERATION_DEFINITION:
1570
1774
  case graphql.Kind.INLINE_FRAGMENT:
1571
1775
  case graphql.Kind.FRAGMENT_DEFINITION: {
1572
- return Math.max(...node.selectionSet.selections.map((selection) => {
1776
+ return Math.max(...node.selectionSet.selections.map(selection => {
1573
1777
  return calculateDepth({
1574
1778
  node: selection,
1575
1779
  currentDepth,
@@ -1590,20 +1794,68 @@ function calculateDepth({ node, currentDepth, maxDepth, getFragment, }) {
1590
1794
  }
1591
1795
  }
1592
1796
  }
1797
+ function countDepth(node, parentDepth, getFragmentReference) {
1798
+ let depth = parentDepth;
1799
+ if ('selectionSet' in node && node.selectionSet) {
1800
+ for (const child of node.selectionSet.selections) {
1801
+ depth = Math.max(depth, countDepth(child, parentDepth + 1, getFragmentReference));
1802
+ }
1803
+ }
1804
+ if (node.kind == graphql.Kind.FRAGMENT_SPREAD) {
1805
+ const fragment = getFragmentReference(node.name.value);
1806
+ if (fragment) {
1807
+ depth = Math.max(depth, countDepth(fragment, parentDepth + 1, getFragmentReference));
1808
+ }
1809
+ }
1810
+ return depth;
1811
+ }
1593
1812
 
1594
- function transformDocumentWithApollo(doc, { keepClientFields }) {
1595
- return graphql.visit(doc, {
1596
- Field(node) {
1597
- return keepClientFields
1598
- ? removeDirectives(node, ['client'])
1599
- : removeFieldIfDirectives(node, ['client']);
1813
+ class ParserWithLexer extends parser.Parser {
1814
+ constructor(source, options) {
1815
+ super(source, options);
1816
+ this.__tokenCount = 0;
1817
+ const lexer = this._lexer;
1818
+ this._lexer = new Proxy(lexer, {
1819
+ get: (target, prop, receiver) => {
1820
+ if (prop === 'advance') {
1821
+ return () => {
1822
+ const token = target.advance();
1823
+ if (token.kind !== graphql.TokenKind.EOF) {
1824
+ this.__tokenCount++;
1825
+ }
1826
+ return token;
1827
+ };
1828
+ }
1829
+ return Reflect.get(target, prop, receiver);
1830
+ },
1831
+ });
1832
+ }
1833
+ get tokenCount() {
1834
+ return this.__tokenCount;
1835
+ }
1836
+ }
1837
+ function calculateTokenCount(args) {
1838
+ const parser = new ParserWithLexer(args.source);
1839
+ const document = parser.parseDocument();
1840
+ let { tokenCount } = parser;
1841
+ graphql.visit(document, {
1842
+ FragmentSpread(node) {
1843
+ const fragmentSource = args.getReferencedFragmentSource(node.name.value);
1844
+ if (fragmentSource) {
1845
+ tokenCount += calculateTokenCount({
1846
+ source: fragmentSource,
1847
+ getReferencedFragmentSource: args.getReferencedFragmentSource,
1848
+ });
1849
+ }
1600
1850
  },
1601
1851
  });
1852
+ return tokenCount;
1602
1853
  }
1603
- function transformSchemaWithApollo(schema) {
1604
- return graphql.extendSchema(schema, graphql.parse(/* GraphQL */ `
1605
- directive @connection(key: String!, filter: [String]) on FIELD
1606
- `));
1854
+ function validateTokenCount(args) {
1855
+ const tokenCount = calculateTokenCount(args);
1856
+ if (tokenCount > args.maxTokenCount) {
1857
+ 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);
1858
+ }
1607
1859
  }
1608
1860
 
1609
1861
  function validate(schema, sources, options) {
@@ -1615,43 +1867,41 @@ function validate(schema, sources, options) {
1615
1867
  const fragments = [];
1616
1868
  const fragmentNames = [];
1617
1869
  const graph = new dependencyGraph.DepGraph({ circular: true });
1618
- documents.forEach((doc) => {
1619
- doc.fragments.forEach((fragment) => {
1870
+ documents.forEach(doc => {
1871
+ doc.fragments.forEach(fragment => {
1620
1872
  fragmentNames.push(fragment.node.name.value);
1621
1873
  fragments.push(fragment);
1622
1874
  graph.addNode(fragment.node.name.value, fragment.node);
1623
1875
  });
1624
1876
  });
1625
- fragments.forEach((fragment) => {
1877
+ fragments.forEach(fragment => {
1626
1878
  const depends = extractFragments(graphql.print(fragment.node));
1627
1879
  if (depends) {
1628
- depends.forEach((name) => {
1880
+ depends.forEach(name => {
1629
1881
  graph.addDependency(fragment.node.name.value, name);
1630
1882
  });
1631
1883
  }
1632
1884
  });
1633
1885
  documents
1634
1886
  // since we include fragments, validate only operations
1635
- .filter((doc) => doc.hasOperations)
1636
- .forEach((doc) => {
1887
+ .filter(doc => doc.hasOperations)
1888
+ .forEach(doc => {
1637
1889
  const docWithOperations = {
1638
1890
  kind: graphql.Kind.DOCUMENT,
1639
- definitions: doc.operations.map((d) => d.node),
1891
+ definitions: doc.operations.map(d => d.node),
1640
1892
  };
1641
1893
  const extractedFragments = (extractFragments(graphql.print(docWithOperations)) || [])
1642
1894
  // resolve all nested fragments
1643
- .map((fragmentName) => resolveFragment(graph.getNodeData(fragmentName), graph))
1895
+ .map(fragmentName => resolveFragment(graph.getNodeData(fragmentName), graph))
1644
1896
  // flatten arrays
1645
1897
  .reduce((list, current) => list.concat(current), [])
1646
1898
  // remove duplicates
1647
- .filter((def, i, all) => all.findIndex((item) => item.name.value === def.name.value) === i);
1899
+ .filter((def, i, all) => all.findIndex(item => item.name.value === def.name.value) === i);
1648
1900
  const merged = {
1649
1901
  kind: graphql.Kind.DOCUMENT,
1650
1902
  definitions: [...docWithOperations.definitions, ...extractedFragments],
1651
1903
  };
1652
- let transformedSchema = config.apollo
1653
- ? transformSchemaWithApollo(schema)
1654
- : schema;
1904
+ const transformedSchema = config.apollo ? transformSchemaWithApollo(schema) : schema;
1655
1905
  const transformedDoc = config.apollo
1656
1906
  ? transformDocumentWithApollo(merged, {
1657
1907
  keepClientFields: config.keepClientFields,
@@ -1669,6 +1919,39 @@ function validate(schema, sources, options) {
1669
1919
  errors.push(depthError);
1670
1920
  }
1671
1921
  }
1922
+ if (config.maxAliasCount) {
1923
+ const aliasError = validateAliasCount({
1924
+ source: doc.source,
1925
+ doc: transformedDoc,
1926
+ maxAliasCount: config.maxAliasCount,
1927
+ fragmentGraph: graph,
1928
+ });
1929
+ if (aliasError) {
1930
+ errors.push(aliasError);
1931
+ }
1932
+ }
1933
+ if (config.maxDirectiveCount) {
1934
+ const directiveError = validateDirectiveCount({
1935
+ source: doc.source,
1936
+ doc: transformedDoc,
1937
+ maxDirectiveCount: config.maxDirectiveCount,
1938
+ fragmentGraph: graph,
1939
+ });
1940
+ if (directiveError) {
1941
+ errors.push(directiveError);
1942
+ }
1943
+ }
1944
+ if (config.maxTokenCount) {
1945
+ const tokenCountError = validateTokenCount({
1946
+ source: doc.source,
1947
+ document: transformedDoc,
1948
+ maxTokenCount: config.maxTokenCount,
1949
+ getReferencedFragmentSource: fragmentName => graphql.print(graph.getNodeData(fragmentName)),
1950
+ });
1951
+ if (tokenCountError) {
1952
+ errors.push(tokenCountError);
1953
+ }
1954
+ }
1672
1955
  const deprecated = config.strictDeprecated
1673
1956
  ? findDeprecatedUsages(transformedSchema, transformedDoc)
1674
1957
  : [];
@@ -1688,7 +1971,7 @@ function validate(schema, sources, options) {
1688
1971
  function findDuplicatedFragments(fragmentNames) {
1689
1972
  return fragmentNames
1690
1973
  .filter((name, i, all) => all.indexOf(name) !== i)
1691
- .map((name) => new graphql.GraphQLError(`Name of '${name}' fragment is not unique`));
1974
+ .map(name => new graphql.GraphQLError(`Name of '${name}' fragment is not unique`));
1692
1975
  }
1693
1976
  //
1694
1977
  // PostInfo -> AuthorInfo
@@ -1697,157 +1980,42 @@ function findDuplicatedFragments(fragmentNames) {
1697
1980
  function resolveFragment(fragment, graph) {
1698
1981
  return graph
1699
1982
  .dependenciesOf(fragment.name.value)
1700
- .reduce((list, current) => [
1701
- ...list,
1702
- ...resolveFragment(graph.getNodeData(current), graph),
1703
- ], [fragment]);
1983
+ .reduce((list, current) => [...list, ...resolveFragment(graph.getNodeData(current), graph)], [fragment]);
1704
1984
  }
1705
1985
  function extractFragments(document) {
1706
- return (document.match(/[\.]{3}[a-z0-9\_]+\b/gi) || []).map((name) => name.replace('...', ''));
1986
+ return (document.match(/[.]{3}[a-z0-9_]+\b/gi) || []).map(name => name.replace('...', ''));
1707
1987
  }
1708
1988
  function sumLengths(...arrays) {
1709
1989
  return arrays.reduce((sum, { length }) => sum + length, 0);
1710
1990
  }
1711
1991
 
1712
- function similar(schema, typeName, threshold = 0.4) {
1713
- const typeMap = schema.getTypeMap();
1714
- const targets = Object.keys(schema.getTypeMap())
1715
- .filter((name) => !isPrimitive(name) && !isForIntrospection(name))
1716
- .map((name) => ({
1717
- typeId: name,
1718
- value: stripType(typeMap[name]),
1719
- }));
1720
- const results = {};
1721
- if (typeof typeName !== 'undefined' &&
1722
- !targets.some((t) => t.typeId === typeName)) {
1723
- throw new Error(`Type '${typeName}' doesn't exist`);
1724
- }
1725
- (typeName ? [{ typeId: typeName, value: '' }] : targets).forEach((source) => {
1726
- const sourceType = schema.getType(source.typeId);
1727
- const matchWith = targets.filter((target) => schema.getType(target.typeId).astNode.kind ===
1728
- sourceType.astNode.kind && target.typeId !== source.typeId);
1729
- if (matchWith.length > 0) {
1730
- const found = similarTo(sourceType, matchWith, threshold);
1731
- if (found) {
1732
- results[source.typeId] = found;
1733
- }
1992
+ function calculateOperationComplexity(node, config, getFragmentByName, depth = 0) {
1993
+ let cost = config.scalarCost;
1994
+ if ('selectionSet' in node && node.selectionSet) {
1995
+ cost = config.objectCost;
1996
+ for (const child of node.selectionSet.selections) {
1997
+ cost +=
1998
+ config.depthCostFactor *
1999
+ calculateOperationComplexity(child, config, getFragmentByName, depth + 1);
1734
2000
  }
1735
- });
1736
- return results;
1737
- }
1738
- function similarTo(type, targets, threshold) {
1739
- const types = targets.filter((target) => target.typeId !== type.name);
1740
- const result = findBestMatch(stripType(type), types);
1741
- if (result.bestMatch.rating < threshold) {
1742
- return;
1743
2001
  }
1744
- return {
1745
- bestMatch: result.bestMatch,
1746
- ratings: result.ratings
1747
- .filter((r) => r.rating >= threshold && r.target !== result.bestMatch.target)
1748
- .sort((a, b) => a.rating - b.rating)
1749
- .reverse(),
1750
- };
1751
- }
1752
- function stripType(type) {
1753
- return graphql.printType(type)
1754
- .trim()
1755
- .replace(/^[a-z]+ [^\{]+\{/g, '')
1756
- .replace(/\}$/g, '')
1757
- .trim()
1758
- .split('\n')
1759
- .map((s) => s.trim())
1760
- .sort((a, b) => a.localeCompare(b))
1761
- .join(' ');
1762
- }
1763
-
1764
- function coverage(schema, sources) {
1765
- const coverage = {
1766
- sources,
1767
- types: {},
1768
- };
1769
- const typeMap = schema.getTypeMap();
1770
- const typeInfo = new graphql.TypeInfo(schema);
1771
- const visitor = (source) => ({
1772
- Field(node) {
1773
- const fieldDef = typeInfo.getFieldDef();
1774
- const parent = typeInfo.getParentType();
1775
- if (parent &&
1776
- parent.name &&
1777
- !isForIntrospection(parent.name) &&
1778
- fieldDef &&
1779
- fieldDef.name &&
1780
- fieldDef.name !== '__typename' &&
1781
- fieldDef.name !== '__schema') {
1782
- const sourceName = source.name;
1783
- const typeCoverage = coverage.types[parent.name];
1784
- const fieldCoverage = typeCoverage.children[fieldDef.name];
1785
- const locations = fieldCoverage.locations[sourceName];
1786
- typeCoverage.hits++;
1787
- fieldCoverage.hits++;
1788
- if (node.loc) {
1789
- fieldCoverage.locations[sourceName] = [
1790
- node.loc,
1791
- ...(locations || []),
1792
- ];
1793
- }
1794
- if (node.arguments) {
1795
- for (const argNode of node.arguments) {
1796
- const argCoverage = fieldCoverage.children[argNode.name.value];
1797
- argCoverage.hits++;
1798
- if (argNode.loc) {
1799
- argCoverage.locations[sourceName] = [
1800
- argNode.loc,
1801
- ...(argCoverage.locations[sourceName] || []),
1802
- ];
1803
- }
1804
- }
1805
- }
1806
- }
1807
- },
1808
- });
1809
- for (const typename in typeMap) {
1810
- if (!isForIntrospection(typename) && !isPrimitive(typename)) {
1811
- const type = typeMap[typename];
1812
- if (graphql.isObjectType(type) || graphql.isInterfaceType(type)) {
1813
- const typeCoverage = {
1814
- hits: 0,
1815
- type,
1816
- children: {},
1817
- };
1818
- const fieldMap = type.getFields();
1819
- for (const fieldname in fieldMap) {
1820
- const field = fieldMap[fieldname];
1821
- typeCoverage.children[field.name] = {
1822
- hits: 0,
1823
- locations: {},
1824
- children: {},
1825
- };
1826
- for (const arg of field.args) {
1827
- typeCoverage.children[field.name].children[arg.name] = {
1828
- hits: 0,
1829
- locations: {},
1830
- };
1831
- }
1832
- }
1833
- coverage.types[type.name] = typeCoverage;
1834
- }
2002
+ if (node.kind == graphql.Kind.FRAGMENT_SPREAD) {
2003
+ const fragment = getFragmentByName(node.name.value);
2004
+ if (fragment) {
2005
+ cost +=
2006
+ config.depthCostFactor *
2007
+ calculateOperationComplexity(fragment, config, getFragmentByName, depth + 1);
1835
2008
  }
1836
2009
  }
1837
- const documents = coverage.sources.map(readDocument);
1838
- documents.forEach((doc, i) => {
1839
- const source = coverage.sources[i];
1840
- doc.operations.forEach((op) => {
1841
- graphql.visit(op.node, graphql.visitWithTypeInfo(typeInfo, visitor(source)));
1842
- });
1843
- doc.fragments.forEach((fr) => {
1844
- graphql.visit(fr.node, graphql.visitWithTypeInfo(typeInfo, visitor(source)));
1845
- });
1846
- });
1847
- return coverage;
2010
+ return cost;
1848
2011
  }
1849
2012
 
1850
2013
  exports.DiffRule = DiffRule;
2014
+ exports.calculateOperationComplexity = calculateOperationComplexity;
2015
+ exports.calculateTokenCount = calculateTokenCount;
2016
+ exports.countAliases = countAliases;
2017
+ exports.countDepth = countDepth;
2018
+ exports.countDirectives = countDirectives;
1851
2019
  exports.coverage = coverage;
1852
2020
  exports.diff = diff;
1853
2021
  exports.getTypePrefix = getTypePrefix;