UNPKG

@absinthe/socket-apollo-link

Version:
1,647 lines (1,448 loc) 341 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.AbsintheSocketApolloLink = {}))); }(this, (function (exports) { 'use strict'; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var _global = createCommonjsModule(function (module) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef }); var _core = createCommonjsModule(function (module) { var core = module.exports = { version: '2.6.0' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef }); var _core_1 = _core.version; var _isObject = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; var _anObject = function (it) { if (!_isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; var _fails = function (exec) { try { return !!exec(); } catch (e) { return true; } }; // Thank's IE8 for his funny defineProperty var _descriptors = !_fails(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); var document = _global.document; // typeof document.createElement is 'object' in old IE var is = _isObject(document) && _isObject(document.createElement); var _domCreate = function (it) { return is ? document.createElement(it) : {}; }; var _ie8DomDefine = !_descriptors && !_fails(function () { return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7; }); // 7.1.1 ToPrimitive(input [, PreferredType]) // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string var _toPrimitive = function (it, S) { if (!_isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; var dP = Object.defineProperty; var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) { _anObject(O); P = _toPrimitive(P, true); _anObject(Attributes); if (_ie8DomDefine) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; var _objectDp = { f: f }; var _propertyDesc = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; var _hide = _descriptors ? function (object, key, value) { return _objectDp.f(object, key, _propertyDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; var hasOwnProperty = {}.hasOwnProperty; var _has = function (it, key) { return hasOwnProperty.call(it, key); }; var id = 0; var px = Math.random(); var _uid = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; var _redefine = createCommonjsModule(function (module) { var SRC = _uid('src'); var TO_STRING = 'toString'; var $toString = Function[TO_STRING]; var TPL = ('' + $toString).split(TO_STRING); _core.inspectSource = function (it) { return $toString.call(it); }; (module.exports = function (O, key, val, safe) { var isFunction = typeof val == 'function'; if (isFunction) _has(val, 'name') || _hide(val, 'name', key); if (O[key] === val) return; if (isFunction) _has(val, SRC) || _hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); if (O === _global) { O[key] = val; } else if (!safe) { delete O[key]; _hide(O, key, val); } else if (O[key]) { O[key] = val; } else { _hide(O, key, val); } // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, TO_STRING, function toString() { return typeof this == 'function' && this[SRC] || $toString.call(this); }); }); var _aFunction = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; // optional / simple context binding var _ctx = function (fn, that, length) { _aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] || (_global[name] = {}) : (_global[name] || {})[PROTOTYPE]; var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}); var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); var key, own, out, exp; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context exp = IS_BIND && own ? _ctx(out, _global) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; // extend global if (target) _redefine(target, key, out, type & $export.U); // export if (exports[key] != out) _hide(exports, key, exp); if (IS_PROTO && expProto[key] != out) expProto[key] = out; } }; _global.core = _core; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` var _export = $export; // fast apply, http://jsperf.lnkit.com/fast-apply/5 var _invoke = function (fn, args, that) { var un = that === undefined; switch (args.length) { case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; var arraySlice = [].slice; var factories = {}; var construct = function (F, len, args) { if (!(len in factories)) { for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; // eslint-disable-next-line no-new-func factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); } return factories[len](F, args); }; var _bind = Function.bind || function bind(that /* , ...args */) { var fn = _aFunction(this); var partArgs = arraySlice.call(arguments, 1); var bound = function (/* args... */) { var args = partArgs.concat(arraySlice.call(arguments)); return this instanceof bound ? construct(fn, args.length, args) : _invoke(fn, args, that); }; if (_isObject(fn.prototype)) bound.prototype = fn.prototype; return bound; }; // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) _export(_export.P, 'Function', { bind: _bind }); function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError("Cannot instantiate an arrow function"); } } var newArrowCheck = _newArrowCheck; var Observable_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // === Symbol Support === var hasSymbols = function () { return typeof Symbol === 'function'; }; var hasSymbol = function (name) { return hasSymbols() && Boolean(Symbol[name]); }; var getSymbol = function (name) { return hasSymbol(name) ? Symbol[name] : '@@' + name; }; if (hasSymbols() && !hasSymbol('observable')) { Symbol.observable = Symbol('observable'); } var SymbolIterator = getSymbol('iterator'); var SymbolObservable = getSymbol('observable'); var SymbolSpecies = getSymbol('species'); // === Abstract Operations === function getMethod(obj, key) { var value = obj[key]; if (value == null) return undefined; if (typeof value !== 'function') throw new TypeError(value + ' is not a function'); return value; } function getSpecies(obj) { var ctor = obj.constructor; if (ctor !== undefined) { ctor = ctor[SymbolSpecies]; if (ctor === null) { ctor = undefined; } } return ctor !== undefined ? ctor : Observable; } function isObservable(x) { return x instanceof Observable; // SPEC: Brand check } function hostReportError(e) { if (hostReportError.log) { hostReportError.log(e); } else { setTimeout(function () { throw e; }); } } function enqueue(fn) { Promise.resolve().then(function () { try { fn(); } catch (e) { hostReportError(e); } }); } function cleanupSubscription(subscription) { var cleanup = subscription._cleanup; if (cleanup === undefined) return; subscription._cleanup = undefined; if (!cleanup) { return; } try { if (typeof cleanup === 'function') { cleanup(); } else { var unsubscribe = getMethod(cleanup, 'unsubscribe'); if (unsubscribe) { unsubscribe.call(cleanup); } } } catch (e) { hostReportError(e); } } function closeSubscription(subscription) { subscription._observer = undefined; subscription._queue = undefined; subscription._state = 'closed'; } function flushSubscription(subscription) { var queue = subscription._queue; if (!queue) { return; } subscription._queue = undefined; subscription._state = 'ready'; for (var i = 0; i < queue.length; ++i) { notifySubscription(subscription, queue[i].type, queue[i].value); if (subscription._state === 'closed') break; } } function notifySubscription(subscription, type, value) { subscription._state = 'running'; var observer = subscription._observer; try { var m = getMethod(observer, type); switch (type) { case 'next': if (m) m.call(observer, value); break; case 'error': closeSubscription(subscription); if (m) m.call(observer, value);else throw value; break; case 'complete': closeSubscription(subscription); if (m) m.call(observer); break; } } catch (e) { hostReportError(e); } if (subscription._state === 'closed') cleanupSubscription(subscription);else if (subscription._state === 'running') subscription._state = 'ready'; } function onNotify(subscription, type, value) { if (subscription._state === 'closed') return; if (subscription._state === 'buffering') { subscription._queue.push({ type: type, value: value }); return; } if (subscription._state !== 'ready') { subscription._state = 'buffering'; subscription._queue = [{ type: type, value: value }]; enqueue(function () { return flushSubscription(subscription); }); return; } notifySubscription(subscription, type, value); } var Subscription = function () { function Subscription(observer, subscriber) { _classCallCheck(this, Subscription); // ASSERT: observer is an object // ASSERT: subscriber is callable this._cleanup = undefined; this._observer = observer; this._queue = undefined; this._state = 'initializing'; var subscriptionObserver = new SubscriptionObserver(this); try { this._cleanup = subscriber.call(undefined, subscriptionObserver); } catch (e) { subscriptionObserver.error(e); } if (this._state === 'initializing') this._state = 'ready'; } _createClass(Subscription, [{ key: 'unsubscribe', value: function unsubscribe() { if (this._state !== 'closed') { closeSubscription(this); cleanupSubscription(this); } } }, { key: 'closed', get: function () { return this._state === 'closed'; } }]); return Subscription; }(); var SubscriptionObserver = function () { function SubscriptionObserver(subscription) { _classCallCheck(this, SubscriptionObserver); this._subscription = subscription; } _createClass(SubscriptionObserver, [{ key: 'next', value: function next(value) { onNotify(this._subscription, 'next', value); } }, { key: 'error', value: function error(value) { onNotify(this._subscription, 'error', value); } }, { key: 'complete', value: function complete() { onNotify(this._subscription, 'complete'); } }, { key: 'closed', get: function () { return this._subscription._state === 'closed'; } }]); return SubscriptionObserver; }(); var Observable = exports.Observable = function () { function Observable(subscriber) { _classCallCheck(this, Observable); if (!(this instanceof Observable)) throw new TypeError('Observable cannot be called as a function'); if (typeof subscriber !== 'function') throw new TypeError('Observable initializer must be a function'); this._subscriber = subscriber; } _createClass(Observable, [{ key: 'subscribe', value: function subscribe(observer) { if (typeof observer !== 'object' || observer === null) { observer = { next: observer, error: arguments[1], complete: arguments[2] }; } return new Subscription(observer, this._subscriber); } }, { key: 'forEach', value: function forEach(fn) { var _this = this; return new Promise(function (resolve, reject) { if (typeof fn !== 'function') { reject(new TypeError(fn + ' is not a function')); return; } function done() { subscription.unsubscribe(); resolve(); } var subscription = _this.subscribe({ next: function (value) { try { fn(value, done); } catch (e) { reject(e); subscription.unsubscribe(); } }, error: reject, complete: resolve }); }); } }, { key: 'map', value: function map(fn) { var _this2 = this; if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function'); var C = getSpecies(this); return new C(function (observer) { return _this2.subscribe({ next: function (value) { try { value = fn(value); } catch (e) { return observer.error(e); } observer.next(value); }, error: function (e) { observer.error(e); }, complete: function () { observer.complete(); } }); }); } }, { key: 'filter', value: function filter(fn) { var _this3 = this; if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function'); var C = getSpecies(this); return new C(function (observer) { return _this3.subscribe({ next: function (value) { try { if (!fn(value)) return; } catch (e) { return observer.error(e); } observer.next(value); }, error: function (e) { observer.error(e); }, complete: function () { observer.complete(); } }); }); } }, { key: 'reduce', value: function reduce(fn) { var _this4 = this; if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function'); var C = getSpecies(this); var hasSeed = arguments.length > 1; var hasValue = false; var seed = arguments[1]; var acc = seed; return new C(function (observer) { return _this4.subscribe({ next: function (value) { var first = !hasValue; hasValue = true; if (!first || hasSeed) { try { acc = fn(acc, value); } catch (e) { return observer.error(e); } } else { acc = value; } }, error: function (e) { observer.error(e); }, complete: function () { if (!hasValue && !hasSeed) return observer.error(new TypeError('Cannot reduce an empty sequence')); observer.next(acc); observer.complete(); } }); }); } }, { key: 'concat', value: function concat() { var _this5 = this; for (var _len = arguments.length, sources = Array(_len), _key = 0; _key < _len; _key++) { sources[_key] = arguments[_key]; } var C = getSpecies(this); return new C(function (observer) { var subscription = void 0; var index = 0; function startNext(next) { subscription = next.subscribe({ next: function (v) { observer.next(v); }, error: function (e) { observer.error(e); }, complete: function () { if (index === sources.length) { subscription = undefined; observer.complete(); } else { startNext(C.from(sources[index++])); } } }); } startNext(_this5); return function () { if (subscription) { subscription.unsubscribe(); subscription = undefined; } }; }); } }, { key: 'flatMap', value: function flatMap(fn) { var _this6 = this; if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function'); var C = getSpecies(this); return new C(function (observer) { var subscriptions = []; var outer = _this6.subscribe({ next: function (value) { if (fn) { try { value = fn(value); } catch (e) { return observer.error(e); } } var inner = C.from(value).subscribe({ next: function (value) { observer.next(value); }, error: function (e) { observer.error(e); }, complete: function () { var i = subscriptions.indexOf(inner); if (i >= 0) subscriptions.splice(i, 1); completeIfDone(); } }); subscriptions.push(inner); }, error: function (e) { observer.error(e); }, complete: function () { completeIfDone(); } }); function completeIfDone() { if (outer.closed && subscriptions.length === 0) observer.complete(); } return function () { subscriptions.forEach(function (s) { return s.unsubscribe(); }); outer.unsubscribe(); }; }); } }, { key: SymbolObservable, value: function () { return this; } }], [{ key: 'from', value: function from(x) { var C = typeof this === 'function' ? this : Observable; if (x == null) throw new TypeError(x + ' is not an object'); var method = getMethod(x, SymbolObservable); if (method) { var observable = method.call(x); if (Object(observable) !== observable) throw new TypeError(observable + ' is not an object'); if (isObservable(observable) && observable.constructor === C) return observable; return new C(function (observer) { return observable.subscribe(observer); }); } if (hasSymbol('iterator')) { method = getMethod(x, SymbolIterator); if (method) { return new C(function (observer) { enqueue(function () { if (observer.closed) return; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = method.call(x)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var item = _step.value; observer.next(item); if (observer.closed) return; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } observer.complete(); }); }); } } if (Array.isArray(x)) { return new C(function (observer) { enqueue(function () { if (observer.closed) return; for (var i = 0; i < x.length; ++i) { observer.next(x[i]); if (observer.closed) return; } observer.complete(); }); }); } throw new TypeError(x + ' is not observable'); } }, { key: 'of', value: function of() { for (var _len2 = arguments.length, items = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { items[_key2] = arguments[_key2]; } var C = typeof this === 'function' ? this : Observable; return new C(function (observer) { enqueue(function () { if (observer.closed) return; for (var i = 0; i < items.length; ++i) { observer.next(items[i]); if (observer.closed) return; } observer.complete(); }); }); } }, { key: SymbolSpecies, get: function () { return this; } }]); return Observable; }(); if (hasSymbols()) { Object.defineProperty(Observable, Symbol('extensions'), { value: { symbol: SymbolObservable, hostReportError: hostReportError }, configurable: true }); } }); unwrapExports(Observable_1); var Observable_2 = Observable_1.Observable; var zenObservable = Observable_1.Observable; /* tslint:disable */ var Observable$1 = zenObservable; var __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __assign$1 = (undefined && undefined.__assign) || function () { __assign$1 = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign$1.apply(this, arguments); }; function getOperationName(doc) { return (doc.definitions .filter(function (definition) { return definition.kind === 'OperationDefinition' && definition.name; }) .map(function (x) { return x.name.value; })[0] || null); } function _typeof(obj) { 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); } /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * strict */ /** * Used to print values in error messages. */ function inspect(value) { switch (_typeof(value)) { case 'string': return JSON.stringify(value); case 'function': return value.name ? "[function ".concat(value.name, "]") : '[function]'; case 'object': if (value) { if (typeof value.inspect === 'function') { return value.inspect(); } else if (Array.isArray(value)) { return '[' + value.map(inspect).join(', ') + ']'; } var properties = Object.keys(value).map(function (k) { return "".concat(k, ": ").concat(inspect(value[k])); }).join(', '); return properties ? '{ ' + properties + ' }' : '{}'; } return String(value); default: return String(value); } } /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * strict */ var QueryDocumentKeys = { Name: [], Document: ['definitions'], OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], Variable: ['name'], SelectionSet: ['selections'], Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], Argument: ['name', 'value'], FragmentSpread: ['name', 'directives'], InlineFragment: ['typeCondition', 'directives', 'selectionSet'], FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed // or removed in the future. 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], IntValue: [], FloatValue: [], StringValue: [], BooleanValue: [], NullValue: [], EnumValue: [], ListValue: ['values'], ObjectValue: ['fields'], ObjectField: ['name', 'value'], Directive: ['name', 'arguments'], NamedType: ['name'], ListType: ['type'], NonNullType: ['type'], SchemaDefinition: ['directives', 'operationTypes'], OperationTypeDefinition: ['type'], ScalarTypeDefinition: ['description', 'name', 'directives'], ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'], UnionTypeDefinition: ['description', 'name', 'directives', 'types'], EnumTypeDefinition: ['description', 'name', 'directives', 'values'], EnumValueDefinition: ['description', 'name', 'directives'], InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], SchemaExtension: ['directives', 'operationTypes'], ScalarTypeExtension: ['name', 'directives'], ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], InterfaceTypeExtension: ['name', 'directives', 'fields'], UnionTypeExtension: ['name', 'directives', 'types'], EnumTypeExtension: ['name', 'directives', 'values'], InputObjectTypeExtension: ['name', 'directives', 'fields'] }; var BREAK = {}; /** * visit() will walk through an AST using a depth first traversal, calling * the visitor's enter function at each node in the traversal, and calling the * leave function after visiting that node and all of its child nodes. * * By returning different values from the enter and leave functions, the * behavior of the visitor can be altered, including skipping over a sub-tree of * the AST (by returning false), editing the AST by returning a value or null * to remove the value, or to stop the whole traversal by returning BREAK. * * When using visit() to edit an AST, the original AST will not be modified, and * a new version of the AST with the changes applied will be returned from the * visit function. * * const editedAST = visit(ast, { * enter(node, key, parent, path, ancestors) { * // @return * // undefined: no action * // false: skip visiting this node * // visitor.BREAK: stop visiting altogether * // null: delete this node * // any value: replace this node with the returned value * }, * leave(node, key, parent, path, ancestors) { * // @return * // undefined: no action * // false: no action * // visitor.BREAK: stop visiting altogether * // null: delete this node * // any value: replace this node with the returned value * } * }); * * Alternatively to providing enter() and leave() functions, a visitor can * instead provide functions named the same as the kinds of AST nodes, or * enter/leave visitors at a named key, leading to four permutations of * visitor API: * * 1) Named visitors triggered when entering a node a specific kind. * * visit(ast, { * Kind(node) { * // enter the "Kind" node * } * }) * * 2) Named visitors that trigger upon entering and leaving a node of * a specific kind. * * visit(ast, { * Kind: { * enter(node) { * // enter the "Kind" node * } * leave(node) { * // leave the "Kind" node * } * } * }) * * 3) Generic visitors that trigger upon entering and leaving any node. * * visit(ast, { * enter(node) { * // enter any node * }, * leave(node) { * // leave any node * } * }) * * 4) Parallel visitors for entering and leaving nodes of a specific kind. * * visit(ast, { * enter: { * Kind(node) { * // enter the "Kind" node * } * }, * leave: { * Kind(node) { * // leave the "Kind" node * } * } * }) */ function visit(root, visitor) { var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys; /* eslint-disable no-undef-init */ var stack = undefined; var inArray = Array.isArray(root); var keys = [root]; var index = -1; var edits = []; var node = undefined; var key = undefined; var parent = undefined; var path = []; var ancestors = []; var newRoot = root; /* eslint-enable no-undef-init */ do { index++; var isLeaving = index === keys.length; var isEdited = isLeaving && edits.length !== 0; if (isLeaving) { key = ancestors.length === 0 ? undefined : path[path.length - 1]; node = parent; parent = ancestors.pop(); if (isEdited) { if (inArray) { node = node.slice(); } else { var clone = {}; for (var k in node) { if (node.hasOwnProperty(k)) { clone[k] = node[k]; } } node = clone; } var editOffset = 0; for (var ii = 0; ii < edits.length; ii++) { var editKey = edits[ii][0]; var editValue = edits[ii][1]; if (inArray) { editKey -= editOffset; } if (inArray && editValue === null) { node.splice(editKey, 1); editOffset++; } else { node[editKey] = editValue; } } } index = stack.index; keys = stack.keys; edits = stack.edits; inArray = stack.inArray; stack = stack.prev; } else { key = parent ? inArray ? index : keys[index] : undefined; node = parent ? parent[key] : newRoot; if (node === null || node === undefined) { continue; } if (parent) { path.push(key); } } var result = void 0; if (!Array.isArray(node)) { if (!isNode(node)) { throw new Error('Invalid AST Node: ' + inspect(node)); } var visitFn = getVisitFn(visitor, node.kind, isLeaving); if (visitFn) { result = visitFn.call(visitor, node, key, parent, path, ancestors); if (result === BREAK) { break; } if (result === false) { if (!isLeaving) { path.pop(); continue; } } else if (result !== undefined) { edits.push([key, result]); if (!isLeaving) { if (isNode(result)) { node = result; } else { path.pop(); continue; } } } } } if (result === undefined && isEdited) { edits.push([key, node]); } if (isLeaving) { path.pop(); } else { stack = { inArray: inArray, index: index, keys: keys, edits: edits, prev: stack }; inArray = Array.isArray(node); keys = inArray ? node : visitorKeys[node.kind] || []; index = -1; edits = []; if (parent) { ancestors.push(parent); } parent = node; } } while (stack !== undefined); if (edits.length !== 0) { newRoot = edits[edits.length - 1][1]; } return newRoot; } function isNode(maybeNode) { return Boolean(maybeNode && typeof maybeNode.kind === 'string'); } /** * Creates a new visitor instance which maintains a provided TypeInfo instance * along with visiting visitor. */ function visitWithTypeInfo(typeInfo, visitor) { return { enter: function enter(node) { typeInfo.enter(node); var fn = getVisitFn(visitor, node.kind, /* isLeaving */ false); if (fn) { var result = fn.apply(visitor, arguments); if (result !== undefined) { typeInfo.leave(node); if (isNode(result)) { typeInfo.enter(result); } } return result; } }, leave: function leave(node) { var fn = getVisitFn(visitor, node.kind, /* isLeaving */ true); var result; if (fn) { result = fn.apply(visitor, arguments); } typeInfo.leave(node); return result; } }; } /** * Given a visitor instance, if it is leaving or not, and a node kind, return * the function the visitor runtime should call. */ function getVisitFn(visitor, kind, isLeaving) { var kindVisitor = visitor[kind]; if (kindVisitor) { if (!isLeaving && typeof kindVisitor === 'function') { // { Kind() {} } return kindVisitor; } var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter; if (typeof kindSpecificVisitor === 'function') { // { Kind: { enter() {}, leave() {} } } return kindSpecificVisitor; } } else { var specificVisitor = isLeaving ? visitor.leave : visitor.enter; if (specificVisitor) { if (typeof specificVisitor === 'function') { // { enter() {}, leave() {} } return specificVisitor; } var specificKindVisitor = specificVisitor[kind]; if (typeof specificKindVisitor === 'function') { // { enter: { Kind() {} }, leave: { Kind() {} } } return specificKindVisitor; } } } } /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * Converts an AST into a string, using one set of reasonable * formatting rules. */ function print(ast) { return visit(ast, { leave: printDocASTReducer }); } var printDocASTReducer = { Name: function Name(node) { return node.value; }, Variable: function Variable(node) { return '$' + node.name; }, // Document Document: function Document(node) { return join(node.definitions, '\n\n') + '\n'; }, OperationDefinition: function OperationDefinition(node) { var op = node.operation; var name = node.name; var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); var directives = join(node.directives, ' '); var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use // the query short form. return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' '); }, VariableDefinition: function VariableDefinition(_ref) { var variable = _ref.variable, type = _ref.type, defaultValue = _ref.defaultValue, directives = _ref.directives; return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')); }, SelectionSet: function SelectionSet(_ref2) { var selections = _ref2.selections; return block(selections); }, Field: function Field(_ref3) { var alias = _ref3.alias, name = _ref3.name, args = _ref3.arguments, directives = _ref3.directives, selectionSet = _ref3.selectionSet; return join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' '); }, Argument: function Argument(_ref4) { var name = _ref4.name, value = _ref4.value; return name + ': ' + value; }, // Fragments FragmentSpread: function FragmentSpread(_ref5) { var name = _ref5.name, directives = _ref5.directives; return '...' + name + wrap(' ', join(directives, ' ')); }, InlineFragment: function InlineFragment(_ref6) { var typeCondition = _ref6.typeCondition, directives = _ref6.directives, selectionSet = _ref6.selectionSet; return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' '); }, FragmentDefinition: function FragmentDefinition(_ref7) { var name = _ref7.name, typeCondition = _ref7.typeCondition, variableDefinitions = _ref7.variableDefinitions, directives = _ref7.directives, selectionSet = _ref7.selectionSet; return (// Note: fragment variable definitions are experimental and may be changed // or removed in the future. "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet ); }, // Value IntValue: function IntValue(_ref8) { var value = _ref8.value; return value; }, FloatValue: function FloatValue(_ref9) { var value = _ref9.value; return value; }, StringValue: function StringValue(_ref10, key) { var value = _ref10.value, isBlockString = _ref10.block; return isBlockString ? printBlockString(value, key === 'description') : JSON.stringify(value); }, BooleanValue: function BooleanValue(_ref11) { var value = _ref11.value; return value ? 'true' : 'false'; }, NullValue: function NullValue() { return 'null'; }, EnumValue: function EnumValue(_ref12) { var value = _ref12.value; return value; }, ListValue: function ListValue(_ref13) { var values = _ref13.values; return '[' + join(values, ', ') + ']'; }, ObjectValue: function ObjectValue(_ref14) { var fields = _ref14.fields; return '{' + join(fields, ', ') + '}'; }, ObjectField: function ObjectField(_ref15) { var name = _ref15.name, value = _ref15.value; return name + ': ' + value; }, // Directive Directive: function Directive(_ref16) { var name = _ref16.name, args = _ref16.arguments; return '@' + name + wrap('(', join(args, ', '), ')'); }, // Type NamedType: function NamedType(_ref17) { var name = _ref17.name; return name; }, ListType: function ListType(_ref18) { var type = _ref18.type; return '[' + type + ']'; }, NonNullType: function NonNullType(_ref19) { var type = _ref19.type; return type + '!'; }, // Type System Definitions SchemaDefinition: function SchemaDefinition(_ref20) { var directives = _ref20.directives, operationTypes = _ref20.operationTypes; return join(['schema', join(directives, ' '), block(operationTypes)], ' '); }, OperationTypeDefinition: function OperationTypeDefinition(_ref21) { var operation = _ref21.operation, type = _ref21.type; return operation + ': ' + type; }, ScalarTypeDefinition: addDescription(function (_ref22) { var name = _ref22.name, directives = _ref22.directives; return join(['scalar', name, join(directives, ' ')], ' '); }), ObjectTypeDefinition: addDescription(function (_ref23) { var name = _ref23.name, interfaces = _ref23.interfaces, directives = _ref23.directives, fields = _ref23.fields; return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); }), FieldDefinition: addDescription(function (_ref24) { var name = _ref24.name, args = _ref24.arguments, type = _ref24.type, directives = _ref24.directives; return name + (args.every(function (arg) { return arg.indexOf('\n') === -1; }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ': ' + type + wrap(' ', join(directives, ' ')); }), InputValueDefinition: addDescription(function (_ref25) { var name = _ref25.name, type = _ref25.type, defaultValue = _ref25.defaultValue, directives = _ref25.directives; return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' '); }), InterfaceTypeDefinition: addDescription(function (_ref26) { var name = _ref26.name, directives = _ref26.directives, fields = _ref26.fields; return join(['interface', name, join(directives, ' '), block(fields)], ' '); }), UnionTypeDefinition: addDescription(function (_ref27) { var name = _ref27.name, directives = _ref27.directives, types = _ref27.types; return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); }), EnumTypeDefinition: addDescription(function (_ref28) { var name = _ref28.name, directives = _ref28.directives, values = _ref28.values; return join(['enum', name, join(directives, ' '), block(values)], ' '); }), EnumValueDefinition: addDescription(function (_ref29) { var name = _ref29.name, directives = _ref29.directives; return join([name, join(directives, ' ')], ' '); }), InputObjectTypeDefinition: addDescription(function (_ref30) { var name = _ref30.name, directives = _ref30.directives, fields = _ref30.fields; return join(['input', name, join(directives, ' '), block(fields)], ' '); }), DirectiveDefinition: addDescription(function (_ref31) { var name = _ref31.name, args = _ref31.arguments, locations = _ref31.locations; return 'directive @' + name + (args.every(function (arg) { return arg.indexOf('\n') === -1; }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ' on ' + join(locations, ' | '); }), SchemaExtension: function SchemaExtension(_ref32) { var directives = _ref32.directives, operationTypes = _ref32.operationTypes; return join(['extend schema', join(directives, ' '), block(operationTypes)], ' '); }, ScalarTypeExtension: function ScalarTypeExtension(_ref33) { var name = _ref33.name, directives = _ref33.directives; return join(['extend scalar', name, join(directives, ' ')], ' '); }, ObjectTypeExtension: function ObjectTypeExtension(_ref34) { var name = _ref34.name, interfaces = _ref34.interfaces, directives = _ref34.directives, fields = _ref34.fields; return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); }, InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) { var name = _ref35.name, directives = _ref35.directives, fields = _ref35.fields; return join(['extend interface', name, join(directives, ' '), block(fields)], ' '); }, UnionTypeExtension: function UnionTypeExtension(_ref36) { var name = _ref36.name, directives = _ref36.directives, types = _ref36.types; return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); }, EnumTypeExtension: function EnumTypeExtension(_ref37) { var name = _ref37.name, directives = _ref37.directives, values = _ref37.values; return join(['extend enum', name, join(directives, ' '), block(values)], ' '); }, InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) { var name = _ref38.name, directives = _ref38.directives, fields = _ref38.fields; return join(['extend input', name, join(directives, ' '), block(fields)], ' '); } }; function addDescription(cb) { return function (node) { return join([node.description, cb(node)], '\n'); }; } /** * Given maybeArray, print an empty string if it is null or empty, otherwise * print all items together separated by separator if provided */ function join(maybeArray, separator) { return maybeArray ? maybeArray.filter(function (x) { return x; }).join(separator || '') : ''; } /** * Given array, print each item on its own line, wrapped in an * indented "{ }" block. */ function block(array) { return array && array.length !== 0 ? '{\n' + indent(join(array, '\n')) + '\n}' : ''; } /** * If maybeString is not null or empty, then wrap with start and end, otherwise * print an empty string. */ function wrap(start, maybeString, end) { return maybeString ? start + maybeString + (end || '') : ''; } function indent(maybeString) { return maybeString && ' ' + maybeString.replace(/\n/g, '\n '); } /** * Print a block string in the indented block form by adding a leading and * trailing blank line. However, if a block string starts with whitespace and is * a single-line, adding a leading blank line would strip that whitespace. */ function printBlockString(value, isD