UNPKG

102 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5const graphql = require('graphql');
6
7const useExtendedValidation = (options) => {
8 let schemaTypeInfo;
9 return {
10 onSchemaChange({ schema }) {
11 schemaTypeInfo = new graphql.TypeInfo(schema);
12 },
13 onExecute({ args, setResultAndStopExecution }) {
14 const errors = [];
15 const typeInfo = schemaTypeInfo || new graphql.TypeInfo(args.schema);
16 const validationContext = new graphql.ValidationContext(args.schema, args.document, typeInfo, e => {
17 errors.push(e);
18 });
19 const visitor = graphql.visitInParallel(options.rules.map(rule => rule(validationContext, args)));
20 graphql.visit(args.document, graphql.visitWithTypeInfo(typeInfo, visitor));
21 for (const rule of options.rules) {
22 rule(validationContext, args);
23 }
24 if (errors.length > 0) {
25 setResultAndStopExecution({
26 data: null,
27 errors,
28 });
29 }
30 },
31 };
32};
33
34function getDirectiveFromAstNode(astNode, names) {
35 const directives = astNode.directives || [];
36 const namesArr = Array.isArray(names) ? names : [names];
37 const authDirective = directives.find(d => namesArr.includes(d.name.value));
38 return authDirective || null;
39}
40function unwrapType(type) {
41 if (graphql.isNonNullType(type) || graphql.isListType(type)) {
42 return unwrapType(type.ofType);
43 }
44 return type;
45}
46
47/**
48 * Creates a keyed JS object from an array, given a function to produce the keys
49 * for each value in the array.
50 *
51 * This provides a convenient lookup for the array items if the key function
52 * produces unique results.
53 *
54 * const phoneBook = [
55 * { name: 'Jon', num: '555-1234' },
56 * { name: 'Jenny', num: '867-5309' }
57 * ]
58 *
59 * // { Jon: { name: 'Jon', num: '555-1234' },
60 * // Jenny: { name: 'Jenny', num: '867-5309' } }
61 * const entriesByName = keyMap(
62 * phoneBook,
63 * entry => entry.name
64 * )
65 *
66 * // { name: 'Jenny', num: '857-6309' }
67 * const jennyEntry = entriesByName['Jenny']
68 *
69 */
70function keyMap(list, keyFn) {
71 return list.reduce(function (map, item) {
72 map[keyFn(item)] = item;
73 return map;
74 }, Object.create(null));
75}
76
77// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
78var nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;
79
80function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
81var MAX_ARRAY_LENGTH = 10;
82var MAX_RECURSIVE_DEPTH = 2;
83/**
84 * Used to print values in error messages.
85 */
86
87function inspect(value) {
88 return formatValue(value, []);
89}
90
91function formatValue(value, seenValues) {
92 switch (_typeof(value)) {
93 case 'string':
94 return JSON.stringify(value);
95
96 case 'function':
97 return value.name ? "[function ".concat(value.name, "]") : '[function]';
98
99 case 'object':
100 if (value === null) {
101 return 'null';
102 }
103
104 return formatObjectValue(value, seenValues);
105
106 default:
107 return String(value);
108 }
109}
110
111function formatObjectValue(value, previouslySeenValues) {
112 if (previouslySeenValues.indexOf(value) !== -1) {
113 return '[Circular]';
114 }
115
116 var seenValues = [].concat(previouslySeenValues, [value]);
117 var customInspectFn = getCustomFn(value);
118
119 if (customInspectFn !== undefined) {
120 var customValue = customInspectFn.call(value); // check for infinite recursion
121
122 if (customValue !== value) {
123 return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues);
124 }
125 } else if (Array.isArray(value)) {
126 return formatArray(value, seenValues);
127 }
128
129 return formatObject(value, seenValues);
130}
131
132function formatObject(object, seenValues) {
133 var keys = Object.keys(object);
134
135 if (keys.length === 0) {
136 return '{}';
137 }
138
139 if (seenValues.length > MAX_RECURSIVE_DEPTH) {
140 return '[' + getObjectTag(object) + ']';
141 }
142
143 var properties = keys.map(function (key) {
144 var value = formatValue(object[key], seenValues);
145 return key + ': ' + value;
146 });
147 return '{ ' + properties.join(', ') + ' }';
148}
149
150function formatArray(array, seenValues) {
151 if (array.length === 0) {
152 return '[]';
153 }
154
155 if (seenValues.length > MAX_RECURSIVE_DEPTH) {
156 return '[Array]';
157 }
158
159 var len = Math.min(MAX_ARRAY_LENGTH, array.length);
160 var remaining = array.length - len;
161 var items = [];
162
163 for (var i = 0; i < len; ++i) {
164 items.push(formatValue(array[i], seenValues));
165 }
166
167 if (remaining === 1) {
168 items.push('... 1 more item');
169 } else if (remaining > 1) {
170 items.push("... ".concat(remaining, " more items"));
171 }
172
173 return '[' + items.join(', ') + ']';
174}
175
176function getCustomFn(object) {
177 var customInspectFn = object[String(nodejsCustomInspectSymbol)];
178
179 if (typeof customInspectFn === 'function') {
180 return customInspectFn;
181 }
182
183 if (typeof object.inspect === 'function') {
184 return object.inspect;
185 }
186}
187
188function getObjectTag(object) {
189 var tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, '');
190
191 if (tag === 'Object' && typeof object.constructor === 'function') {
192 var name = object.constructor.name;
193
194 if (typeof name === 'string' && name !== '') {
195 return name;
196 }
197 }
198
199 return tag;
200}
201
202function _typeof$1(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); }
203
204/**
205 * Return true if `value` is object-like. A value is object-like if it's not
206 * `null` and has a `typeof` result of "object".
207 */
208function isObjectLike(value) {
209 return _typeof$1(value) == 'object' && value !== null;
210}
211
212// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator
213
214var SYMBOL_TO_STRING_TAG = typeof Symbol === 'function' && Symbol.toStringTag != null ? Symbol.toStringTag : '@@toStringTag';
215
216/**
217 * Represents a location in a Source.
218 */
219
220/**
221 * Takes a Source and a UTF-8 character offset, and returns the corresponding
222 * line and column as a SourceLocation.
223 */
224function getLocation(source, position) {
225 var lineRegexp = /\r\n|[\n\r]/g;
226 var line = 1;
227 var column = position + 1;
228 var match;
229
230 while ((match = lineRegexp.exec(source.body)) && match.index < position) {
231 line += 1;
232 column = position + 1 - (match.index + match[0].length);
233 }
234
235 return {
236 line: line,
237 column: column
238 };
239}
240
241/**
242 * Render a helpful description of the location in the GraphQL Source document.
243 */
244
245function printLocation(location) {
246 return printSourceLocation(location.source, getLocation(location.source, location.start));
247}
248/**
249 * Render a helpful description of the location in the GraphQL Source document.
250 */
251
252function printSourceLocation(source, sourceLocation) {
253 var firstLineColumnOffset = source.locationOffset.column - 1;
254 var body = whitespace(firstLineColumnOffset) + source.body;
255 var lineIndex = sourceLocation.line - 1;
256 var lineOffset = source.locationOffset.line - 1;
257 var lineNum = sourceLocation.line + lineOffset;
258 var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
259 var columnNum = sourceLocation.column + columnOffset;
260 var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");
261 var lines = body.split(/\r\n|[\n\r]/g);
262 var locationLine = lines[lineIndex]; // Special case for minified documents
263
264 if (locationLine.length > 120) {
265 var subLineIndex = Math.floor(columnNum / 80);
266 var subLineColumnNum = columnNum % 80;
267 var subLines = [];
268
269 for (var i = 0; i < locationLine.length; i += 80) {
270 subLines.push(locationLine.slice(i, i + 80));
271 }
272
273 return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) {
274 return ['', subLine];
275 }), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]]));
276 }
277
278 return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"],
279 ["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]);
280}
281
282function printPrefixedLines(lines) {
283 var existingLines = lines.filter(function (_ref) {
284 var _ = _ref[0],
285 line = _ref[1];
286 return line !== undefined;
287 });
288 var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {
289 var prefix = _ref2[0];
290 return prefix.length;
291 }));
292 return existingLines.map(function (_ref3) {
293 var prefix = _ref3[0],
294 line = _ref3[1];
295 return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |');
296 }).join('\n');
297}
298
299function whitespace(len) {
300 return Array(len + 1).join(' ');
301}
302
303function leftPad(len, str) {
304 return whitespace(len - str.length) + str;
305}
306
307function _typeof$2(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$2 = function _typeof(obj) { return typeof obj; }; } else { _typeof$2 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$2(obj); }
308
309function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
310
311function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
312
313function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
314
315function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
316
317function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
318
319function _possibleConstructorReturn(self, call) { if (call && (_typeof$2(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
320
321function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
322
323function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
324
325function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
326
327function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
328
329function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
330
331function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
332
333function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
334/**
335 * A GraphQLError describes an Error found during the parse, validate, or
336 * execute phases of performing a GraphQL operation. In addition to a message
337 * and stack trace, it also includes information about the locations in a
338 * GraphQL document and/or execution result that correspond to the Error.
339 */
340
341var GraphQLError = /*#__PURE__*/function (_Error) {
342 _inherits(GraphQLError, _Error);
343
344 var _super = _createSuper(GraphQLError);
345
346 /**
347 * A message describing the Error for debugging purposes.
348 *
349 * Enumerable, and appears in the result of JSON.stringify().
350 *
351 * Note: should be treated as readonly, despite invariant usage.
352 */
353
354 /**
355 * An array of { line, column } locations within the source GraphQL document
356 * which correspond to this error.
357 *
358 * Errors during validation often contain multiple locations, for example to
359 * point out two things with the same name. Errors during execution include a
360 * single location, the field which produced the error.
361 *
362 * Enumerable, and appears in the result of JSON.stringify().
363 */
364
365 /**
366 * An array describing the JSON-path into the execution response which
367 * corresponds to this error. Only included for errors during execution.
368 *
369 * Enumerable, and appears in the result of JSON.stringify().
370 */
371
372 /**
373 * An array of GraphQL AST Nodes corresponding to this error.
374 */
375
376 /**
377 * The source GraphQL document for the first location of this error.
378 *
379 * Note that if this Error represents more than one node, the source may not
380 * represent nodes after the first node.
381 */
382
383 /**
384 * An array of character offsets within the source GraphQL document
385 * which correspond to this error.
386 */
387
388 /**
389 * The original error thrown from a field resolver during execution.
390 */
391
392 /**
393 * Extension fields to add to the formatted error.
394 */
395 function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {
396 var _locations2, _source2, _positions2, _extensions2;
397
398 var _this;
399
400 _classCallCheck(this, GraphQLError);
401
402 _this = _super.call(this, message); // Compute list of blame nodes.
403
404 var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.
405
406
407 var _source = source;
408
409 if (!_source && _nodes) {
410 var _nodes$0$loc;
411
412 _source = (_nodes$0$loc = _nodes[0].loc) === null || _nodes$0$loc === void 0 ? void 0 : _nodes$0$loc.source;
413 }
414
415 var _positions = positions;
416
417 if (!_positions && _nodes) {
418 _positions = _nodes.reduce(function (list, node) {
419 if (node.loc) {
420 list.push(node.loc.start);
421 }
422
423 return list;
424 }, []);
425 }
426
427 if (_positions && _positions.length === 0) {
428 _positions = undefined;
429 }
430
431 var _locations;
432
433 if (positions && source) {
434 _locations = positions.map(function (pos) {
435 return getLocation(source, pos);
436 });
437 } else if (_nodes) {
438 _locations = _nodes.reduce(function (list, node) {
439 if (node.loc) {
440 list.push(getLocation(node.loc.source, node.loc.start));
441 }
442
443 return list;
444 }, []);
445 }
446
447 var _extensions = extensions;
448
449 if (_extensions == null && originalError != null) {
450 var originalExtensions = originalError.extensions;
451
452 if (isObjectLike(originalExtensions)) {
453 _extensions = originalExtensions;
454 }
455 }
456
457 Object.defineProperties(_assertThisInitialized(_this), {
458 name: {
459 value: 'GraphQLError'
460 },
461 message: {
462 value: message,
463 // By being enumerable, JSON.stringify will include `message` in the
464 // resulting output. This ensures that the simplest possible GraphQL
465 // service adheres to the spec.
466 enumerable: true,
467 writable: true
468 },
469 locations: {
470 // Coercing falsy values to undefined ensures they will not be included
471 // in JSON.stringify() when not provided.
472 value: (_locations2 = _locations) !== null && _locations2 !== void 0 ? _locations2 : undefined,
473 // By being enumerable, JSON.stringify will include `locations` in the
474 // resulting output. This ensures that the simplest possible GraphQL
475 // service adheres to the spec.
476 enumerable: _locations != null
477 },
478 path: {
479 // Coercing falsy values to undefined ensures they will not be included
480 // in JSON.stringify() when not provided.
481 value: path !== null && path !== void 0 ? path : undefined,
482 // By being enumerable, JSON.stringify will include `path` in the
483 // resulting output. This ensures that the simplest possible GraphQL
484 // service adheres to the spec.
485 enumerable: path != null
486 },
487 nodes: {
488 value: _nodes !== null && _nodes !== void 0 ? _nodes : undefined
489 },
490 source: {
491 value: (_source2 = _source) !== null && _source2 !== void 0 ? _source2 : undefined
492 },
493 positions: {
494 value: (_positions2 = _positions) !== null && _positions2 !== void 0 ? _positions2 : undefined
495 },
496 originalError: {
497 value: originalError
498 },
499 extensions: {
500 // Coercing falsy values to undefined ensures they will not be included
501 // in JSON.stringify() when not provided.
502 value: (_extensions2 = _extensions) !== null && _extensions2 !== void 0 ? _extensions2 : undefined,
503 // By being enumerable, JSON.stringify will include `path` in the
504 // resulting output. This ensures that the simplest possible GraphQL
505 // service adheres to the spec.
506 enumerable: _extensions != null
507 }
508 }); // Include (non-enumerable) stack trace.
509
510 if (originalError !== null && originalError !== void 0 && originalError.stack) {
511 Object.defineProperty(_assertThisInitialized(_this), 'stack', {
512 value: originalError.stack,
513 writable: true,
514 configurable: true
515 });
516 return _possibleConstructorReturn(_this);
517 } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
518
519
520 if (Error.captureStackTrace) {
521 Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);
522 } else {
523 Object.defineProperty(_assertThisInitialized(_this), 'stack', {
524 value: Error().stack,
525 writable: true,
526 configurable: true
527 });
528 }
529
530 return _this;
531 }
532
533 _createClass(GraphQLError, [{
534 key: "toString",
535 value: function toString() {
536 return printError(this);
537 } // FIXME: workaround to not break chai comparisons, should be remove in v16
538 // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
539
540 }, {
541 key: SYMBOL_TO_STRING_TAG,
542 get: function get() {
543 return 'Object';
544 }
545 }]);
546
547 return GraphQLError;
548}( /*#__PURE__*/_wrapNativeSuper(Error));
549/**
550 * Prints a GraphQLError to a string, representing useful location information
551 * about the error's position in the source.
552 */
553
554function printError(error) {
555 var output = error.message;
556
557 if (error.nodes) {
558 for (var _i2 = 0, _error$nodes2 = error.nodes; _i2 < _error$nodes2.length; _i2++) {
559 var node = _error$nodes2[_i2];
560
561 if (node.loc) {
562 output += '\n\n' + printLocation(node.loc);
563 }
564 }
565 } else if (error.source && error.locations) {
566 for (var _i4 = 0, _error$locations2 = error.locations; _i4 < _error$locations2.length; _i4++) {
567 var location = _error$locations2[_i4];
568 output += '\n\n' + printSourceLocation(error.source, location);
569 }
570 }
571
572 return output;
573}
574
575/**
576 * The set of allowed kind values for AST nodes.
577 */
578var Kind = Object.freeze({
579 // Name
580 NAME: 'Name',
581 // Document
582 DOCUMENT: 'Document',
583 OPERATION_DEFINITION: 'OperationDefinition',
584 VARIABLE_DEFINITION: 'VariableDefinition',
585 SELECTION_SET: 'SelectionSet',
586 FIELD: 'Field',
587 ARGUMENT: 'Argument',
588 // Fragments
589 FRAGMENT_SPREAD: 'FragmentSpread',
590 INLINE_FRAGMENT: 'InlineFragment',
591 FRAGMENT_DEFINITION: 'FragmentDefinition',
592 // Values
593 VARIABLE: 'Variable',
594 INT: 'IntValue',
595 FLOAT: 'FloatValue',
596 STRING: 'StringValue',
597 BOOLEAN: 'BooleanValue',
598 NULL: 'NullValue',
599 ENUM: 'EnumValue',
600 LIST: 'ListValue',
601 OBJECT: 'ObjectValue',
602 OBJECT_FIELD: 'ObjectField',
603 // Directives
604 DIRECTIVE: 'Directive',
605 // Types
606 NAMED_TYPE: 'NamedType',
607 LIST_TYPE: 'ListType',
608 NON_NULL_TYPE: 'NonNullType',
609 // Type System Definitions
610 SCHEMA_DEFINITION: 'SchemaDefinition',
611 OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',
612 // Type Definitions
613 SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',
614 OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',
615 FIELD_DEFINITION: 'FieldDefinition',
616 INPUT_VALUE_DEFINITION: 'InputValueDefinition',
617 INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',
618 UNION_TYPE_DEFINITION: 'UnionTypeDefinition',
619 ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',
620 ENUM_VALUE_DEFINITION: 'EnumValueDefinition',
621 INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',
622 // Directive Definitions
623 DIRECTIVE_DEFINITION: 'DirectiveDefinition',
624 // Type System Extensions
625 SCHEMA_EXTENSION: 'SchemaExtension',
626 // Type Extensions
627 SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',
628 OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',
629 INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',
630 UNION_TYPE_EXTENSION: 'UnionTypeExtension',
631 ENUM_TYPE_EXTENSION: 'EnumTypeExtension',
632 INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'
633});
634/**
635 * The enum type representing the possible kind values of AST nodes.
636 */
637
638function invariant(condition, message) {
639 var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')
640
641 if (!booleanCondition) {
642 throw new Error(message != null ? message : 'Unexpected invariant triggered.');
643 }
644}
645
646/**
647 * The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON`
648 */
649
650function defineInspect(classObject) {
651 var fn = classObject.prototype.toJSON;
652 typeof fn === 'function' || invariant(0);
653 classObject.prototype.inspect = fn; // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317')
654
655 if (nodejsCustomInspectSymbol) {
656 classObject.prototype[nodejsCustomInspectSymbol] = fn;
657 }
658}
659
660/**
661 * Contains a range of UTF-8 character offsets and token references that
662 * identify the region of the source from which the AST derived.
663 */
664var Location = /*#__PURE__*/function () {
665 /**
666 * The character offset at which this Node begins.
667 */
668
669 /**
670 * The character offset at which this Node ends.
671 */
672
673 /**
674 * The Token at which this Node begins.
675 */
676
677 /**
678 * The Token at which this Node ends.
679 */
680
681 /**
682 * The Source document the AST represents.
683 */
684 function Location(startToken, endToken, source) {
685 this.start = startToken.start;
686 this.end = endToken.end;
687 this.startToken = startToken;
688 this.endToken = endToken;
689 this.source = source;
690 }
691
692 var _proto = Location.prototype;
693
694 _proto.toJSON = function toJSON() {
695 return {
696 start: this.start,
697 end: this.end
698 };
699 };
700
701 return Location;
702}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
703
704defineInspect(Location);
705/**
706 * Represents a range of characters represented by a lexical token
707 * within a Source.
708 */
709
710var Token = /*#__PURE__*/function () {
711 /**
712 * The kind of Token.
713 */
714
715 /**
716 * The character offset at which this Node begins.
717 */
718
719 /**
720 * The character offset at which this Node ends.
721 */
722
723 /**
724 * The 1-indexed line number on which this Token appears.
725 */
726
727 /**
728 * The 1-indexed column number at which this Token begins.
729 */
730
731 /**
732 * For non-punctuation tokens, represents the interpreted value of the token.
733 */
734
735 /**
736 * Tokens exist as nodes in a double-linked-list amongst all tokens
737 * including ignored tokens. <SOF> is always the first node and <EOF>
738 * the last.
739 */
740 function Token(kind, start, end, line, column, prev, value) {
741 this.kind = kind;
742 this.start = start;
743 this.end = end;
744 this.line = line;
745 this.column = column;
746 this.value = value;
747 this.prev = prev;
748 this.next = null;
749 }
750
751 var _proto2 = Token.prototype;
752
753 _proto2.toJSON = function toJSON() {
754 return {
755 kind: this.kind,
756 value: this.value,
757 line: this.line,
758 column: this.column
759 };
760 };
761
762 return Token;
763}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
764
765defineInspect(Token);
766/**
767 * @internal
768 */
769
770function isNode(maybeNode) {
771 return maybeNode != null && typeof maybeNode.kind === 'string';
772}
773/**
774 * The list of all possible AST node types.
775 */
776
777/**
778 * A visitor is provided to visit, it contains the collection of
779 * relevant functions to be called during the visitor's traversal.
780 */
781
782var QueryDocumentKeys = {
783 Name: [],
784 Document: ['definitions'],
785 OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
786 VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],
787 Variable: ['name'],
788 SelectionSet: ['selections'],
789 Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
790 Argument: ['name', 'value'],
791 FragmentSpread: ['name', 'directives'],
792 InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
793 FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed
794 // or removed in the future.
795 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'],
796 IntValue: [],
797 FloatValue: [],
798 StringValue: [],
799 BooleanValue: [],
800 NullValue: [],
801 EnumValue: [],
802 ListValue: ['values'],
803 ObjectValue: ['fields'],
804 ObjectField: ['name', 'value'],
805 Directive: ['name', 'arguments'],
806 NamedType: ['name'],
807 ListType: ['type'],
808 NonNullType: ['type'],
809 SchemaDefinition: ['description', 'directives', 'operationTypes'],
810 OperationTypeDefinition: ['type'],
811 ScalarTypeDefinition: ['description', 'name', 'directives'],
812 ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
813 FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],
814 InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'],
815 InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
816 UnionTypeDefinition: ['description', 'name', 'directives', 'types'],
817 EnumTypeDefinition: ['description', 'name', 'directives', 'values'],
818 EnumValueDefinition: ['description', 'name', 'directives'],
819 InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],
820 DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],
821 SchemaExtension: ['directives', 'operationTypes'],
822 ScalarTypeExtension: ['name', 'directives'],
823 ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
824 InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
825 UnionTypeExtension: ['name', 'directives', 'types'],
826 EnumTypeExtension: ['name', 'directives', 'values'],
827 InputObjectTypeExtension: ['name', 'directives', 'fields']
828};
829var BREAK = Object.freeze({});
830/**
831 * visit() will walk through an AST using a depth-first traversal, calling
832 * the visitor's enter function at each node in the traversal, and calling the
833 * leave function after visiting that node and all of its child nodes.
834 *
835 * By returning different values from the enter and leave functions, the
836 * behavior of the visitor can be altered, including skipping over a sub-tree of
837 * the AST (by returning false), editing the AST by returning a value or null
838 * to remove the value, or to stop the whole traversal by returning BREAK.
839 *
840 * When using visit() to edit an AST, the original AST will not be modified, and
841 * a new version of the AST with the changes applied will be returned from the
842 * visit function.
843 *
844 * const editedAST = visit(ast, {
845 * enter(node, key, parent, path, ancestors) {
846 * // @return
847 * // undefined: no action
848 * // false: skip visiting this node
849 * // visitor.BREAK: stop visiting altogether
850 * // null: delete this node
851 * // any value: replace this node with the returned value
852 * },
853 * leave(node, key, parent, path, ancestors) {
854 * // @return
855 * // undefined: no action
856 * // false: no action
857 * // visitor.BREAK: stop visiting altogether
858 * // null: delete this node
859 * // any value: replace this node with the returned value
860 * }
861 * });
862 *
863 * Alternatively to providing enter() and leave() functions, a visitor can
864 * instead provide functions named the same as the kinds of AST nodes, or
865 * enter/leave visitors at a named key, leading to four permutations of the
866 * visitor API:
867 *
868 * 1) Named visitors triggered when entering a node of a specific kind.
869 *
870 * visit(ast, {
871 * Kind(node) {
872 * // enter the "Kind" node
873 * }
874 * })
875 *
876 * 2) Named visitors that trigger upon entering and leaving a node of
877 * a specific kind.
878 *
879 * visit(ast, {
880 * Kind: {
881 * enter(node) {
882 * // enter the "Kind" node
883 * }
884 * leave(node) {
885 * // leave the "Kind" node
886 * }
887 * }
888 * })
889 *
890 * 3) Generic visitors that trigger upon entering and leaving any node.
891 *
892 * visit(ast, {
893 * enter(node) {
894 * // enter any node
895 * },
896 * leave(node) {
897 * // leave any node
898 * }
899 * })
900 *
901 * 4) Parallel visitors for entering and leaving nodes of a specific kind.
902 *
903 * visit(ast, {
904 * enter: {
905 * Kind(node) {
906 * // enter the "Kind" node
907 * }
908 * },
909 * leave: {
910 * Kind(node) {
911 * // leave the "Kind" node
912 * }
913 * }
914 * })
915 */
916
917function visit(root, visitor) {
918 var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys;
919
920 /* eslint-disable no-undef-init */
921 var stack = undefined;
922 var inArray = Array.isArray(root);
923 var keys = [root];
924 var index = -1;
925 var edits = [];
926 var node = undefined;
927 var key = undefined;
928 var parent = undefined;
929 var path = [];
930 var ancestors = [];
931 var newRoot = root;
932 /* eslint-enable no-undef-init */
933
934 do {
935 index++;
936 var isLeaving = index === keys.length;
937 var isEdited = isLeaving && edits.length !== 0;
938
939 if (isLeaving) {
940 key = ancestors.length === 0 ? undefined : path[path.length - 1];
941 node = parent;
942 parent = ancestors.pop();
943
944 if (isEdited) {
945 if (inArray) {
946 node = node.slice();
947 } else {
948 var clone = {};
949
950 for (var _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) {
951 var k = _Object$keys2[_i2];
952 clone[k] = node[k];
953 }
954
955 node = clone;
956 }
957
958 var editOffset = 0;
959
960 for (var ii = 0; ii < edits.length; ii++) {
961 var editKey = edits[ii][0];
962 var editValue = edits[ii][1];
963
964 if (inArray) {
965 editKey -= editOffset;
966 }
967
968 if (inArray && editValue === null) {
969 node.splice(editKey, 1);
970 editOffset++;
971 } else {
972 node[editKey] = editValue;
973 }
974 }
975 }
976
977 index = stack.index;
978 keys = stack.keys;
979 edits = stack.edits;
980 inArray = stack.inArray;
981 stack = stack.prev;
982 } else {
983 key = parent ? inArray ? index : keys[index] : undefined;
984 node = parent ? parent[key] : newRoot;
985
986 if (node === null || node === undefined) {
987 continue;
988 }
989
990 if (parent) {
991 path.push(key);
992 }
993 }
994
995 var result = void 0;
996
997 if (!Array.isArray(node)) {
998 if (!isNode(node)) {
999 throw new Error("Invalid AST Node: ".concat(inspect(node), "."));
1000 }
1001
1002 var visitFn = getVisitFn(visitor, node.kind, isLeaving);
1003
1004 if (visitFn) {
1005 result = visitFn.call(visitor, node, key, parent, path, ancestors);
1006
1007 if (result === BREAK) {
1008 break;
1009 }
1010
1011 if (result === false) {
1012 if (!isLeaving) {
1013 path.pop();
1014 continue;
1015 }
1016 } else if (result !== undefined) {
1017 edits.push([key, result]);
1018
1019 if (!isLeaving) {
1020 if (isNode(result)) {
1021 node = result;
1022 } else {
1023 path.pop();
1024 continue;
1025 }
1026 }
1027 }
1028 }
1029 }
1030
1031 if (result === undefined && isEdited) {
1032 edits.push([key, node]);
1033 }
1034
1035 if (isLeaving) {
1036 path.pop();
1037 } else {
1038 var _visitorKeys$node$kin;
1039
1040 stack = {
1041 inArray: inArray,
1042 index: index,
1043 keys: keys,
1044 edits: edits,
1045 prev: stack
1046 };
1047 inArray = Array.isArray(node);
1048 keys = inArray ? node : (_visitorKeys$node$kin = visitorKeys[node.kind]) !== null && _visitorKeys$node$kin !== void 0 ? _visitorKeys$node$kin : [];
1049 index = -1;
1050 edits = [];
1051
1052 if (parent) {
1053 ancestors.push(parent);
1054 }
1055
1056 parent = node;
1057 }
1058 } while (stack !== undefined);
1059
1060 if (edits.length !== 0) {
1061 newRoot = edits[edits.length - 1][1];
1062 }
1063
1064 return newRoot;
1065}
1066/**
1067 * Given a visitor instance, if it is leaving or not, and a node kind, return
1068 * the function the visitor runtime should call.
1069 */
1070
1071function getVisitFn(visitor, kind, isLeaving) {
1072 var kindVisitor = visitor[kind];
1073
1074 if (kindVisitor) {
1075 if (!isLeaving && typeof kindVisitor === 'function') {
1076 // { Kind() {} }
1077 return kindVisitor;
1078 }
1079
1080 var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
1081
1082 if (typeof kindSpecificVisitor === 'function') {
1083 // { Kind: { enter() {}, leave() {} } }
1084 return kindSpecificVisitor;
1085 }
1086 } else {
1087 var specificVisitor = isLeaving ? visitor.leave : visitor.enter;
1088
1089 if (specificVisitor) {
1090 if (typeof specificVisitor === 'function') {
1091 // { enter() {}, leave() {} }
1092 return specificVisitor;
1093 }
1094
1095 var specificKindVisitor = specificVisitor[kind];
1096
1097 if (typeof specificKindVisitor === 'function') {
1098 // { enter: { Kind() {} }, leave: { Kind() {} } }
1099 return specificKindVisitor;
1100 }
1101 }
1102 }
1103}
1104
1105/**
1106 * Produces the value of a block string from its parsed raw value, similar to
1107 * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.
1108 *
1109 * This implements the GraphQL spec's BlockStringValue() static algorithm.
1110 *
1111 * @internal
1112 */
1113/**
1114 * Print a block string in the indented block form by adding a leading and
1115 * trailing blank line. However, if a block string starts with whitespace and is
1116 * a single-line, adding a leading blank line would strip that whitespace.
1117 *
1118 * @internal
1119 */
1120
1121function printBlockString(value) {
1122 var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
1123 var preferMultipleLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1124 var isSingleLine = value.indexOf('\n') === -1;
1125 var hasLeadingSpace = value[0] === ' ' || value[0] === '\t';
1126 var hasTrailingQuote = value[value.length - 1] === '"';
1127 var hasTrailingSlash = value[value.length - 1] === '\\';
1128 var printAsMultipleLines = !isSingleLine || hasTrailingQuote || hasTrailingSlash || preferMultipleLines;
1129 var result = ''; // Format a multi-line block quote to account for leading space.
1130
1131 if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) {
1132 result += '\n' + indentation;
1133 }
1134
1135 result += indentation ? value.replace(/\n/g, '\n' + indentation) : value;
1136
1137 if (printAsMultipleLines) {
1138 result += '\n';
1139 }
1140
1141 return '"""' + result.replace(/"""/g, '\\"""') + '"""';
1142}
1143
1144/**
1145 * Converts an AST into a string, using one set of reasonable
1146 * formatting rules.
1147 */
1148
1149function print(ast) {
1150 return visit(ast, {
1151 leave: printDocASTReducer
1152 });
1153}
1154var MAX_LINE_LENGTH = 80; // TODO: provide better type coverage in future
1155
1156var printDocASTReducer = {
1157 Name: function Name(node) {
1158 return node.value;
1159 },
1160 Variable: function Variable(node) {
1161 return '$' + node.name;
1162 },
1163 // Document
1164 Document: function Document(node) {
1165 return join(node.definitions, '\n\n') + '\n';
1166 },
1167 OperationDefinition: function OperationDefinition(node) {
1168 var op = node.operation;
1169 var name = node.name;
1170 var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
1171 var directives = join(node.directives, ' ');
1172 var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use
1173 // the query short form.
1174
1175 return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' ');
1176 },
1177 VariableDefinition: function VariableDefinition(_ref) {
1178 var variable = _ref.variable,
1179 type = _ref.type,
1180 defaultValue = _ref.defaultValue,
1181 directives = _ref.directives;
1182 return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' '));
1183 },
1184 SelectionSet: function SelectionSet(_ref2) {
1185 var selections = _ref2.selections;
1186 return block(selections);
1187 },
1188 Field: function Field(_ref3) {
1189 var alias = _ref3.alias,
1190 name = _ref3.name,
1191 args = _ref3.arguments,
1192 directives = _ref3.directives,
1193 selectionSet = _ref3.selectionSet;
1194 var prefix = wrap('', alias, ': ') + name;
1195 var argsLine = prefix + wrap('(', join(args, ', '), ')');
1196
1197 if (argsLine.length > MAX_LINE_LENGTH) {
1198 argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)');
1199 }
1200
1201 return join([argsLine, join(directives, ' '), selectionSet], ' ');
1202 },
1203 Argument: function Argument(_ref4) {
1204 var name = _ref4.name,
1205 value = _ref4.value;
1206 return name + ': ' + value;
1207 },
1208 // Fragments
1209 FragmentSpread: function FragmentSpread(_ref5) {
1210 var name = _ref5.name,
1211 directives = _ref5.directives;
1212 return '...' + name + wrap(' ', join(directives, ' '));
1213 },
1214 InlineFragment: function InlineFragment(_ref6) {
1215 var typeCondition = _ref6.typeCondition,
1216 directives = _ref6.directives,
1217 selectionSet = _ref6.selectionSet;
1218 return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ');
1219 },
1220 FragmentDefinition: function FragmentDefinition(_ref7) {
1221 var name = _ref7.name,
1222 typeCondition = _ref7.typeCondition,
1223 variableDefinitions = _ref7.variableDefinitions,
1224 directives = _ref7.directives,
1225 selectionSet = _ref7.selectionSet;
1226 return (// Note: fragment variable definitions are experimental and may be changed
1227 // or removed in the future.
1228 "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet
1229 );
1230 },
1231 // Value
1232 IntValue: function IntValue(_ref8) {
1233 var value = _ref8.value;
1234 return value;
1235 },
1236 FloatValue: function FloatValue(_ref9) {
1237 var value = _ref9.value;
1238 return value;
1239 },
1240 StringValue: function StringValue(_ref10, key) {
1241 var value = _ref10.value,
1242 isBlockString = _ref10.block;
1243 return isBlockString ? printBlockString(value, key === 'description' ? '' : ' ') : JSON.stringify(value);
1244 },
1245 BooleanValue: function BooleanValue(_ref11) {
1246 var value = _ref11.value;
1247 return value ? 'true' : 'false';
1248 },
1249 NullValue: function NullValue() {
1250 return 'null';
1251 },
1252 EnumValue: function EnumValue(_ref12) {
1253 var value = _ref12.value;
1254 return value;
1255 },
1256 ListValue: function ListValue(_ref13) {
1257 var values = _ref13.values;
1258 return '[' + join(values, ', ') + ']';
1259 },
1260 ObjectValue: function ObjectValue(_ref14) {
1261 var fields = _ref14.fields;
1262 return '{' + join(fields, ', ') + '}';
1263 },
1264 ObjectField: function ObjectField(_ref15) {
1265 var name = _ref15.name,
1266 value = _ref15.value;
1267 return name + ': ' + value;
1268 },
1269 // Directive
1270 Directive: function Directive(_ref16) {
1271 var name = _ref16.name,
1272 args = _ref16.arguments;
1273 return '@' + name + wrap('(', join(args, ', '), ')');
1274 },
1275 // Type
1276 NamedType: function NamedType(_ref17) {
1277 var name = _ref17.name;
1278 return name;
1279 },
1280 ListType: function ListType(_ref18) {
1281 var type = _ref18.type;
1282 return '[' + type + ']';
1283 },
1284 NonNullType: function NonNullType(_ref19) {
1285 var type = _ref19.type;
1286 return type + '!';
1287 },
1288 // Type System Definitions
1289 SchemaDefinition: addDescription(function (_ref20) {
1290 var directives = _ref20.directives,
1291 operationTypes = _ref20.operationTypes;
1292 return join(['schema', join(directives, ' '), block(operationTypes)], ' ');
1293 }),
1294 OperationTypeDefinition: function OperationTypeDefinition(_ref21) {
1295 var operation = _ref21.operation,
1296 type = _ref21.type;
1297 return operation + ': ' + type;
1298 },
1299 ScalarTypeDefinition: addDescription(function (_ref22) {
1300 var name = _ref22.name,
1301 directives = _ref22.directives;
1302 return join(['scalar', name, join(directives, ' ')], ' ');
1303 }),
1304 ObjectTypeDefinition: addDescription(function (_ref23) {
1305 var name = _ref23.name,
1306 interfaces = _ref23.interfaces,
1307 directives = _ref23.directives,
1308 fields = _ref23.fields;
1309 return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
1310 }),
1311 FieldDefinition: addDescription(function (_ref24) {
1312 var name = _ref24.name,
1313 args = _ref24.arguments,
1314 type = _ref24.type,
1315 directives = _ref24.directives;
1316 return name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' '));
1317 }),
1318 InputValueDefinition: addDescription(function (_ref25) {
1319 var name = _ref25.name,
1320 type = _ref25.type,
1321 defaultValue = _ref25.defaultValue,
1322 directives = _ref25.directives;
1323 return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ');
1324 }),
1325 InterfaceTypeDefinition: addDescription(function (_ref26) {
1326 var name = _ref26.name,
1327 interfaces = _ref26.interfaces,
1328 directives = _ref26.directives,
1329 fields = _ref26.fields;
1330 return join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
1331 }),
1332 UnionTypeDefinition: addDescription(function (_ref27) {
1333 var name = _ref27.name,
1334 directives = _ref27.directives,
1335 types = _ref27.types;
1336 return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
1337 }),
1338 EnumTypeDefinition: addDescription(function (_ref28) {
1339 var name = _ref28.name,
1340 directives = _ref28.directives,
1341 values = _ref28.values;
1342 return join(['enum', name, join(directives, ' '), block(values)], ' ');
1343 }),
1344 EnumValueDefinition: addDescription(function (_ref29) {
1345 var name = _ref29.name,
1346 directives = _ref29.directives;
1347 return join([name, join(directives, ' ')], ' ');
1348 }),
1349 InputObjectTypeDefinition: addDescription(function (_ref30) {
1350 var name = _ref30.name,
1351 directives = _ref30.directives,
1352 fields = _ref30.fields;
1353 return join(['input', name, join(directives, ' '), block(fields)], ' ');
1354 }),
1355 DirectiveDefinition: addDescription(function (_ref31) {
1356 var name = _ref31.name,
1357 args = _ref31.arguments,
1358 repeatable = _ref31.repeatable,
1359 locations = _ref31.locations;
1360 return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | ');
1361 }),
1362 SchemaExtension: function SchemaExtension(_ref32) {
1363 var directives = _ref32.directives,
1364 operationTypes = _ref32.operationTypes;
1365 return join(['extend schema', join(directives, ' '), block(operationTypes)], ' ');
1366 },
1367 ScalarTypeExtension: function ScalarTypeExtension(_ref33) {
1368 var name = _ref33.name,
1369 directives = _ref33.directives;
1370 return join(['extend scalar', name, join(directives, ' ')], ' ');
1371 },
1372 ObjectTypeExtension: function ObjectTypeExtension(_ref34) {
1373 var name = _ref34.name,
1374 interfaces = _ref34.interfaces,
1375 directives = _ref34.directives,
1376 fields = _ref34.fields;
1377 return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
1378 },
1379 InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) {
1380 var name = _ref35.name,
1381 interfaces = _ref35.interfaces,
1382 directives = _ref35.directives,
1383 fields = _ref35.fields;
1384 return join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
1385 },
1386 UnionTypeExtension: function UnionTypeExtension(_ref36) {
1387 var name = _ref36.name,
1388 directives = _ref36.directives,
1389 types = _ref36.types;
1390 return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
1391 },
1392 EnumTypeExtension: function EnumTypeExtension(_ref37) {
1393 var name = _ref37.name,
1394 directives = _ref37.directives,
1395 values = _ref37.values;
1396 return join(['extend enum', name, join(directives, ' '), block(values)], ' ');
1397 },
1398 InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) {
1399 var name = _ref38.name,
1400 directives = _ref38.directives,
1401 fields = _ref38.fields;
1402 return join(['extend input', name, join(directives, ' '), block(fields)], ' ');
1403 }
1404};
1405
1406function addDescription(cb) {
1407 return function (node) {
1408 return join([node.description, cb(node)], '\n');
1409 };
1410}
1411/**
1412 * Given maybeArray, print an empty string if it is null or empty, otherwise
1413 * print all items together separated by separator if provided
1414 */
1415
1416
1417function join(maybeArray) {
1418 var _maybeArray$filter$jo;
1419
1420 var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
1421 return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(function (x) {
1422 return x;
1423 }).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : '';
1424}
1425/**
1426 * Given array, print each item on its own line, wrapped in an
1427 * indented "{ }" block.
1428 */
1429
1430
1431function block(array) {
1432 return wrap('{\n', indent(join(array, '\n')), '\n}');
1433}
1434/**
1435 * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string.
1436 */
1437
1438
1439function wrap(start, maybeString) {
1440 var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
1441 return maybeString != null && maybeString !== '' ? start + maybeString + end : '';
1442}
1443
1444function indent(str) {
1445 return wrap(' ', str.replace(/\n/g, '\n '));
1446}
1447
1448function isMultiline(str) {
1449 return str.indexOf('\n') !== -1;
1450}
1451
1452function hasMultilineItems(maybeArray) {
1453 return maybeArray != null && maybeArray.some(isMultiline);
1454}
1455
1456/* eslint-disable no-redeclare */
1457// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441
1458var objectEntries = Object.entries || function (obj) {
1459 return Object.keys(obj).map(function (key) {
1460 return [key, obj[key]];
1461 });
1462};
1463
1464/**
1465 * Creates an object map with the same keys as `map` and values generated by
1466 * running each value of `map` thru `fn`.
1467 */
1468function mapValue(map, fn) {
1469 var result = Object.create(null);
1470
1471 for (var _i2 = 0, _objectEntries2 = objectEntries(map); _i2 < _objectEntries2.length; _i2++) {
1472 var _ref2 = _objectEntries2[_i2];
1473 var _key = _ref2[0];
1474 var _value = _ref2[1];
1475 result[_key] = fn(_value, _key);
1476 }
1477
1478 return result;
1479}
1480
1481function toObjMap(obj) {
1482 /* eslint-enable no-redeclare */
1483 if (Object.getPrototypeOf(obj) === null) {
1484 return obj;
1485 }
1486
1487 var map = Object.create(null);
1488
1489 for (var _i2 = 0, _objectEntries2 = objectEntries(obj); _i2 < _objectEntries2.length; _i2++) {
1490 var _ref2 = _objectEntries2[_i2];
1491 var key = _ref2[0];
1492 var value = _ref2[1];
1493 map[key] = value;
1494 }
1495
1496 return map;
1497}
1498
1499function devAssert(condition, message) {
1500 var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')
1501
1502 if (!booleanCondition) {
1503 throw new Error(message);
1504 }
1505}
1506
1507/**
1508 * Creates a keyed JS object from an array, given a function to produce the keys
1509 * and a function to produce the values from each item in the array.
1510 *
1511 * const phoneBook = [
1512 * { name: 'Jon', num: '555-1234' },
1513 * { name: 'Jenny', num: '867-5309' }
1514 * ]
1515 *
1516 * // { Jon: '555-1234', Jenny: '867-5309' }
1517 * const phonesByName = keyValMap(
1518 * phoneBook,
1519 * entry => entry.name,
1520 * entry => entry.num
1521 * )
1522 *
1523 */
1524function keyValMap(list, keyFn, valFn) {
1525 return list.reduce(function (map, item) {
1526 map[keyFn(item)] = valFn(item);
1527 return map;
1528 }, Object.create(null));
1529}
1530
1531/**
1532 * A replacement for instanceof which includes an error warning when multi-realm
1533 * constructors are detected.
1534 */
1535// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
1536// See: https://webpack.js.org/guides/production/
1537const instanceOf = process.env.NODE_ENV === 'production' ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
1538// eslint-disable-next-line no-shadow
1539function instanceOf(value, constructor) {
1540 return value instanceof constructor;
1541} : // eslint-disable-next-line no-shadow
1542function instanceOf(value, constructor) {
1543 if (value instanceof constructor) {
1544 return true;
1545 }
1546
1547 if (value) {
1548 var valueClass = value.constructor;
1549 var className = constructor.name;
1550
1551 if (className && valueClass && valueClass.name === className) {
1552 throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results."));
1553 }
1554 }
1555
1556 return false;
1557};
1558
1559var MAX_SUGGESTIONS = 5;
1560/**
1561 * Given [ A, B, C ] return ' Did you mean A, B, or C?'.
1562 */
1563
1564// eslint-disable-next-line no-redeclare
1565function didYouMean(firstArg, secondArg) {
1566 var _ref = typeof firstArg === 'string' ? [firstArg, secondArg] : [undefined, firstArg],
1567 subMessage = _ref[0],
1568 suggestionsArg = _ref[1];
1569
1570 var message = ' Did you mean ';
1571
1572 if (subMessage) {
1573 message += subMessage + ' ';
1574 }
1575
1576 var suggestions = suggestionsArg.map(function (x) {
1577 return "\"".concat(x, "\"");
1578 });
1579
1580 switch (suggestions.length) {
1581 case 0:
1582 return '';
1583
1584 case 1:
1585 return message + suggestions[0] + '?';
1586
1587 case 2:
1588 return message + suggestions[0] + ' or ' + suggestions[1] + '?';
1589 }
1590
1591 var selected = suggestions.slice(0, MAX_SUGGESTIONS);
1592 var lastItem = selected.pop();
1593 return message + selected.join(', ') + ', or ' + lastItem + '?';
1594}
1595
1596/**
1597 * Returns the first argument it receives.
1598 */
1599function identityFunc(x) {
1600 return x;
1601}
1602
1603/**
1604 * Returns a number indicating whether a reference string comes before, or after,
1605 * or is the same as the given string in natural sort order.
1606 *
1607 * See: https://en.wikipedia.org/wiki/Natural_sort_order
1608 *
1609 */
1610function naturalCompare(aStr, bStr) {
1611 var aIdx = 0;
1612 var bIdx = 0;
1613
1614 while (aIdx < aStr.length && bIdx < bStr.length) {
1615 var aChar = aStr.charCodeAt(aIdx);
1616 var bChar = bStr.charCodeAt(bIdx);
1617
1618 if (isDigit(aChar) && isDigit(bChar)) {
1619 var aNum = 0;
1620
1621 do {
1622 ++aIdx;
1623 aNum = aNum * 10 + aChar - DIGIT_0;
1624 aChar = aStr.charCodeAt(aIdx);
1625 } while (isDigit(aChar) && aNum > 0);
1626
1627 var bNum = 0;
1628
1629 do {
1630 ++bIdx;
1631 bNum = bNum * 10 + bChar - DIGIT_0;
1632 bChar = bStr.charCodeAt(bIdx);
1633 } while (isDigit(bChar) && bNum > 0);
1634
1635 if (aNum < bNum) {
1636 return -1;
1637 }
1638
1639 if (aNum > bNum) {
1640 return 1;
1641 }
1642 } else {
1643 if (aChar < bChar) {
1644 return -1;
1645 }
1646
1647 if (aChar > bChar) {
1648 return 1;
1649 }
1650
1651 ++aIdx;
1652 ++bIdx;
1653 }
1654 }
1655
1656 return aStr.length - bStr.length;
1657}
1658var DIGIT_0 = 48;
1659var DIGIT_9 = 57;
1660
1661function isDigit(code) {
1662 return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9;
1663}
1664
1665/**
1666 * Given an invalid input string and a list of valid options, returns a filtered
1667 * list of valid options sorted based on their similarity with the input.
1668 */
1669
1670function suggestionList(input, options) {
1671 var optionsByDistance = Object.create(null);
1672 var lexicalDistance = new LexicalDistance(input);
1673 var threshold = Math.floor(input.length * 0.4) + 1;
1674
1675 for (var _i2 = 0; _i2 < options.length; _i2++) {
1676 var option = options[_i2];
1677 var distance = lexicalDistance.measure(option, threshold);
1678
1679 if (distance !== undefined) {
1680 optionsByDistance[option] = distance;
1681 }
1682 }
1683
1684 return Object.keys(optionsByDistance).sort(function (a, b) {
1685 var distanceDiff = optionsByDistance[a] - optionsByDistance[b];
1686 return distanceDiff !== 0 ? distanceDiff : naturalCompare(a, b);
1687 });
1688}
1689/**
1690 * Computes the lexical distance between strings A and B.
1691 *
1692 * The "distance" between two strings is given by counting the minimum number
1693 * of edits needed to transform string A into string B. An edit can be an
1694 * insertion, deletion, or substitution of a single character, or a swap of two
1695 * adjacent characters.
1696 *
1697 * Includes a custom alteration from Damerau-Levenshtein to treat case changes
1698 * as a single edit which helps identify mis-cased values with an edit distance
1699 * of 1.
1700 *
1701 * This distance can be useful for detecting typos in input or sorting
1702 */
1703
1704var LexicalDistance = /*#__PURE__*/function () {
1705 function LexicalDistance(input) {
1706 this._input = input;
1707 this._inputLowerCase = input.toLowerCase();
1708 this._inputArray = stringToArray(this._inputLowerCase);
1709 this._rows = [new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0)];
1710 }
1711
1712 var _proto = LexicalDistance.prototype;
1713
1714 _proto.measure = function measure(option, threshold) {
1715 if (this._input === option) {
1716 return 0;
1717 }
1718
1719 var optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit
1720
1721 if (this._inputLowerCase === optionLowerCase) {
1722 return 1;
1723 }
1724
1725 var a = stringToArray(optionLowerCase);
1726 var b = this._inputArray;
1727
1728 if (a.length < b.length) {
1729 var tmp = a;
1730 a = b;
1731 b = tmp;
1732 }
1733
1734 var aLength = a.length;
1735 var bLength = b.length;
1736
1737 if (aLength - bLength > threshold) {
1738 return undefined;
1739 }
1740
1741 var rows = this._rows;
1742
1743 for (var j = 0; j <= bLength; j++) {
1744 rows[0][j] = j;
1745 }
1746
1747 for (var i = 1; i <= aLength; i++) {
1748 var upRow = rows[(i - 1) % 3];
1749 var currentRow = rows[i % 3];
1750 var smallestCell = currentRow[0] = i;
1751
1752 for (var _j = 1; _j <= bLength; _j++) {
1753 var cost = a[i - 1] === b[_j - 1] ? 0 : 1;
1754 var currentCell = Math.min(upRow[_j] + 1, // delete
1755 currentRow[_j - 1] + 1, // insert
1756 upRow[_j - 1] + cost // substitute
1757 );
1758
1759 if (i > 1 && _j > 1 && a[i - 1] === b[_j - 2] && a[i - 2] === b[_j - 1]) {
1760 // transposition
1761 var doubleDiagonalCell = rows[(i - 2) % 3][_j - 2];
1762 currentCell = Math.min(currentCell, doubleDiagonalCell + 1);
1763 }
1764
1765 if (currentCell < smallestCell) {
1766 smallestCell = currentCell;
1767 }
1768
1769 currentRow[_j] = currentCell;
1770 } // Early exit, since distance can't go smaller than smallest element of the previous row.
1771
1772
1773 if (smallestCell > threshold) {
1774 return undefined;
1775 }
1776 }
1777
1778 var distance = rows[aLength % 3][bLength];
1779 return distance <= threshold ? distance : undefined;
1780 };
1781
1782 return LexicalDistance;
1783}();
1784
1785function stringToArray(str) {
1786 var strLength = str.length;
1787 var array = new Array(strLength);
1788
1789 for (var i = 0; i < strLength; ++i) {
1790 array[i] = str.charCodeAt(i);
1791 }
1792
1793 return array;
1794}
1795
1796/**
1797 * Produces a JavaScript value given a GraphQL Value AST.
1798 *
1799 * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value
1800 * will reflect the provided GraphQL value AST.
1801 *
1802 * | GraphQL Value | JavaScript Value |
1803 * | -------------------- | ---------------- |
1804 * | Input Object | Object |
1805 * | List | Array |
1806 * | Boolean | Boolean |
1807 * | String / Enum | String |
1808 * | Int / Float | Number |
1809 * | Null | null |
1810 *
1811 */
1812function valueFromASTUntyped(valueNode, variables) {
1813 switch (valueNode.kind) {
1814 case Kind.NULL:
1815 return null;
1816
1817 case Kind.INT:
1818 return parseInt(valueNode.value, 10);
1819
1820 case Kind.FLOAT:
1821 return parseFloat(valueNode.value);
1822
1823 case Kind.STRING:
1824 case Kind.ENUM:
1825 case Kind.BOOLEAN:
1826 return valueNode.value;
1827
1828 case Kind.LIST:
1829 return valueNode.values.map(function (node) {
1830 return valueFromASTUntyped(node, variables);
1831 });
1832
1833 case Kind.OBJECT:
1834 return keyValMap(valueNode.fields, function (field) {
1835 return field.name.value;
1836 }, function (field) {
1837 return valueFromASTUntyped(field.value, variables);
1838 });
1839
1840 case Kind.VARIABLE:
1841 return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value];
1842 } // istanbul ignore next (Not reachable. All possible value nodes have been considered)
1843
1844
1845 invariant(0, 'Unexpected value node: ' + inspect(valueNode));
1846}
1847
1848function _defineProperties$1(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
1849
1850function _createClass$1(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); return Constructor; }
1851function isType(type) {
1852 return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type);
1853}
1854function assertType(type) {
1855 if (!isType(type)) {
1856 throw new Error("Expected ".concat(inspect(type), " to be a GraphQL type."));
1857 }
1858
1859 return type;
1860}
1861/**
1862 * There are predicates for each kind of GraphQL type.
1863 */
1864
1865// eslint-disable-next-line no-redeclare
1866function isScalarType(type) {
1867 return instanceOf(type, GraphQLScalarType);
1868}
1869// eslint-disable-next-line no-redeclare
1870function isObjectType(type) {
1871 return instanceOf(type, GraphQLObjectType);
1872}
1873// eslint-disable-next-line no-redeclare
1874function isInterfaceType(type) {
1875 return instanceOf(type, GraphQLInterfaceType);
1876}
1877// eslint-disable-next-line no-redeclare
1878function isUnionType(type) {
1879 return instanceOf(type, GraphQLUnionType);
1880}
1881// eslint-disable-next-line no-redeclare
1882function isEnumType(type) {
1883 return instanceOf(type, GraphQLEnumType);
1884}
1885// eslint-disable-next-line no-redeclare
1886function isInputObjectType(type) {
1887 return instanceOf(type, GraphQLInputObjectType);
1888}
1889// eslint-disable-next-line no-redeclare
1890function isListType(type) {
1891 return instanceOf(type, GraphQLList);
1892}
1893// eslint-disable-next-line no-redeclare
1894function isNonNullType(type) {
1895 return instanceOf(type, GraphQLNonNull);
1896}
1897/**
1898 * These types may describe types which may be leaf values.
1899 */
1900
1901function isLeafType(type) {
1902 return isScalarType(type) || isEnumType(type);
1903}
1904/**
1905 * List Type Wrapper
1906 *
1907 * A list is a wrapping type which points to another type.
1908 * Lists are often created within the context of defining the fields of
1909 * an object type.
1910 *
1911 * Example:
1912 *
1913 * const PersonType = new GraphQLObjectType({
1914 * name: 'Person',
1915 * fields: () => ({
1916 * parents: { type: new GraphQLList(PersonType) },
1917 * children: { type: new GraphQLList(PersonType) },
1918 * })
1919 * })
1920 *
1921 */
1922// FIXME: workaround to fix issue with Babel parser
1923
1924/* ::
1925declare class GraphQLList<+T: GraphQLType> {
1926 +ofType: T;
1927 static <T>(ofType: T): GraphQLList<T>;
1928 // Note: constructors cannot be used for covariant types. Drop the "new".
1929 constructor(ofType: GraphQLType): void;
1930}
1931*/
1932
1933function GraphQLList(ofType) {
1934 // istanbul ignore else (to be removed in v16.0.0)
1935 if (this instanceof GraphQLList) {
1936 this.ofType = assertType(ofType);
1937 } else {
1938 return new GraphQLList(ofType);
1939 }
1940} // Need to cast through any to alter the prototype.
1941
1942GraphQLList.prototype.toString = function toString() {
1943 return '[' + String(this.ofType) + ']';
1944};
1945
1946GraphQLList.prototype.toJSON = function toJSON() {
1947 return this.toString();
1948};
1949
1950Object.defineProperty(GraphQLList.prototype, SYMBOL_TO_STRING_TAG, {
1951 get: function get() {
1952 return 'GraphQLList';
1953 }
1954}); // Print a simplified form when appearing in `inspect` and `util.inspect`.
1955
1956defineInspect(GraphQLList);
1957/**
1958 * Non-Null Type Wrapper
1959 *
1960 * A non-null is a wrapping type which points to another type.
1961 * Non-null types enforce that their values are never null and can ensure
1962 * an error is raised if this ever occurs during a request. It is useful for
1963 * fields which you can make a strong guarantee on non-nullability, for example
1964 * usually the id field of a database row will never be null.
1965 *
1966 * Example:
1967 *
1968 * const RowType = new GraphQLObjectType({
1969 * name: 'Row',
1970 * fields: () => ({
1971 * id: { type: new GraphQLNonNull(GraphQLString) },
1972 * })
1973 * })
1974 *
1975 * Note: the enforcement of non-nullability occurs within the executor.
1976 */
1977// FIXME: workaround to fix issue with Babel parser
1978
1979/* ::
1980declare class GraphQLNonNull<+T: GraphQLNullableType> {
1981 +ofType: T;
1982 static <T>(ofType: T): GraphQLNonNull<T>;
1983 // Note: constructors cannot be used for covariant types. Drop the "new".
1984 constructor(ofType: GraphQLType): void;
1985}
1986*/
1987
1988function GraphQLNonNull(ofType) {
1989 // istanbul ignore else (to be removed in v16.0.0)
1990 if (this instanceof GraphQLNonNull) {
1991 this.ofType = assertNullableType(ofType);
1992 } else {
1993 return new GraphQLNonNull(ofType);
1994 }
1995} // Need to cast through any to alter the prototype.
1996
1997GraphQLNonNull.prototype.toString = function toString() {
1998 return String(this.ofType) + '!';
1999};
2000
2001GraphQLNonNull.prototype.toJSON = function toJSON() {
2002 return this.toString();
2003};
2004
2005Object.defineProperty(GraphQLNonNull.prototype, SYMBOL_TO_STRING_TAG, {
2006 get: function get() {
2007 return 'GraphQLNonNull';
2008 }
2009}); // Print a simplified form when appearing in `inspect` and `util.inspect`.
2010
2011defineInspect(GraphQLNonNull);
2012/**
2013 * These types can all accept null as a value.
2014 */
2015
2016function isNullableType(type) {
2017 return isType(type) && !isNonNullType(type);
2018}
2019function assertNullableType(type) {
2020 if (!isNullableType(type)) {
2021 throw new Error("Expected ".concat(inspect(type), " to be a GraphQL nullable type."));
2022 }
2023
2024 return type;
2025}
2026/**
2027 * Used while defining GraphQL types to allow for circular references in
2028 * otherwise immutable type definitions.
2029 */
2030
2031function resolveThunk(thunk) {
2032 // $FlowFixMe[incompatible-use]
2033 return typeof thunk === 'function' ? thunk() : thunk;
2034}
2035
2036function undefineIfEmpty(arr) {
2037 return arr && arr.length > 0 ? arr : undefined;
2038}
2039/**
2040 * Scalar Type Definition
2041 *
2042 * The leaf values of any request and input values to arguments are
2043 * Scalars (or Enums) and are defined with a name and a series of functions
2044 * used to parse input from ast or variables and to ensure validity.
2045 *
2046 * If a type's serialize function does not return a value (i.e. it returns
2047 * `undefined`) then an error will be raised and a `null` value will be returned
2048 * in the response. If the serialize function returns `null`, then no error will
2049 * be included in the response.
2050 *
2051 * Example:
2052 *
2053 * const OddType = new GraphQLScalarType({
2054 * name: 'Odd',
2055 * serialize(value) {
2056 * if (value % 2 === 1) {
2057 * return value;
2058 * }
2059 * }
2060 * });
2061 *
2062 */
2063
2064
2065var GraphQLScalarType = /*#__PURE__*/function () {
2066 function GraphQLScalarType(config) {
2067 var _config$parseValue, _config$serialize, _config$parseLiteral;
2068
2069 var parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : identityFunc;
2070 this.name = config.name;
2071 this.description = config.description;
2072 this.specifiedByUrl = config.specifiedByUrl;
2073 this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : identityFunc;
2074 this.parseValue = parseValue;
2075 this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : function (node, variables) {
2076 return parseValue(valueFromASTUntyped(node, variables));
2077 };
2078 this.extensions = config.extensions && toObjMap(config.extensions);
2079 this.astNode = config.astNode;
2080 this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
2081 typeof config.name === 'string' || devAssert(0, 'Must provide name.');
2082 config.specifiedByUrl == null || typeof config.specifiedByUrl === 'string' || devAssert(0, "".concat(this.name, " must provide \"specifiedByUrl\" as a string, ") + "but got: ".concat(inspect(config.specifiedByUrl), "."));
2083 config.serialize == null || typeof config.serialize === 'function' || devAssert(0, "".concat(this.name, " must provide \"serialize\" function. If this custom Scalar is also used as an input type, ensure \"parseValue\" and \"parseLiteral\" functions are also provided."));
2084
2085 if (config.parseLiteral) {
2086 typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function' || devAssert(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" functions."));
2087 }
2088 }
2089
2090 var _proto = GraphQLScalarType.prototype;
2091
2092 _proto.toConfig = function toConfig() {
2093 var _this$extensionASTNod;
2094
2095 return {
2096 name: this.name,
2097 description: this.description,
2098 specifiedByUrl: this.specifiedByUrl,
2099 serialize: this.serialize,
2100 parseValue: this.parseValue,
2101 parseLiteral: this.parseLiteral,
2102 extensions: this.extensions,
2103 astNode: this.astNode,
2104 extensionASTNodes: (_this$extensionASTNod = this.extensionASTNodes) !== null && _this$extensionASTNod !== void 0 ? _this$extensionASTNod : []
2105 };
2106 };
2107
2108 _proto.toString = function toString() {
2109 return this.name;
2110 };
2111
2112 _proto.toJSON = function toJSON() {
2113 return this.toString();
2114 } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
2115 ;
2116
2117 _createClass$1(GraphQLScalarType, [{
2118 key: SYMBOL_TO_STRING_TAG,
2119 get: function get() {
2120 return 'GraphQLScalarType';
2121 }
2122 }]);
2123
2124 return GraphQLScalarType;
2125}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
2126
2127defineInspect(GraphQLScalarType);
2128
2129/**
2130 * Object Type Definition
2131 *
2132 * Almost all of the GraphQL types you define will be object types. Object types
2133 * have a name, but most importantly describe their fields.
2134 *
2135 * Example:
2136 *
2137 * const AddressType = new GraphQLObjectType({
2138 * name: 'Address',
2139 * fields: {
2140 * street: { type: GraphQLString },
2141 * number: { type: GraphQLInt },
2142 * formatted: {
2143 * type: GraphQLString,
2144 * resolve(obj) {
2145 * return obj.number + ' ' + obj.street
2146 * }
2147 * }
2148 * }
2149 * });
2150 *
2151 * When two types need to refer to each other, or a type needs to refer to
2152 * itself in a field, you can use a function expression (aka a closure or a
2153 * thunk) to supply the fields lazily.
2154 *
2155 * Example:
2156 *
2157 * const PersonType = new GraphQLObjectType({
2158 * name: 'Person',
2159 * fields: () => ({
2160 * name: { type: GraphQLString },
2161 * bestFriend: { type: PersonType },
2162 * })
2163 * });
2164 *
2165 */
2166var GraphQLObjectType = /*#__PURE__*/function () {
2167 function GraphQLObjectType(config) {
2168 this.name = config.name;
2169 this.description = config.description;
2170 this.isTypeOf = config.isTypeOf;
2171 this.extensions = config.extensions && toObjMap(config.extensions);
2172 this.astNode = config.astNode;
2173 this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
2174 this._fields = defineFieldMap.bind(undefined, config);
2175 this._interfaces = defineInterfaces.bind(undefined, config);
2176 typeof config.name === 'string' || devAssert(0, 'Must provide name.');
2177 config.isTypeOf == null || typeof config.isTypeOf === 'function' || devAssert(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat(inspect(config.isTypeOf), "."));
2178 }
2179
2180 var _proto2 = GraphQLObjectType.prototype;
2181
2182 _proto2.getFields = function getFields() {
2183 if (typeof this._fields === 'function') {
2184 this._fields = this._fields();
2185 }
2186
2187 return this._fields;
2188 };
2189
2190 _proto2.getInterfaces = function getInterfaces() {
2191 if (typeof this._interfaces === 'function') {
2192 this._interfaces = this._interfaces();
2193 }
2194
2195 return this._interfaces;
2196 };
2197
2198 _proto2.toConfig = function toConfig() {
2199 return {
2200 name: this.name,
2201 description: this.description,
2202 interfaces: this.getInterfaces(),
2203 fields: fieldsToFieldsConfig(this.getFields()),
2204 isTypeOf: this.isTypeOf,
2205 extensions: this.extensions,
2206 astNode: this.astNode,
2207 extensionASTNodes: this.extensionASTNodes || []
2208 };
2209 };
2210
2211 _proto2.toString = function toString() {
2212 return this.name;
2213 };
2214
2215 _proto2.toJSON = function toJSON() {
2216 return this.toString();
2217 } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
2218 ;
2219
2220 _createClass$1(GraphQLObjectType, [{
2221 key: SYMBOL_TO_STRING_TAG,
2222 get: function get() {
2223 return 'GraphQLObjectType';
2224 }
2225 }]);
2226
2227 return GraphQLObjectType;
2228}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
2229
2230defineInspect(GraphQLObjectType);
2231
2232function defineInterfaces(config) {
2233 var _resolveThunk;
2234
2235 var interfaces = (_resolveThunk = resolveThunk(config.interfaces)) !== null && _resolveThunk !== void 0 ? _resolveThunk : [];
2236 Array.isArray(interfaces) || devAssert(0, "".concat(config.name, " interfaces must be an Array or a function which returns an Array."));
2237 return interfaces;
2238}
2239
2240function defineFieldMap(config) {
2241 var fieldMap = resolveThunk(config.fields);
2242 isPlainObj(fieldMap) || devAssert(0, "".concat(config.name, " fields must be an object with field names as keys or a function which returns such an object."));
2243 return mapValue(fieldMap, function (fieldConfig, fieldName) {
2244 var _fieldConfig$args;
2245
2246 isPlainObj(fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object."));
2247 !('isDeprecated' in fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" instead of \"isDeprecated\"."));
2248 fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function' || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field resolver must be a function if ") + "provided, but got: ".concat(inspect(fieldConfig.resolve), "."));
2249 var argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {};
2250 isPlainObj(argsConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument names as keys."));
2251 var args = objectEntries(argsConfig).map(function (_ref) {
2252 var argName = _ref[0],
2253 argConfig = _ref[1];
2254 return {
2255 name: argName,
2256 description: argConfig.description,
2257 type: argConfig.type,
2258 defaultValue: argConfig.defaultValue,
2259 deprecationReason: argConfig.deprecationReason,
2260 extensions: argConfig.extensions && toObjMap(argConfig.extensions),
2261 astNode: argConfig.astNode
2262 };
2263 });
2264 return {
2265 name: fieldName,
2266 description: fieldConfig.description,
2267 type: fieldConfig.type,
2268 args: args,
2269 resolve: fieldConfig.resolve,
2270 subscribe: fieldConfig.subscribe,
2271 isDeprecated: fieldConfig.deprecationReason != null,
2272 deprecationReason: fieldConfig.deprecationReason,
2273 extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions),
2274 astNode: fieldConfig.astNode
2275 };
2276 });
2277}
2278
2279function isPlainObj(obj) {
2280 return isObjectLike(obj) && !Array.isArray(obj);
2281}
2282
2283function fieldsToFieldsConfig(fields) {
2284 return mapValue(fields, function (field) {
2285 return {
2286 description: field.description,
2287 type: field.type,
2288 args: argsToArgsConfig(field.args),
2289 resolve: field.resolve,
2290 subscribe: field.subscribe,
2291 deprecationReason: field.deprecationReason,
2292 extensions: field.extensions,
2293 astNode: field.astNode
2294 };
2295 });
2296}
2297/**
2298 * @internal
2299 */
2300
2301
2302function argsToArgsConfig(args) {
2303 return keyValMap(args, function (arg) {
2304 return arg.name;
2305 }, function (arg) {
2306 return {
2307 description: arg.description,
2308 type: arg.type,
2309 defaultValue: arg.defaultValue,
2310 deprecationReason: arg.deprecationReason,
2311 extensions: arg.extensions,
2312 astNode: arg.astNode
2313 };
2314 });
2315}
2316
2317/**
2318 * Interface Type Definition
2319 *
2320 * When a field can return one of a heterogeneous set of types, a Interface type
2321 * is used to describe what types are possible, what fields are in common across
2322 * all types, as well as a function to determine which type is actually used
2323 * when the field is resolved.
2324 *
2325 * Example:
2326 *
2327 * const EntityType = new GraphQLInterfaceType({
2328 * name: 'Entity',
2329 * fields: {
2330 * name: { type: GraphQLString }
2331 * }
2332 * });
2333 *
2334 */
2335var GraphQLInterfaceType = /*#__PURE__*/function () {
2336 function GraphQLInterfaceType(config) {
2337 this.name = config.name;
2338 this.description = config.description;
2339 this.resolveType = config.resolveType;
2340 this.extensions = config.extensions && toObjMap(config.extensions);
2341 this.astNode = config.astNode;
2342 this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
2343 this._fields = defineFieldMap.bind(undefined, config);
2344 this._interfaces = defineInterfaces.bind(undefined, config);
2345 typeof config.name === 'string' || devAssert(0, 'Must provide name.');
2346 config.resolveType == null || typeof config.resolveType === 'function' || devAssert(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), "."));
2347 }
2348
2349 var _proto3 = GraphQLInterfaceType.prototype;
2350
2351 _proto3.getFields = function getFields() {
2352 if (typeof this._fields === 'function') {
2353 this._fields = this._fields();
2354 }
2355
2356 return this._fields;
2357 };
2358
2359 _proto3.getInterfaces = function getInterfaces() {
2360 if (typeof this._interfaces === 'function') {
2361 this._interfaces = this._interfaces();
2362 }
2363
2364 return this._interfaces;
2365 };
2366
2367 _proto3.toConfig = function toConfig() {
2368 var _this$extensionASTNod2;
2369
2370 return {
2371 name: this.name,
2372 description: this.description,
2373 interfaces: this.getInterfaces(),
2374 fields: fieldsToFieldsConfig(this.getFields()),
2375 resolveType: this.resolveType,
2376 extensions: this.extensions,
2377 astNode: this.astNode,
2378 extensionASTNodes: (_this$extensionASTNod2 = this.extensionASTNodes) !== null && _this$extensionASTNod2 !== void 0 ? _this$extensionASTNod2 : []
2379 };
2380 };
2381
2382 _proto3.toString = function toString() {
2383 return this.name;
2384 };
2385
2386 _proto3.toJSON = function toJSON() {
2387 return this.toString();
2388 } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
2389 ;
2390
2391 _createClass$1(GraphQLInterfaceType, [{
2392 key: SYMBOL_TO_STRING_TAG,
2393 get: function get() {
2394 return 'GraphQLInterfaceType';
2395 }
2396 }]);
2397
2398 return GraphQLInterfaceType;
2399}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
2400
2401defineInspect(GraphQLInterfaceType);
2402
2403/**
2404 * Union Type Definition
2405 *
2406 * When a field can return one of a heterogeneous set of types, a Union type
2407 * is used to describe what types are possible as well as providing a function
2408 * to determine which type is actually used when the field is resolved.
2409 *
2410 * Example:
2411 *
2412 * const PetType = new GraphQLUnionType({
2413 * name: 'Pet',
2414 * types: [ DogType, CatType ],
2415 * resolveType(value) {
2416 * if (value instanceof Dog) {
2417 * return DogType;
2418 * }
2419 * if (value instanceof Cat) {
2420 * return CatType;
2421 * }
2422 * }
2423 * });
2424 *
2425 */
2426var GraphQLUnionType = /*#__PURE__*/function () {
2427 function GraphQLUnionType(config) {
2428 this.name = config.name;
2429 this.description = config.description;
2430 this.resolveType = config.resolveType;
2431 this.extensions = config.extensions && toObjMap(config.extensions);
2432 this.astNode = config.astNode;
2433 this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
2434 this._types = defineTypes.bind(undefined, config);
2435 typeof config.name === 'string' || devAssert(0, 'Must provide name.');
2436 config.resolveType == null || typeof config.resolveType === 'function' || devAssert(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), "."));
2437 }
2438
2439 var _proto4 = GraphQLUnionType.prototype;
2440
2441 _proto4.getTypes = function getTypes() {
2442 if (typeof this._types === 'function') {
2443 this._types = this._types();
2444 }
2445
2446 return this._types;
2447 };
2448
2449 _proto4.toConfig = function toConfig() {
2450 var _this$extensionASTNod3;
2451
2452 return {
2453 name: this.name,
2454 description: this.description,
2455 types: this.getTypes(),
2456 resolveType: this.resolveType,
2457 extensions: this.extensions,
2458 astNode: this.astNode,
2459 extensionASTNodes: (_this$extensionASTNod3 = this.extensionASTNodes) !== null && _this$extensionASTNod3 !== void 0 ? _this$extensionASTNod3 : []
2460 };
2461 };
2462
2463 _proto4.toString = function toString() {
2464 return this.name;
2465 };
2466
2467 _proto4.toJSON = function toJSON() {
2468 return this.toString();
2469 } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
2470 ;
2471
2472 _createClass$1(GraphQLUnionType, [{
2473 key: SYMBOL_TO_STRING_TAG,
2474 get: function get() {
2475 return 'GraphQLUnionType';
2476 }
2477 }]);
2478
2479 return GraphQLUnionType;
2480}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
2481
2482defineInspect(GraphQLUnionType);
2483
2484function defineTypes(config) {
2485 var types = resolveThunk(config.types);
2486 Array.isArray(types) || devAssert(0, "Must provide Array of types or a function which returns such an array for Union ".concat(config.name, "."));
2487 return types;
2488}
2489
2490/**
2491 * Enum Type Definition
2492 *
2493 * Some leaf values of requests and input values are Enums. GraphQL serializes
2494 * Enum values as strings, however internally Enums can be represented by any
2495 * kind of type, often integers.
2496 *
2497 * Example:
2498 *
2499 * const RGBType = new GraphQLEnumType({
2500 * name: 'RGB',
2501 * values: {
2502 * RED: { value: 0 },
2503 * GREEN: { value: 1 },
2504 * BLUE: { value: 2 }
2505 * }
2506 * });
2507 *
2508 * Note: If a value is not provided in a definition, the name of the enum value
2509 * will be used as its internal value.
2510 */
2511var GraphQLEnumType
2512/* <T> */
2513= /*#__PURE__*/function () {
2514 function GraphQLEnumType(config) {
2515 this.name = config.name;
2516 this.description = config.description;
2517 this.extensions = config.extensions && toObjMap(config.extensions);
2518 this.astNode = config.astNode;
2519 this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
2520 this._values = defineEnumValues(this.name, config.values);
2521 this._valueLookup = new Map(this._values.map(function (enumValue) {
2522 return [enumValue.value, enumValue];
2523 }));
2524 this._nameLookup = keyMap(this._values, function (value) {
2525 return value.name;
2526 });
2527 typeof config.name === 'string' || devAssert(0, 'Must provide name.');
2528 }
2529
2530 var _proto5 = GraphQLEnumType.prototype;
2531
2532 _proto5.getValues = function getValues() {
2533 return this._values;
2534 };
2535
2536 _proto5.getValue = function getValue(name) {
2537 return this._nameLookup[name];
2538 };
2539
2540 _proto5.serialize = function serialize(outputValue) {
2541 var enumValue = this._valueLookup.get(outputValue);
2542
2543 if (enumValue === undefined) {
2544 throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent value: ").concat(inspect(outputValue)));
2545 }
2546
2547 return enumValue.name;
2548 };
2549
2550 _proto5.parseValue = function parseValue(inputValue)
2551 /* T */
2552 {
2553 if (typeof inputValue !== 'string') {
2554 var valueStr = inspect(inputValue);
2555 throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-string value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr));
2556 }
2557
2558 var enumValue = this.getValue(inputValue);
2559
2560 if (enumValue == null) {
2561 throw new GraphQLError("Value \"".concat(inputValue, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, inputValue));
2562 }
2563
2564 return enumValue.value;
2565 };
2566
2567 _proto5.parseLiteral = function parseLiteral(valueNode, _variables)
2568 /* T */
2569 {
2570 // Note: variables will be resolved to a value before calling this function.
2571 if (valueNode.kind !== Kind.ENUM) {
2572 var valueStr = print(valueNode);
2573 throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-enum value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr), valueNode);
2574 }
2575
2576 var enumValue = this.getValue(valueNode.value);
2577
2578 if (enumValue == null) {
2579 var _valueStr = print(valueNode);
2580
2581 throw new GraphQLError("Value \"".concat(_valueStr, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, _valueStr), valueNode);
2582 }
2583
2584 return enumValue.value;
2585 };
2586
2587 _proto5.toConfig = function toConfig() {
2588 var _this$extensionASTNod4;
2589
2590 var values = keyValMap(this.getValues(), function (value) {
2591 return value.name;
2592 }, function (value) {
2593 return {
2594 description: value.description,
2595 value: value.value,
2596 deprecationReason: value.deprecationReason,
2597 extensions: value.extensions,
2598 astNode: value.astNode
2599 };
2600 });
2601 return {
2602 name: this.name,
2603 description: this.description,
2604 values: values,
2605 extensions: this.extensions,
2606 astNode: this.astNode,
2607 extensionASTNodes: (_this$extensionASTNod4 = this.extensionASTNodes) !== null && _this$extensionASTNod4 !== void 0 ? _this$extensionASTNod4 : []
2608 };
2609 };
2610
2611 _proto5.toString = function toString() {
2612 return this.name;
2613 };
2614
2615 _proto5.toJSON = function toJSON() {
2616 return this.toString();
2617 } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
2618 ;
2619
2620 _createClass$1(GraphQLEnumType, [{
2621 key: SYMBOL_TO_STRING_TAG,
2622 get: function get() {
2623 return 'GraphQLEnumType';
2624 }
2625 }]);
2626
2627 return GraphQLEnumType;
2628}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
2629
2630defineInspect(GraphQLEnumType);
2631
2632function didYouMeanEnumValue(enumType, unknownValueStr) {
2633 var allNames = enumType.getValues().map(function (value) {
2634 return value.name;
2635 });
2636 var suggestedValues = suggestionList(unknownValueStr, allNames);
2637 return didYouMean('the enum value', suggestedValues);
2638}
2639
2640function defineEnumValues(typeName, valueMap) {
2641 isPlainObj(valueMap) || devAssert(0, "".concat(typeName, " values must be an object with value names as keys."));
2642 return objectEntries(valueMap).map(function (_ref2) {
2643 var valueName = _ref2[0],
2644 valueConfig = _ref2[1];
2645 isPlainObj(valueConfig) || devAssert(0, "".concat(typeName, ".").concat(valueName, " must refer to an object with a \"value\" key ") + "representing an internal value but got: ".concat(inspect(valueConfig), "."));
2646 !('isDeprecated' in valueConfig) || devAssert(0, "".concat(typeName, ".").concat(valueName, " should provide \"deprecationReason\" instead of \"isDeprecated\"."));
2647 return {
2648 name: valueName,
2649 description: valueConfig.description,
2650 value: valueConfig.value !== undefined ? valueConfig.value : valueName,
2651 isDeprecated: valueConfig.deprecationReason != null,
2652 deprecationReason: valueConfig.deprecationReason,
2653 extensions: valueConfig.extensions && toObjMap(valueConfig.extensions),
2654 astNode: valueConfig.astNode
2655 };
2656 });
2657}
2658
2659/**
2660 * Input Object Type Definition
2661 *
2662 * An input object defines a structured collection of fields which may be
2663 * supplied to a field argument.
2664 *
2665 * Using `NonNull` will ensure that a value must be provided by the query
2666 *
2667 * Example:
2668 *
2669 * const GeoPoint = new GraphQLInputObjectType({
2670 * name: 'GeoPoint',
2671 * fields: {
2672 * lat: { type: new GraphQLNonNull(GraphQLFloat) },
2673 * lon: { type: new GraphQLNonNull(GraphQLFloat) },
2674 * alt: { type: GraphQLFloat, defaultValue: 0 },
2675 * }
2676 * });
2677 *
2678 */
2679var GraphQLInputObjectType = /*#__PURE__*/function () {
2680 function GraphQLInputObjectType(config) {
2681 this.name = config.name;
2682 this.description = config.description;
2683 this.extensions = config.extensions && toObjMap(config.extensions);
2684 this.astNode = config.astNode;
2685 this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
2686 this._fields = defineInputFieldMap.bind(undefined, config);
2687 typeof config.name === 'string' || devAssert(0, 'Must provide name.');
2688 }
2689
2690 var _proto6 = GraphQLInputObjectType.prototype;
2691
2692 _proto6.getFields = function getFields() {
2693 if (typeof this._fields === 'function') {
2694 this._fields = this._fields();
2695 }
2696
2697 return this._fields;
2698 };
2699
2700 _proto6.toConfig = function toConfig() {
2701 var _this$extensionASTNod5;
2702
2703 var fields = mapValue(this.getFields(), function (field) {
2704 return {
2705 description: field.description,
2706 type: field.type,
2707 defaultValue: field.defaultValue,
2708 extensions: field.extensions,
2709 astNode: field.astNode
2710 };
2711 });
2712 return {
2713 name: this.name,
2714 description: this.description,
2715 fields: fields,
2716 extensions: this.extensions,
2717 astNode: this.astNode,
2718 extensionASTNodes: (_this$extensionASTNod5 = this.extensionASTNodes) !== null && _this$extensionASTNod5 !== void 0 ? _this$extensionASTNod5 : []
2719 };
2720 };
2721
2722 _proto6.toString = function toString() {
2723 return this.name;
2724 };
2725
2726 _proto6.toJSON = function toJSON() {
2727 return this.toString();
2728 } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
2729 ;
2730
2731 _createClass$1(GraphQLInputObjectType, [{
2732 key: SYMBOL_TO_STRING_TAG,
2733 get: function get() {
2734 return 'GraphQLInputObjectType';
2735 }
2736 }]);
2737
2738 return GraphQLInputObjectType;
2739}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
2740
2741defineInspect(GraphQLInputObjectType);
2742
2743function defineInputFieldMap(config) {
2744 var fieldMap = resolveThunk(config.fields);
2745 isPlainObj(fieldMap) || devAssert(0, "".concat(config.name, " fields must be an object with field names as keys or a function which returns such an object."));
2746 return mapValue(fieldMap, function (fieldConfig, fieldName) {
2747 !('resolve' in fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but Input Types cannot define resolvers."));
2748 return {
2749 name: fieldName,
2750 description: fieldConfig.description,
2751 type: fieldConfig.type,
2752 defaultValue: fieldConfig.defaultValue,
2753 deprecationReason: fieldConfig.deprecationReason,
2754 extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions),
2755 astNode: fieldConfig.astNode
2756 };
2757 });
2758}
2759
2760/* eslint-disable no-redeclare */
2761// $FlowFixMe[name-already-bound] workaround for: https://github.com/facebook/flow/issues/4441
2762var objectValues = Object.values || function (obj) {
2763 return Object.keys(obj).map(function (key) {
2764 return obj[key];
2765 });
2766};
2767
2768/**
2769 * Produces a JavaScript value given a GraphQL Value AST.
2770 *
2771 * A GraphQL type must be provided, which will be used to interpret different
2772 * GraphQL Value literals.
2773 *
2774 * Returns `undefined` when the value could not be validly coerced according to
2775 * the provided type.
2776 *
2777 * | GraphQL Value | JSON Value |
2778 * | -------------------- | ------------- |
2779 * | Input Object | Object |
2780 * | List | Array |
2781 * | Boolean | Boolean |
2782 * | String | String |
2783 * | Int / Float | Number |
2784 * | Enum Value | Mixed |
2785 * | NullValue | null |
2786 *
2787 */
2788
2789function valueFromAST(valueNode, type, variables) {
2790 if (!valueNode) {
2791 // When there is no node, then there is also no value.
2792 // Importantly, this is different from returning the value null.
2793 return;
2794 }
2795
2796 if (valueNode.kind === Kind.VARIABLE) {
2797 var variableName = valueNode.name.value;
2798
2799 if (variables == null || variables[variableName] === undefined) {
2800 // No valid return value.
2801 return;
2802 }
2803
2804 var variableValue = variables[variableName];
2805
2806 if (variableValue === null && isNonNullType(type)) {
2807 return; // Invalid: intentionally return no value.
2808 } // Note: This does no further checking that this variable is correct.
2809 // This assumes that this query has been validated and the variable
2810 // usage here is of the correct type.
2811
2812
2813 return variableValue;
2814 }
2815
2816 if (isNonNullType(type)) {
2817 if (valueNode.kind === Kind.NULL) {
2818 return; // Invalid: intentionally return no value.
2819 }
2820
2821 return valueFromAST(valueNode, type.ofType, variables);
2822 }
2823
2824 if (valueNode.kind === Kind.NULL) {
2825 // This is explicitly returning the value null.
2826 return null;
2827 }
2828
2829 if (isListType(type)) {
2830 var itemType = type.ofType;
2831
2832 if (valueNode.kind === Kind.LIST) {
2833 var coercedValues = [];
2834
2835 for (var _i2 = 0, _valueNode$values2 = valueNode.values; _i2 < _valueNode$values2.length; _i2++) {
2836 var itemNode = _valueNode$values2[_i2];
2837
2838 if (isMissingVariable(itemNode, variables)) {
2839 // If an array contains a missing variable, it is either coerced to
2840 // null or if the item type is non-null, it considered invalid.
2841 if (isNonNullType(itemType)) {
2842 return; // Invalid: intentionally return no value.
2843 }
2844
2845 coercedValues.push(null);
2846 } else {
2847 var itemValue = valueFromAST(itemNode, itemType, variables);
2848
2849 if (itemValue === undefined) {
2850 return; // Invalid: intentionally return no value.
2851 }
2852
2853 coercedValues.push(itemValue);
2854 }
2855 }
2856
2857 return coercedValues;
2858 }
2859
2860 var coercedValue = valueFromAST(valueNode, itemType, variables);
2861
2862 if (coercedValue === undefined) {
2863 return; // Invalid: intentionally return no value.
2864 }
2865
2866 return [coercedValue];
2867 }
2868
2869 if (isInputObjectType(type)) {
2870 if (valueNode.kind !== Kind.OBJECT) {
2871 return; // Invalid: intentionally return no value.
2872 }
2873
2874 var coercedObj = Object.create(null);
2875 var fieldNodes = keyMap(valueNode.fields, function (field) {
2876 return field.name.value;
2877 });
2878
2879 for (var _i4 = 0, _objectValues2 = objectValues(type.getFields()); _i4 < _objectValues2.length; _i4++) {
2880 var field = _objectValues2[_i4];
2881 var fieldNode = fieldNodes[field.name];
2882
2883 if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
2884 if (field.defaultValue !== undefined) {
2885 coercedObj[field.name] = field.defaultValue;
2886 } else if (isNonNullType(field.type)) {
2887 return; // Invalid: intentionally return no value.
2888 }
2889
2890 continue;
2891 }
2892
2893 var fieldValue = valueFromAST(fieldNode.value, field.type, variables);
2894
2895 if (fieldValue === undefined) {
2896 return; // Invalid: intentionally return no value.
2897 }
2898
2899 coercedObj[field.name] = fieldValue;
2900 }
2901
2902 return coercedObj;
2903 } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')
2904
2905
2906 if (isLeafType(type)) {
2907 // Scalars and Enums fulfill parsing a literal value via parseLiteral().
2908 // Invalid values represent a failure to parse correctly, in which case
2909 // no value is returned.
2910 var result;
2911
2912 try {
2913 result = type.parseLiteral(valueNode, variables);
2914 } catch (_error) {
2915 return; // Invalid: intentionally return no value.
2916 }
2917
2918 if (result === undefined) {
2919 return; // Invalid: intentionally return no value.
2920 }
2921
2922 return result;
2923 } // istanbul ignore next (Not reachable. All possible input types have been considered)
2924
2925
2926 invariant(0, 'Unexpected input type: ' + inspect(type));
2927} // Returns true if the provided valueNode is a variable which is not defined
2928// in the set of variables.
2929
2930function isMissingVariable(valueNode, variables) {
2931 return valueNode.kind === Kind.VARIABLE && (variables == null || variables[valueNode.name.value] === undefined);
2932}
2933
2934/**
2935 * Prepares an object map of argument values given a list of argument
2936 * definitions and list of argument AST nodes.
2937 *
2938 * Note: The returned value is a plain Object with a prototype, since it is
2939 * exposed to user code. Care should be taken to not pull values from the
2940 * Object prototype.
2941 *
2942 * @internal
2943 */
2944
2945
2946function getArgumentValues(def, node, variableValues) {
2947 var _node$arguments;
2948
2949 var coercedValues = {}; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
2950
2951 var argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : [];
2952 var argNodeMap = keyMap(argumentNodes, function (arg) {
2953 return arg.name.value;
2954 });
2955
2956 for (var _i4 = 0, _def$args2 = def.args; _i4 < _def$args2.length; _i4++) {
2957 var argDef = _def$args2[_i4];
2958 var name = argDef.name;
2959 var argType = argDef.type;
2960 var argumentNode = argNodeMap[name];
2961
2962 if (!argumentNode) {
2963 if (argDef.defaultValue !== undefined) {
2964 coercedValues[name] = argDef.defaultValue;
2965 } else if (isNonNullType(argType)) {
2966 throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + 'was not provided.', node);
2967 }
2968
2969 continue;
2970 }
2971
2972 var valueNode = argumentNode.value;
2973 var isNull = valueNode.kind === Kind.NULL;
2974
2975 if (valueNode.kind === Kind.VARIABLE) {
2976 var variableName = valueNode.name.value;
2977
2978 if (variableValues == null || !hasOwnProperty(variableValues, variableName)) {
2979 if (argDef.defaultValue !== undefined) {
2980 coercedValues[name] = argDef.defaultValue;
2981 } else if (isNonNullType(argType)) {
2982 throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + "was provided the variable \"$".concat(variableName, "\" which was not provided a runtime value."), valueNode);
2983 }
2984
2985 continue;
2986 }
2987
2988 isNull = variableValues[variableName] == null;
2989 }
2990
2991 if (isNull && isNonNullType(argType)) {
2992 throw new GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat(inspect(argType), "\" ") + 'must not be null.', valueNode);
2993 }
2994
2995 var coercedValue = valueFromAST(valueNode, argType, variableValues);
2996
2997 if (coercedValue === undefined) {
2998 // Note: ValuesOfCorrectTypeRule validation should catch this before
2999 // execution. This is a runtime check to ensure execution does not
3000 // continue with an invalid argument value.
3001 throw new GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat(print(valueNode), "."), valueNode);
3002 }
3003
3004 coercedValues[name] = coercedValue;
3005 }
3006
3007 return coercedValues;
3008}
3009
3010function hasOwnProperty(obj, prop) {
3011 return Object.prototype.hasOwnProperty.call(obj, prop);
3012}
3013
3014const ONE_OF_DIRECTIVE_SDL = /* GraphQL */ `
3015 directive @oneOf on INPUT_OBJECT | FIELD_DEFINITION
3016`;
3017const OneOfInputObjectsRule = (validationContext, executionArgs) => {
3018 return {
3019 Field: node => {
3020 var _a, _b;
3021 if ((_a = node.arguments) === null || _a === void 0 ? void 0 : _a.length) {
3022 const fieldType = validationContext.getFieldDef();
3023 if (!fieldType) {
3024 return;
3025 }
3026 const values = getArgumentValues(fieldType, node, executionArgs.variableValues);
3027 if (fieldType) {
3028 const isOneOfFieldType = ((_b = fieldType.extensions) === null || _b === void 0 ? void 0 : _b.oneOf) || (fieldType.astNode && getDirectiveFromAstNode(fieldType.astNode, 'oneOf'));
3029 if (isOneOfFieldType) {
3030 if (Object.keys(values).length !== 1) {
3031 validationContext.reportError(new graphql.GraphQLError(`Exactly one key must be specified for input for field "${fieldType.type.toString()}.${node.name.value}"`, [node]));
3032 }
3033 }
3034 }
3035 for (const arg of node.arguments) {
3036 const argType = fieldType.args.find(typeArg => typeArg.name === arg.name.value);
3037 if (argType) {
3038 traverseVariables(validationContext, arg, argType.type, values[arg.name.value]);
3039 }
3040 }
3041 }
3042 },
3043 };
3044};
3045function traverseVariables(validationContext, arg, graphqlType, currentValue) {
3046 var _a;
3047 // if the current value is empty we don't need to traverse deeper
3048 // if it shouldn't be empty, the "original" validation phase should complain.
3049 if (currentValue == null) {
3050 return;
3051 }
3052 if (graphql.isListType(graphqlType)) {
3053 if (!Array.isArray(currentValue)) {
3054 // because of graphql type coercion a single object should be treated as an array of one object
3055 currentValue = [currentValue];
3056 }
3057 currentValue.forEach(value => {
3058 traverseVariables(validationContext, arg, graphqlType.ofType, value);
3059 });
3060 return;
3061 }
3062 if (typeof currentValue !== 'object' || currentValue == null) {
3063 // in case the value is not an object, the "original" validation phase should complain.
3064 return;
3065 }
3066 const inputType = unwrapType(graphqlType);
3067 const isOneOfInputType = ((_a = inputType.extensions) === null || _a === void 0 ? void 0 : _a.oneOf) || (inputType.astNode && getDirectiveFromAstNode(inputType.astNode, 'oneOf'));
3068 if (isOneOfInputType) {
3069 if (Object.keys(currentValue).length !== 1) {
3070 validationContext.reportError(new graphql.GraphQLError(`Exactly one key must be specified for input type "${inputType.name}"`, [arg]));
3071 }
3072 }
3073 if (inputType instanceof graphql.GraphQLInputObjectType) {
3074 for (const [name, fieldConfig] of Object.entries(inputType.getFields())) {
3075 traverseVariables(validationContext, arg, fieldConfig.type, currentValue[name]);
3076 }
3077 }
3078}
3079
3080exports.ONE_OF_DIRECTIVE_SDL = ONE_OF_DIRECTIVE_SDL;
3081exports.OneOfInputObjectsRule = OneOfInputObjectsRule;
3082exports.getDirectiveFromAstNode = getDirectiveFromAstNode;
3083exports.unwrapType = unwrapType;
3084exports.useExtendedValidation = useExtendedValidation;
3085//# sourceMappingURL=index.cjs.js.map